From 74c7cb7e700b5a8f90dcb8c2a9efe69418b6e2b0 Mon Sep 17 00:00:00 2001 From: Edwin Amirian Date: Tue, 11 Aug 2026 07:44:37 -0700 Subject: [PATCH] Add P2D LIVE conflict and correction proof --- .github/workflows/ci.yml | 10 + CHANGELOG.md | 21 + README.md | 46 +- ROADMAP.md | 20 +- adapters/federal_register_source/README.md | 8 + .../__init__.py | 58 + .../planetary_defense_adapter.py | 416 +++++ .../tests/test_planetary_defense_adapter.py | 173 ++ ...p2d-live-conflict-correction-2026-08-11.md | 92 + ...live-conflict-correction-work-packet-v1.md | 78 + ...telligence_p2d_live_conflict_correction.py | 63 + ...rld_intelligence_planetary_defense_pack.py | 38 + .../p2d_live_conflict_correction_input.json | 163 ++ .../conformance/p2d_live_expected.json | 62 + .../manifest.json | 112 ++ .../modules/detection.json | 31 + .../modules/epistemic_status.json | 68 + .../modules/ontology.json | 25 + .../modules/personas.json | 27 + .../modules/source_mapping.json | 106 ++ .../modules/synthesis.json | 24 + pyproject.toml | 5 + scripts/p2d_live_conflict_correction.py | 1560 +++++++++++++++++ tests/test_release_contract.py | 2 + 24 files changed, 3196 insertions(+), 12 deletions(-) create mode 100644 adapters/federal_register_source/src/ace_world_federal_register_source/planetary_defense_adapter.py create mode 100644 adapters/federal_register_source/tests/test_planetary_defense_adapter.py create mode 100644 docs/audits/world-intelligence-p2d-live-conflict-correction-2026-08-11.md create mode 100644 docs/design/world-intelligence-p2d-live-conflict-correction-work-packet-v1.md create mode 100644 domain_packs/tests/test_world_intelligence_p2d_live_conflict_correction.py create mode 100644 domain_packs/tests/test_world_intelligence_planetary_defense_pack.py create mode 100644 domain_packs/world_intelligence_planetary_defense/conformance/p2d_live_conflict_correction_input.json create mode 100644 domain_packs/world_intelligence_planetary_defense/conformance/p2d_live_expected.json create mode 100644 domain_packs/world_intelligence_planetary_defense/manifest.json create mode 100644 domain_packs/world_intelligence_planetary_defense/modules/detection.json create mode 100644 domain_packs/world_intelligence_planetary_defense/modules/epistemic_status.json create mode 100644 domain_packs/world_intelligence_planetary_defense/modules/ontology.json create mode 100644 domain_packs/world_intelligence_planetary_defense/modules/personas.json create mode 100644 domain_packs/world_intelligence_planetary_defense/modules/source_mapping.json create mode 100644 domain_packs/world_intelligence_planetary_defense/modules/synthesis.json create mode 100644 scripts/p2d_live_conflict_correction.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f60423..cdd0106 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -142,6 +142,7 @@ jobs: world = "domain_packs/world_intelligence/" ai = "domain_packs/world_intelligence_ai/" + planetary = "domain_packs/world_intelligence_planetary_defense/" federal = "domain_packs/world_intelligence_federal_register/" monitor = "domain_packs/world_intelligence_federal_register_monitor/" expected_payload = sorted( @@ -180,6 +181,15 @@ jobs: ai + "modules/source_mapping.json", ai + "modules/synthesis.json", ai + "conformance/ai_command_center_live_input.json", + planetary + "manifest.json", + planetary + "modules/detection.json", + planetary + "modules/epistemic_status.json", + planetary + "modules/ontology.json", + planetary + "modules/personas.json", + planetary + "modules/source_mapping.json", + planetary + "modules/synthesis.json", + planetary + "conformance/p2d_live_conflict_correction_input.json", + planetary + "conformance/p2d_live_expected.json", federal + "manifest.json", federal + "modules/ontology.json", federal + "modules/source_mapping.json", diff --git a/CHANGELOG.md b/CHANGELOG.md index d5e8fb2..c5b02eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,27 @@ noted here only where the boundary between them changes. ## Unreleased +### Added + +- **P2D LIVE conflict and correction.** Four exact NASA/ESA planetary-defense publications become + LIVE Observations, one dated cross-source divergence and two same-source downward-revision Shifts, + three routed Signals, immutable historical and corrected Cases, and cited Reality Briefs with + family-aware per-claim epistemic status. +- **Additive LIVE supersession impact.** Two explicit same-source supersession assertions append + exact dependency projections over the historical closure. Each reaches five resources and seven + Brief claims, discloses two unaffected resources, and leaves the historical Brief byte-identical. +- **Exact official-source connector profiles.** The separately packaged connector now validates the + four reviewed NASA/ESA canonical pages under recorded, network-free transport. Eighteen focused + adapter cases cover accepted material and fail-closed boundary violations. + +### Boundaries + +- The new six-module pack is inert JSON only. The P2D proof contains 44 LIVE records and zero + PREPARED records, performs no network request, and creates no action, delivery, publication, + persuasion, monitor, or schedule. +- NASA and ESA are independent claimant publication roots, not proven independent measurements. + Same-lineage supersessions collapse to their predecessor and do not manufacture corroboration. + ### Repository consistency - Added the full Apache-2.0 license, NOTICE, security policy, contribution guide, Code of Conduct, diff --git a/README.md b/README.md index af23433..f69c133 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,30 @@ The accepted stable identities are `pack_ir:0679116c6b5e02cd021b085ba2d80cf2`, `brief:d7d240147e48c3aef6a4a8e7ec481121`. The proof store contains 16 LIVE records and zero PREPARED records; the synthetic PREPARED packet remains byte-frozen and is not reused. +P2D adds the first complete LIVE conflict-and-correction packet. A separate inert six-module pack +maps four dated publications about asteroid 2024 YR4 from two official claimant roots: NASA's 2.3% +and later 0.004% Earth-impact estimates, and ESA's 1.8% and later 0.001% estimates. Recorded, +network-free captures become four exact LIVE source transactions. The configured numeric bridge +first routes the dated NASA/ESA estimate divergence into a historical Case and two-citation Reality +Brief, then routes both same-source downward revisions into a corrected Case and four-citation +Brief. + +The later records do not rewrite the earlier ones. Two explicit LIVE supersession Observations name +the exact same-source predecessors, and two additive impact projections enumerate five affected +resources and seven affected historical Brief claims apiece while disclosing two unaffected +resources. Impact means dependency, not falsehood. The original Brief reopens byte-identically +after both corrections. Its status projection has two source families; the corrected projection has +four raw-observation roots, but each same-lineage supersession collapses to its predecessor and adds +no corroboration. The corrected `corroborated` claim is supported by exactly two claimant families, +NASA and ESA—not by treating before/after records as independent. + +The accepted P2D identities are `pack_ir:bb400cc0652622b43c01504e651110e0`, historical +`brief:c3549af0262b100ca65024ee19cbae6e`, corrected +`brief:806d69d8e41f83f93ee3dc10f58f0d16`, and corrected status projection +`brief_derivation_family_status_projection:2acb48dd15e625c4b729ecef484b0209`. The proof store +contains 44 LIVE records and zero PREPARED records. Separate official publication roots do not prove +independent measurements: both agencies describe a shared international observation ecosystem. + P2C2 completes that sensing path across the Core + Intelligence + Domain boundaries. A new declarative monitor pack admits two exact FCC records — document `2026-15932` published August 6 and document `2026-16197` published August 7 — as successive LIVE snapshots of one stable monitor @@ -274,11 +298,11 @@ With `$REPO`, `$ACE`, `$PYTHONPATH`, and `$PY` exported as in [Develop from a source checkout](#develop-from-a-source-checkout): ```bash -# Complete domain suite, including every frozen packet, P2C2, and the AI command-center journey: 87 passed +# Complete domain suite, including P2C2, AI Command Center, and P2D correction: 90 passed export PYTHONPATH="$PYTHONPATH:$ACE/adapters/reference_workspace_action/src" $PY -m pytest -q -# Connector fail-closed unit suite: 62 passed +# Connector fail-closed unit suite: 80 passed $PY -m pytest adapters/federal_register_source/tests -q # Individual acceptance harnesses @@ -290,6 +314,7 @@ $PY scripts/p2b_status_case_brief.py $PY scripts/p2b_independent_case_brief.py $PY scripts/p2c_federal_register_live_acceptance.py $PY -m scripts.ai_command_center_live_acceptance +$PY -m scripts.p2d_live_conflict_correction # Complete official-record -> Shift -> Signal -> Brief -> reviewed export journey WORKSPACE=$(mktemp -d) @@ -303,7 +328,7 @@ P2C2 action test runs when the independently packaged Core reference adapter is uv sync --frozen --no-install-project uv run --no-sync python -m pytest # released + candidate-compatible gates uv run --no-sync python -m pytest tests/test_release_contract.py # publishable-identity gate -uv run --no-sync python -m pytest adapters/federal_register_source/tests # connector: 26 passed +uv run --no-sync python -m pytest adapters/federal_register_source/tests # connector: 80 passed ``` The released 0.9.0 baseline, measured with public `ace-core==0.5.0` from PyPI and the independently @@ -312,6 +337,9 @@ suite and `26 passed` for the connector. With the AI command-center candidate in baseline, the same environment passes `87` domain and `62` connector tests. The public demo reproduces `case:412426eee708d56f6bda931ccf9e5d8b` and `brief:25d8232c9bfa27050bdcb160fb75f06c`, and its two artifacts are byte-identical across runs. +With P2D integrated, the source-tree candidate passes `90` domain tests, `80` connector tests, and +all `7` release-contract tests. Its locally built wheel contains exactly 55 JSON resources, nine +from the planetary-defense pack, and no executable code. The exact identities, negative cases, and artifact proofs are recorded in [`docs/audits/world-intelligence-p2a-2026-08-06.md`](docs/audits/world-intelligence-p2a-2026-08-06.md) @@ -333,6 +361,8 @@ The complete governed product-journey evidence is recorded in [`docs/audits/world-intelligence-p2c2-governed-reality-brief-2026-08-10.md`](docs/audits/world-intelligence-p2c2-governed-reality-brief-2026-08-10.md). The two-lineage LIVE Shift → Signal → Case → cited Brief proof is recorded in [`docs/audits/world-intelligence-ai-command-center-live-2026-08-10.md`](docs/audits/world-intelligence-ai-command-center-live-2026-08-10.md). +The LIVE conflict, correction, supersession, and per-claim status proof is recorded in +[`docs/audits/world-intelligence-p2d-live-conflict-correction-2026-08-11.md`](docs/audits/world-intelligence-p2d-live-conflict-correction-2026-08-11.md). Release-level scope and evidence are recorded in [`docs/releases/world-intelligence-p2c2-v0.9.0.md`](docs/releases/world-intelligence-p2c2-v0.9.0.md), @@ -355,16 +385,16 @@ content autonomously. Every LIVE capture demonstrated here is one explicitly req read-only retrieval. P2C2's only effect is an explicitly authorized and reviewed create-only local workspace export followed by separate verification and promotion. -Next: exercise P2D multi-source conflict and append-only correction with LIVE inputs while keeping -publication-lineage independence distinct from claimant independence. The packet may not add -publishing, delivery, persuasion, or other external-action authority. +Next: turn one-shot governed sensing into explicit user-owned monitors and subscriptions while +preserving correction visibility, suppression controls, and source-family independence. That work +may not add publishing, delivery, persuasion, or other external-action authority to a Domain Pack. ## Roadmap and project status The [World Intelligence roadmap](ROADMAP.md) owns current domain direction. Detailed packet history remains in [`docs/world-intelligence-roadmap-status-2026-08-06.md`](docs/world-intelligence-roadmap-status-2026-08-06.md), -and release history is in [`CHANGELOG.md`](CHANGELOG.md). The next bounded work is P2D -multi-source conflict/correction with LIVE inputs. It may not add autonomous publishing, delivery, +and release history is in [`CHANGELOG.md`](CHANGELOG.md). The next bounded work is explicit +user-owned monitoring and subscription state. It may not add autonomous publishing, delivery, persuasion, or action authority to a Domain Pack. ## Community and security diff --git a/ROADMAP.md b/ROADMAP.md index 67bbf9c..e06f351 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,13 +16,25 @@ source code into the platform. See the [0.9.0 release record](docs/releases/world-intelligence-p2c2-v0.9.0.md). -## Next — trustworthy live orientation +## Candidate — trustworthy LIVE correction + +- Four dated NASA/ESA publications become exact LIVE Observations over one stable risk-estimate + entity through separately reviewed, recorded official-source adapters. +- A cross-source estimate divergence and two same-source downward revisions produce configured + Shifts, routed Signals, immutable Cases, and cited historical and corrected Reality Briefs. +- Explicit supersession assertions and additive dependency-impact projections preserve earlier + artifacts, exact citations, per-claim epistemic status, claimant-family independence, correction + visibility, and PREPARED/LIVE separation. +- The packet performs no network request, external action, delivery, publication, or monitoring. + +See the [P2D audit](docs/audits/world-intelligence-p2d-live-conflict-correction-2026-08-11.md). + +## Next — user-owned live orientation - Add a separately reviewed, opt-in production transport without bundling it into the Domain Pack. -- Exercise multi-source conflict, correction, and supersession against LIVE admitted records. - Turn one-shot governed sensing into explicit user-owned monitors and subscriptions. -- Preserve source independence, per-claim epistemic status, exact citations, correction visibility, - and PREPARED/LIVE separation. +- Preserve source independence, correction visibility, attention ownership, suppression, and + PREPARED/LIVE separation across repeated sensing windows. ## Later — measured personal and public sensemaking diff --git a/adapters/federal_register_source/README.md b/adapters/federal_register_source/README.md index 8c61e91..7c0a081 100644 --- a/adapters/federal_register_source/README.md +++ b/adapters/federal_register_source/README.md @@ -29,6 +29,14 @@ no White House network transport is enabled by this package. The source is a pub independent of the Federal Register API record, but it is not independent non-government corroboration. +P2D adds exact recorded-transport profiles for two NASA and two ESA planetary-defense pages about +asteroid 2024 YR4. The adapter accepts only the four reviewed canonical URIs, titles, publication +dates, claimant types, target date, and probability statements. Decimal estimates remain exact text +at the capture boundary and are converted to numeric attributes only by the inert source-mapping +declaration. These profiles have no enabled network transport. NASA and ESA are separate official +claimant publication roots; the connector does not claim their underlying observations or models +are independent. + ## License Apache-2.0 under the repository [`LICENSE`](../../LICENSE) and [`NOTICE`](../../NOTICE). diff --git a/adapters/federal_register_source/src/ace_world_federal_register_source/__init__.py b/adapters/federal_register_source/src/ace_world_federal_register_source/__init__.py index 118db88..d53340d 100644 --- a/adapters/federal_register_source/src/ace_world_federal_register_source/__init__.py +++ b/adapters/federal_register_source/src/ace_world_federal_register_source/__init__.py @@ -38,6 +38,36 @@ FederalRegisterNetworkTransportError, OptInFederalRegisterNetworkTransport, ) +from .planetary_defense_adapter import ( + ESA_INITIAL_PROFILE, + ESA_INITIAL_TITLE, + ESA_INITIAL_URI, + ESA_PLANETARY_DEFENCE_IMPLEMENTATION_ID, + ESA_PLANETARY_DEFENCE_PROFILES, + ESA_PLANETARY_DEFENCE_SOURCE_TYPE, + ESA_REVISED_PROFILE, + ESA_REVISED_TITLE, + ESA_REVISED_URI, + NASA_INITIAL_PROFILE, + NASA_INITIAL_TITLE, + NASA_INITIAL_URI, + NASA_PLANETARY_DEFENSE_IMPLEMENTATION_ID, + NASA_PLANETARY_DEFENSE_PROFILES, + NASA_PLANETARY_DEFENSE_SOURCE_TYPE, + NASA_REVISED_PROFILE, + NASA_REVISED_TITLE, + NASA_REVISED_URI, + PLANETARY_DEFENSE_IMPLEMENTATION_VERSION, + PLANETARY_DEFENSE_LOCATOR, + PLANETARY_DEFENSE_OBJECT, + PLANETARY_DEFENSE_TARGET_DATE, + PlanetaryDefensePublicationProfile, + PlanetaryDefenseRetrievalRequest, + PlanetaryDefenseRetrievalResult, + PlanetaryDefenseSourceAdapter, + PlanetaryDefenseSourceAdapterError, + PlanetaryDefenseTransport, +) from .white_house_adapter import ( WHITE_HOUSE_IMPLEMENTATION_ID, WHITE_HOUSE_IMPLEMENTATION_VERSION, @@ -74,10 +104,32 @@ "DEFAULT_DOCUMENT_PROFILE", "DOCUMENT_NUMBER", "DOCUMENT_TITLE", + "ESA_INITIAL_PROFILE", + "ESA_INITIAL_TITLE", + "ESA_INITIAL_URI", + "ESA_PLANETARY_DEFENCE_IMPLEMENTATION_ID", + "ESA_PLANETARY_DEFENCE_PROFILES", + "ESA_PLANETARY_DEFENCE_SOURCE_TYPE", + "ESA_REVISED_PROFILE", + "ESA_REVISED_TITLE", + "ESA_REVISED_URI", "FEDERAL_REGISTER_DOCUMENT_URI", "FEDERAL_REGISTER_LOCATOR", "FEDERAL_REGISTER_SOURCE_TYPE", + "NASA_INITIAL_PROFILE", + "NASA_INITIAL_TITLE", + "NASA_INITIAL_URI", + "NASA_PLANETARY_DEFENSE_IMPLEMENTATION_ID", + "NASA_PLANETARY_DEFENSE_PROFILES", + "NASA_PLANETARY_DEFENSE_SOURCE_TYPE", + "NASA_REVISED_PROFILE", + "NASA_REVISED_TITLE", + "NASA_REVISED_URI", "OFFICIAL_PDF_URI", + "PLANETARY_DEFENSE_IMPLEMENTATION_VERSION", + "PLANETARY_DEFENSE_LOCATOR", + "PLANETARY_DEFENSE_OBJECT", + "PLANETARY_DEFENSE_TARGET_DATE", "WHITE_HOUSE_IMPLEMENTATION_ID", "WHITE_HOUSE_IMPLEMENTATION_VERSION", "WHITE_HOUSE_LINEAGE_ID", @@ -97,6 +149,12 @@ "FederalRegisterSourceAdapterError", "FederalRegisterTransport", "OptInFederalRegisterNetworkTransport", + "PlanetaryDefensePublicationProfile", + "PlanetaryDefenseRetrievalRequest", + "PlanetaryDefenseRetrievalResult", + "PlanetaryDefenseSourceAdapter", + "PlanetaryDefenseSourceAdapterError", + "PlanetaryDefenseTransport", "WhiteHouseAIPolicySourceAdapter", "WhiteHouseRetrievalRequest", "WhiteHouseRetrievalResult", diff --git a/adapters/federal_register_source/src/ace_world_federal_register_source/planetary_defense_adapter.py b/adapters/federal_register_source/src/ace_world_federal_register_source/planetary_defense_adapter.py new file mode 100644 index 0000000..075844f --- /dev/null +++ b/adapters/federal_register_source/src/ace_world_federal_register_source/planetary_defense_adapter.py @@ -0,0 +1,416 @@ +"""Exact read-only adapters for frozen NASA and ESA planetary-defense pages.""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from datetime import UTC, datetime +from html.parser import HTMLParser +from typing import Protocol + +from ace.core import CapabilityArtifactIdentityV1Alpha1, canonical_json, validate_exact_https_uri +from ace.intelligence import CapturedSourceMaterialV1Alpha1, SourceAdapterCaptureRequestV1Alpha1 + +from .adapter import ADAPTER_CAPABILITY, ADAPTER_CONTRACT, _aware_utc, _validated_addresses + +NASA_PLANETARY_DEFENSE_IMPLEMENTATION_ID = "world_nasa_planetary_defense_source" +ESA_PLANETARY_DEFENCE_IMPLEMENTATION_ID = "world_esa_planetary_defence_source" +PLANETARY_DEFENSE_IMPLEMENTATION_VERSION = "0.1.0" +NASA_PLANETARY_DEFENSE_SOURCE_TYPE = "nasa_planetary_defense_publication" +ESA_PLANETARY_DEFENCE_SOURCE_TYPE = "esa_planetary_defence_publication" +PLANETARY_DEFENSE_LOCATOR = "css:article" +PLANETARY_DEFENSE_OBJECT = "2024 YR4" +PLANETARY_DEFENSE_TARGET_DATE = "2032-12-22" +MAX_RESPONSE_BODY_CHARS = 512_000 + +NASA_INITIAL_URI = ( + "https://science.nasa.gov/blogs/planetary-defense/2025/02/07/" + "nasa-continues-to-monitor-orbit-of-near-earth-asteroid-2024-yr4/" +) +NASA_INITIAL_TITLE = "NASA Continues to Monitor Orbit of Near-Earth Asteroid 2024 YR4" +NASA_REVISED_URI = ( + "https://science.nasa.gov/blogs/planetary-defense/2025/02/24/" + "latest-calculations-conclude-asteroid-2024-yr4-now-poses-no-significant-" + "threat-to-earth-in-2032-and-beyond/" +) +NASA_REVISED_TITLE = ( + "Latest Calculations Conclude Asteroid 2024 YR4 Now Poses No Significant Threat to Earth in 2032 and Beyond" +) +ESA_INITIAL_URI = ( + "https://blogs.esa.int/rocketscience/2025/02/06/2024-yr4-flyby-geometry-or-1-8-of-what/comment-page-1/" +) +ESA_INITIAL_TITLE = "2024 YR4 flyby geometry, or 1.8% of What?" +ESA_REVISED_URI = "https://www.esa.int/ESA_Multimedia/Images/2025/02/Asteroid_2024_YR4_impact_risk_rises_and_falls" +ESA_REVISED_TITLE = "Asteroid 2024 YR4 impact risk rises and falls" + + +class PlanetaryDefenseSourceAdapterError(ValueError): + """An official planetary-defense retrieval crossed its reviewed scope.""" + + +@dataclass(frozen=True, slots=True) +class PlanetaryDefensePublicationProfile: + source_type_ref: str + requested_uri: str + title: str + publication_date: str + claimant_org: str + claimant_office: str + probability_percent: float + estimate_status: str + source_lineage_id: str + predecessor_lineage_id: str + assessment_note: str + required_statements: tuple[str, ...] + + +NASA_INITIAL_PROFILE = PlanetaryDefensePublicationProfile( + source_type_ref=NASA_PLANETARY_DEFENSE_SOURCE_TYPE, + requested_uri=NASA_INITIAL_URI, + title=NASA_INITIAL_TITLE, + publication_date="2025-02-07", + claimant_org="NASA", + claimant_office="Planetary Defense Coordination Office / JPL Center for Near-Earth Object Studies", + probability_percent=2.3, + estimate_status="earlier_estimate", + source_lineage_id="nasa_pdco:2024_yr4:2025-02-07", + predecessor_lineage_id="none", + assessment_note=( + "NASA reported a 2.3% Earth-impact probability for 22 December 2032 and said the " + "estimate could change as observations accumulated." + ), + required_statements=("2.3%", "Dec. 22, 2032", "impact probability"), +) +NASA_REVISED_PROFILE = PlanetaryDefensePublicationProfile( + source_type_ref=NASA_PLANETARY_DEFENSE_SOURCE_TYPE, + requested_uri=NASA_REVISED_URI, + title=NASA_REVISED_TITLE, + publication_date="2025-02-24", + claimant_org="NASA", + claimant_office="Planetary Defense Coordination Office / JPL Center for Near-Earth Object Studies", + probability_percent=0.004, + estimate_status="revised_estimate", + source_lineage_id="nasa_pdco:2024_yr4:2025-02-24", + predecessor_lineage_id=NASA_INITIAL_PROFILE.source_lineage_id, + assessment_note=( + "NASA reported an updated 0.004% Earth-impact probability for 22 December 2032 and " + "no significant impact potential for the next century." + ), + required_statements=("0.004%", "Dec. 22, 2032", "no significant potential"), +) +ESA_INITIAL_PROFILE = PlanetaryDefensePublicationProfile( + source_type_ref=ESA_PLANETARY_DEFENCE_SOURCE_TYPE, + requested_uri=ESA_INITIAL_URI, + title=ESA_INITIAL_TITLE, + publication_date="2025-02-06", + claimant_org="ESA", + claimant_office="Planetary Defence Office", + probability_percent=1.8, + estimate_status="earlier_estimate", + source_lineage_id="esa_pdo:2024_yr4:2025-02-06", + predecessor_lineage_id="none", + assessment_note=( + "ESA reported a 1.8% Earth-impact risk for 22 December 2032 and expected the numerical " + "value to evolve with additional observations." + ), + required_statements=("1.8%", "22 December 2032", "expected to evolve"), +) +ESA_REVISED_PROFILE = PlanetaryDefensePublicationProfile( + source_type_ref=ESA_PLANETARY_DEFENCE_SOURCE_TYPE, + requested_uri=ESA_REVISED_URI, + title=ESA_REVISED_TITLE, + publication_date="2025-02-25", + claimant_org="ESA", + claimant_office="Planetary Defence Office", + probability_percent=0.001, + estimate_status="revised_estimate", + source_lineage_id="esa_pdo:2024_yr4:2025-02-25", + predecessor_lineage_id=ESA_INITIAL_PROFILE.source_lineage_id, + assessment_note=( + "ESA reported a 0.001% Earth-impact risk for 22 December 2032, down from estimates " + "published during the preceding days." + ), + required_statements=("0.001%", "22 December 2032", "down from"), +) + +NASA_PLANETARY_DEFENSE_PROFILES = (NASA_INITIAL_PROFILE, NASA_REVISED_PROFILE) +ESA_PLANETARY_DEFENCE_PROFILES = (ESA_INITIAL_PROFILE, ESA_REVISED_PROFILE) + + +@dataclass(frozen=True, slots=True) +class PlanetaryDefenseRetrievalRequest: + source_type_ref: str + requested_uri: str + max_response_chars: int + credentials_allowed: bool = False + redirects_allowed: bool = False + public_network_only: bool = True + dns_rebinding_protection_required: bool = True + + +@dataclass(frozen=True, slots=True) +class PlanetaryDefenseRetrievalResult: + source_type_ref: str + requested_uri: str + effective_uri: str + status_code: int + media_type: str + response_body: str + redirect_chain: tuple[str, ...] + resolved_ip_addresses: tuple[str, ...] + connected_ip_addresses: tuple[str, ...] + dns_rebinding_protection_applied: bool + credentials_used: bool + locator: str + observed_at: datetime + captured_at: datetime + + +class PlanetaryDefenseTransport(Protocol): + async def retrieve( + self, + request: PlanetaryDefenseRetrievalRequest, + ) -> PlanetaryDefenseRetrievalResult: ... + + +def _fail(message: str) -> PlanetaryDefenseSourceAdapterError: + return PlanetaryDefenseSourceAdapterError(message) + + +class _PublicationHTML(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.metadata: dict[str, str] = {} + self.canonical_uri: str | None = None + self.visible: list[str] = [] + self._ignored_depth = 0 + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + values = {key.lower(): value for key, value in attrs if value is not None} + if tag in {"script", "style", "template", "noscript"}: + self._ignored_depth += 1 + if tag == "meta": + key = values.get("property") or values.get("name") + content = values.get("content") + if key in {"og:title", "article:published_time"} and content is not None: + if key in self.metadata: + raise _fail(f"duplicate reviewed planetary-defense metadata: {key}") + self.metadata[key] = content + if tag == "link" and values.get("rel", "").lower() == "canonical": + if self.canonical_uri is not None: + raise _fail("duplicate reviewed planetary-defense canonical URI") + self.canonical_uri = values.get("href") + + def handle_endtag(self, tag: str) -> None: + if tag in {"script", "style", "template", "noscript"} and self._ignored_depth: + self._ignored_depth -= 1 + + def handle_data(self, data: str) -> None: + if not self._ignored_depth: + normalized = " ".join(data.split()) + if normalized: + self.visible.append(normalized) + + +def _canonical_publication_payload( + response_body: object, + *, + profile: PlanetaryDefensePublicationProfile, + max_chars: int, +) -> str: + if type(response_body) is not str: + raise _fail("planetary-defense response body must be text") + if not response_body or len(response_body) > max_chars: + raise _fail("planetary-defense response body exceeded its exact character bound") + parser = _PublicationHTML() + try: + parser.feed(response_body) + parser.close() + except PlanetaryDefenseSourceAdapterError: + raise + except (TypeError, ValueError) as exc: + raise _fail("planetary-defense response is not bounded parseable HTML") from exc + if parser.metadata.get("og:title") != profile.title: + raise _fail("planetary-defense title crossed the exact reviewed publication scope") + published = parser.metadata.get("article:published_time", "") + if not published.startswith(profile.publication_date): + raise _fail("planetary-defense publication date crossed the exact reviewed scope") + if parser.canonical_uri != profile.requested_uri: + raise _fail("planetary-defense canonical URI crossed the exact reviewed scope") + validate_exact_https_uri(parser.canonical_uri, name="canonical_uri") + visible = " ".join(parser.visible) + if any(statement not in visible for statement in profile.required_statements): + raise _fail("planetary-defense page omitted an exact reviewed estimate statement") + return canonical_json( + { + "assessment_note": profile.assessment_note, + "assessment_subject": "earth_impact_probability", + "claimant_office": profile.claimant_office, + "claimant_org": profile.claimant_org, + "estimate_status": profile.estimate_status, + "impact_probability_percent": format(profile.probability_percent, "g"), + "object_name": PLANETARY_DEFENSE_OBJECT, + "predecessor_lineage_id": profile.predecessor_lineage_id, + "publication_date": profile.publication_date, + "source_lineage_id": profile.source_lineage_id, + "source_uri": profile.requested_uri, + "target_date": PLANETARY_DEFENSE_TARGET_DATE, + } + ) + + +class PlanetaryDefenseSourceAdapter: + """Validate one agency's exact reviewed publications and emit inert JSON.""" + + def __init__( + self, + *, + transport: PlanetaryDefenseTransport, + artifact_digest: str, + source_type_ref: str, + ) -> None: + if source_type_ref == NASA_PLANETARY_DEFENSE_SOURCE_TYPE: + implementation_id = NASA_PLANETARY_DEFENSE_IMPLEMENTATION_ID + profiles = NASA_PLANETARY_DEFENSE_PROFILES + elif source_type_ref == ESA_PLANETARY_DEFENCE_SOURCE_TYPE: + implementation_id = ESA_PLANETARY_DEFENCE_IMPLEMENTATION_ID + profiles = ESA_PLANETARY_DEFENCE_PROFILES + else: + raise _fail("unsupported planetary-defense source type") + self.source_type_ref = source_type_ref + self.profiles = {profile.requested_uri: profile for profile in profiles} + self._transport = transport + self.artifact_identity = CapabilityArtifactIdentityV1Alpha1( + capability=ADAPTER_CAPABILITY, + contract=ADAPTER_CONTRACT, + implementation_id=implementation_id, + implementation_version=PLANETARY_DEFENSE_IMPLEMENTATION_VERSION, + artifact_digest=artifact_digest, + ) + self.capture_calls = 0 + + async def capture( + self, + request: SourceAdapterCaptureRequestV1Alpha1, + ) -> CapturedSourceMaterialV1Alpha1: + try: + validated = SourceAdapterCaptureRequestV1Alpha1.model_validate(request.model_dump(mode="python")) + except (AttributeError, TypeError, ValueError) as exc: + raise _fail("source-adapter request failed exact public-contract revalidation") from exc + if validated.adapter_artifact != self.artifact_identity: + raise _fail("source-adapter request names a different installed artifact") + if validated.source_type_ref != self.source_type_ref: + raise _fail("source-adapter request names a different claimant source type") + profile = self.profiles.get(validated.requested_uri) + if profile is None: + raise _fail("source-adapter request crossed the exact reviewed URI set") + validate_exact_https_uri(validated.requested_uri, name="requested_uri") + + transport_request = PlanetaryDefenseRetrievalRequest( + source_type_ref=validated.source_type_ref, + requested_uri=validated.requested_uri, + max_response_chars=min(validated.max_payload_chars, MAX_RESPONSE_BODY_CHARS), + ) + self.capture_calls += 1 + result = await self._transport.retrieve(transport_request) + if type(result) is not PlanetaryDefenseRetrievalResult: + raise _fail("transport returned an unsupported planetary-defense result type") + if any( + type(value) is not str + for value in ( + result.source_type_ref, + result.requested_uri, + result.effective_uri, + result.media_type, + result.response_body, + result.locator, + ) + ): + raise _fail("planetary-defense retrieval scalar fields must use exact string types") + if type(result.status_code) is not int: + raise _fail("planetary-defense status_code must use the exact integer type") + if type(result.redirect_chain) is not tuple or result.redirect_chain != (): + raise _fail("planetary-defense redirect_chain must be exactly an empty tuple") + if type(result.credentials_used) is not bool or result.credentials_used is not False: + raise _fail("planetary-defense retrieval must attest exact false credentials_used") + if ( + type(result.dns_rebinding_protection_applied) is not bool + or result.dns_rebinding_protection_applied is not True + ): + raise _fail("planetary-defense retrieval must attest exact true DNS-rebinding protection") + if ( + result.source_type_ref != self.source_type_ref + or result.requested_uri != profile.requested_uri + or result.effective_uri != profile.requested_uri + ): + raise _fail("planetary-defense retrieval crossed source type or exact URI scope") + if result.locator != PLANETARY_DEFENSE_LOCATOR: + raise _fail("planetary-defense retrieval does not bind the exact article locator") + if result.status_code != 200 or result.media_type != "text/html": + raise _fail("planetary-defense retrieval must be exact HTTP 200 text/html material") + try: + resolved = _validated_addresses(result.resolved_ip_addresses, name="resolved_ip_addresses") + connected = _validated_addresses(result.connected_ip_addresses, name="connected_ip_addresses") + observed_at = _aware_utc(result.observed_at, name="observed_at") + captured_at = _aware_utc(result.captured_at, name="captured_at") + except ValueError as exc: + raise _fail(str(exc)) from exc + if connected != resolved: + raise _fail("every resolved and connected planetary-defense address must remain exactly attested") + if observed_at < validated.started_at or captured_at < observed_at: + raise _fail("planetary-defense observation/capture times fall outside the exact operation") + + payload_json = _canonical_publication_payload( + result.response_body, + profile=profile, + max_chars=transport_request.max_response_chars, + ) + return CapturedSourceMaterialV1Alpha1( + capture_request_ref=str(validated.request_id), + capture_request_digest=str(validated.request_digest), + source_type_ref=validated.source_type_ref, + requested_uri=validated.requested_uri, + effective_uri=result.effective_uri, + redirect_chain=(), + resolved_ip_addresses=resolved, + dns_rebinding_protection_applied=True, + captured_payload_json=payload_json, + captured_payload_digest="sha256:" + hashlib.sha256(payload_json.encode("utf-8")).hexdigest(), + locator=PLANETARY_DEFENSE_LOCATOR, + source_published_at=datetime.fromisoformat(profile.publication_date).replace(tzinfo=UTC), + event_effective_at=None, + observed_at=observed_at, + captured_at=captured_at, + ) + + +__all__ = [ + "ESA_INITIAL_PROFILE", + "ESA_INITIAL_TITLE", + "ESA_INITIAL_URI", + "ESA_PLANETARY_DEFENCE_IMPLEMENTATION_ID", + "ESA_PLANETARY_DEFENCE_PROFILES", + "ESA_PLANETARY_DEFENCE_SOURCE_TYPE", + "ESA_REVISED_PROFILE", + "ESA_REVISED_TITLE", + "ESA_REVISED_URI", + "NASA_INITIAL_PROFILE", + "NASA_INITIAL_TITLE", + "NASA_INITIAL_URI", + "NASA_PLANETARY_DEFENSE_IMPLEMENTATION_ID", + "NASA_PLANETARY_DEFENSE_PROFILES", + "NASA_PLANETARY_DEFENSE_SOURCE_TYPE", + "NASA_REVISED_PROFILE", + "NASA_REVISED_TITLE", + "NASA_REVISED_URI", + "PLANETARY_DEFENSE_IMPLEMENTATION_VERSION", + "PLANETARY_DEFENSE_LOCATOR", + "PLANETARY_DEFENSE_OBJECT", + "PLANETARY_DEFENSE_TARGET_DATE", + "PlanetaryDefensePublicationProfile", + "PlanetaryDefenseRetrievalRequest", + "PlanetaryDefenseRetrievalResult", + "PlanetaryDefenseSourceAdapter", + "PlanetaryDefenseSourceAdapterError", + "PlanetaryDefenseTransport", +] diff --git a/adapters/federal_register_source/tests/test_planetary_defense_adapter.py b/adapters/federal_register_source/tests/test_planetary_defense_adapter.py new file mode 100644 index 0000000..7f7f5ff --- /dev/null +++ b/adapters/federal_register_source/tests/test_planetary_defense_adapter.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import json +from dataclasses import replace +from datetime import UTC, datetime, timedelta + +import pytest +from ace.core import AuthenticatedRuntimeContextV1Alpha1 +from ace.intelligence import SourceAdapterCaptureRequestV1Alpha1 + +from ace_world_federal_register_source import ( + ESA_INITIAL_PROFILE, + ESA_PLANETARY_DEFENCE_SOURCE_TYPE, + ESA_REVISED_PROFILE, + NASA_INITIAL_PROFILE, + NASA_PLANETARY_DEFENSE_SOURCE_TYPE, + NASA_REVISED_PROFILE, + PLANETARY_DEFENSE_LOCATOR, + PlanetaryDefenseRetrievalResult, + PlanetaryDefenseSourceAdapter, + PlanetaryDefenseSourceAdapterError, +) + +ARTIFACT_DIGEST = "sha256:" + "6" * 64 +STARTED = datetime(2026, 8, 11, 18, 0, tzinfo=UTC) +PROFILES = ( + NASA_INITIAL_PROFILE, + NASA_REVISED_PROFILE, + ESA_INITIAL_PROFILE, + ESA_REVISED_PROFILE, +) + + +def _body(profile, **changes: str) -> str: + title = changes.get("title", profile.title) + published = changes.get("published", profile.publication_date + "T00:00:00+00:00") + canonical = changes.get("canonical", profile.requested_uri) + statement = changes.get("statement", " ".join(profile.required_statements)) + return ( + "" + f'' + f'' + f'' + f"

{title}

{statement}

" + "
" + ) + + +class _Transport: + def __init__(self, result: PlanetaryDefenseRetrievalResult) -> None: + self.result = result + self.calls = 0 + + async def retrieve(self, request): + assert request.requested_uri == self.result.requested_uri + self.calls += 1 + return self.result + + +def _result(profile, **changes: object) -> PlanetaryDefenseRetrievalResult: + base = PlanetaryDefenseRetrievalResult( + source_type_ref=profile.source_type_ref, + requested_uri=profile.requested_uri, + effective_uri=profile.requested_uri, + status_code=200, + media_type="text/html", + response_body=_body(profile), + redirect_chain=(), + resolved_ip_addresses=("1.1.1.1",), + connected_ip_addresses=("1.1.1.1",), + dns_rebinding_protection_applied=True, + credentials_used=False, + locator=PLANETARY_DEFENSE_LOCATOR, + observed_at=STARTED + timedelta(seconds=1), + captured_at=STARTED + timedelta(seconds=2), + ) + return replace(base, **changes) + + +def _adapter_and_request(profile, **changes: object): + transport = _Transport(_result(profile, **changes)) + adapter = PlanetaryDefenseSourceAdapter( + transport=transport, + artifact_digest=ARTIFACT_DIGEST, + source_type_ref=profile.source_type_ref, + ) + context = AuthenticatedRuntimeContextV1Alpha1( + product_id="product:world-planetary-defense", + actor_ref="actor:world-planetary-defense-researcher", + authentication_receipt_ref="authentication_receipt:planetary-defense", + authentication_receipt_digest="sha256:" + "7" * 64, + authenticated_at=STARTED - timedelta(minutes=1), + expires_at=STARTED + timedelta(minutes=10), + ) + request = SourceAdapterCaptureRequestV1Alpha1( + product_id=context.product_id, + authenticated_context=context, + use_subject_ref="live_source_ingress_request:planetary-defense", + use_subject_digest="sha256:" + "8" * 64, + source_definition_ref="source_definition:planetary-defense", + source_type_ref=profile.source_type_ref, + requested_uri=profile.requested_uri, + adapter_artifact=adapter.artifact_identity, + configuration_ref="config:planetary-defense", + configuration_digest="sha256:" + "9" * 64, + started_at=STARTED, + max_payload_chars=512_000, + ) + return adapter, transport, request + + +@pytest.mark.asyncio +@pytest.mark.parametrize("profile", PROFILES, ids=lambda item: item.source_lineage_id) +async def test_exact_planetary_defense_publication_becomes_closed_inert_material(profile) -> None: + adapter, transport, request = _adapter_and_request(profile) + capture = await adapter.capture(request) + payload = json.loads(capture.captured_payload_json) + + assert payload == { + "assessment_note": profile.assessment_note, + "assessment_subject": "earth_impact_probability", + "claimant_office": profile.claimant_office, + "claimant_org": profile.claimant_org, + "estimate_status": profile.estimate_status, + "impact_probability_percent": format(profile.probability_percent, "g"), + "object_name": "2024 YR4", + "predecessor_lineage_id": profile.predecessor_lineage_id, + "publication_date": profile.publication_date, + "source_lineage_id": profile.source_lineage_id, + "source_uri": profile.requested_uri, + "target_date": "2032-12-22", + } + assert capture.source_published_at == datetime.fromisoformat(profile.publication_date).replace(tzinfo=UTC) + assert capture.requested_uri == capture.effective_uri == profile.requested_uri + assert adapter.capture_calls == transport.calls == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("changes", "message"), + [ + ({"status_code": 404}, "HTTP 200"), + ({"media_type": "application/json"}, "text/html"), + ({"effective_uri": NASA_INITIAL_PROFILE.requested_uri + "?other=1"}, "URI scope"), + ({"redirect_chain": (NASA_INITIAL_PROFILE.requested_uri,)}, "empty tuple"), + ({"credentials_used": True}, "false credentials"), + ({"resolved_ip_addresses": ("127.0.0.1",)}, "globally routable"), + ({"connected_ip_addresses": ("8.8.8.8",)}, "exactly attested"), + ({"locator": "css:h1"}, "article locator"), + ({"response_body": _body(NASA_INITIAL_PROFILE, title="Different")}, "title"), + ({"response_body": _body(NASA_INITIAL_PROFILE, published="2025-02-08")}, "publication date"), + ({"response_body": _body(NASA_INITIAL_PROFILE, canonical="https://example.com")}, "canonical URI"), + ({"response_body": _body(NASA_INITIAL_PROFILE, statement="2.3%")}, "estimate statement"), + ({"captured_at": STARTED}, "observation/capture times"), + ], +) +async def test_planetary_defense_adapter_fails_closed( + changes: dict[str, object], + message: str, +) -> None: + adapter, _, request = _adapter_and_request(NASA_INITIAL_PROFILE, **changes) + with pytest.raises(PlanetaryDefenseSourceAdapterError, match=message): + await adapter.capture(request) + + +def test_planetary_defense_adapter_rejects_cross_claimant_source_type() -> None: + with pytest.raises(PlanetaryDefenseSourceAdapterError, match="unsupported"): + PlanetaryDefenseSourceAdapter( + transport=object(), + artifact_digest=ARTIFACT_DIGEST, + source_type_ref="other", + ) + assert NASA_PLANETARY_DEFENSE_SOURCE_TYPE != ESA_PLANETARY_DEFENCE_SOURCE_TYPE diff --git a/docs/audits/world-intelligence-p2d-live-conflict-correction-2026-08-11.md b/docs/audits/world-intelligence-p2d-live-conflict-correction-2026-08-11.md new file mode 100644 index 0000000..7a1ebb4 --- /dev/null +++ b/docs/audits/world-intelligence-p2d-live-conflict-correction-2026-08-11.md @@ -0,0 +1,92 @@ +# World Intelligence P2D LIVE conflict/correction audit — 2026-08-11 + +## Result + +P2D carries four recorded official publications through governed LIVE admission, configured Shift +and Signal derivation, immutable Case assembly, cited Reality Briefs, family-aware per-claim status, +explicit same-source supersession, and additive dependency-impact projection. The historical +artifacts remain immutable after the later source records arrive. PREPARED and LIVE remain visibly +separate: the accepted store contains 44 LIVE records and zero PREPARED records. + +## Source boundary + +The scenario freezes these dated official publication claims: + +| Claimant lineage | Earlier record | Later record | +|---|---|---| +| NASA Planetary Defense / JPL CNEOS | [2.3% on 2025-02-07](https://science.nasa.gov/blogs/planetary-defense/2025/02/07/nasa-continues-to-monitor-orbit-of-near-earth-asteroid-2024-yr4/) | [0.004% on 2025-02-24](https://science.nasa.gov/blogs/planetary-defense/2025/02/24/latest-calculations-conclude-asteroid-2024-yr4-now-poses-no-significant-threat-to-earth-in-2032-and-beyond/) | +| ESA Planetary Defence Office | [1.8% on 2025-02-06](https://blogs.esa.int/rocketscience/2025/02/06/2024-yr4-flyby-geometry-or-1-8-of-what/comment-page-1/) | [0.001% on 2025-02-25](https://www.esa.int/ESA_Multimedia/Images/2025/02/Asteroid_2024_YR4_impact_risk_rises_and_falls) | + +The conformance responses are bounded recorded HTML and use no network. The connector validates +the exact source type, canonical URI, title, publication date, target date, estimate statements, +empty redirect chain, credential absence, public-address attestations, and operation-time order. +Fractional source values are retained as exact decimal text at capture and transformed to numeric +attributes by the declarative source-mapping module. + +The two organizations are independent official claimant publication roots. This audit does **not** +claim independent measurements: both publications describe a shared international observation +ecosystem, and source independence is only as strong as admitted lineage. + +## Accepted journey + +| Boundary | Historical | Corrected | +|---|---:|---:| +| Official cited records | 2 | 4 | +| Brief claims | 8 | 8 | +| Derived source families | 2 | 4 raw roots | +| Case members | 4 | 12 | +| PREPARED records | 0 | 0 | + +The corrected family closure retains four raw source-observation roots. Each explicit same-lineage +supersession assertion collapses to its earlier same-source Observation, so a before/after pair does +not manufacture a second family. The corrected `corroborated` claim is supported by exactly two +families: the NASA and ESA revised-source assertions. + +## Supersession impact + +Each later source produces a distinct LIVE assertion Observation with: + +- one exact `supersedes` edge to its earlier same-source Observation; +- one non-collapsing support edge to the captured later Observation; +- the predecessor lineage identifier already present in the captured official-source payload; and +- an explicit statement that impact means dependency, not falsehood. + +The two additive impact projections each enumerate five affected historical resources, seven +affected Brief claims, and two unaffected resources. Both replay exactly. Four malformed vectors +fail closed: cross-claimant target, missing target, future-leaking closure, and a record with no +`supersedes` edge. + +## Exact identities + +| Artifact | Identity | +|---|---| +| Compiled pack | `pack_ir:bb400cc0652622b43c01504e651110e0` | +| Historical Case | `case:9f2a90fa065e26aba4792c8cdd24647d` | +| Historical Brief | `brief:c3549af0262b100ca65024ee19cbae6e` | +| Historical status projection | `brief_derivation_family_status_projection:617cbe6102c82b13dcbe35735d685355` | +| NASA impact projection | `supersession_impact_projection:8c397e0253ddbfce3a7045d2b4c9db81` | +| ESA impact projection | `supersession_impact_projection:4c475c4dc1054e5a3d3c62699964fc9e` | +| Corrected Case | `case:7298a4c57828df679d03b2ed6493b437` | +| Corrected Brief | `brief:806d69d8e41f83f93ee3dc10f58f0d16` | +| Corrected status projection | `brief_derivation_family_status_projection:2acb48dd15e625c4b729ecef484b0209` | + +## Guardrails + +- estimate divergence is not a truth verdict; +- supersession impact is dependency, not falsehood; +- earlier records, Cases, Briefs, claims, and statuses are never rewritten; +- the Domain Pack contains JSON only and grants only source-read requests; +- the conformance transport is recorded and makes no freshness claim; +- no Decision, Outcome, feedback, monitor, schedule, delivery, persuasion, publication, or other + external action is created. + +## Verification + +- focused pack, journey, connector, negative, replay, and separation tests: **21 passed**; +- complete World domain suite: **90 passed**; +- complete separately packaged connector suite: **80 passed**; +- root release-contract suite: **7 passed**; +- static lint and formatting checks over every changed Python boundary: passed; +- root sdist and wheel: built successfully; +- wheel payload: exactly **55 JSON resources**, including nine planetary-defense resources, with no + `.py`, `.pyc`, `.so`, or `.pyd` payload. diff --git a/docs/design/world-intelligence-p2d-live-conflict-correction-work-packet-v1.md b/docs/design/world-intelligence-p2d-live-conflict-correction-work-packet-v1.md new file mode 100644 index 0000000..da175fd --- /dev/null +++ b/docs/design/world-intelligence-p2d-live-conflict-correction-work-packet-v1.md @@ -0,0 +1,78 @@ +# P2D work packet — LIVE conflict, correction, and supersession + +**Status:** frozen implementation packet + +**Mode:** LIVE only; PREPARED material is excluded +**Scenario:** official 2024 YR4 Earth-impact estimates published by NASA and ESA + +## Product claim + +Recorded, network-free captures from two independently governed official publication roots are +admitted through ACE as LIVE Observations. A configured numeric detector makes the dated estimate +divergence visible as a Shift and routed Signal. A LIVE Case and cited Reality Brief preserve that +historical view. Later official estimates are then admitted as new LIVE records, explicit +supersession assertions name the exact earlier same-source records, and additive impact projections +show which historical resources and claims depended on them. A second LIVE Case and Reality Brief +make the revisions and the earlier divergence visible without rewriting any prior artifact. + +This packet treats a percentage difference as a **dated estimate divergence**, not a truth verdict. +It treats supersession impact as **dependency, not falsehood**. The NASA and ESA publication roots +are independent claimant lineages; they are not independent measurements because both agencies +describe a shared international observation ecosystem. + +## Frozen official-source material + +| Lineage | Earlier publication | Later publication | Exact quantitative claim | +|---|---|---|---:| +| NASA Planetary Defense / JPL CNEOS | 2025-02-07 | 2025-02-24 | 2.3% → 0.004% | +| ESA Planetary Defence Office | 2025-02-06 | 2025-02-25 | 1.8% → 0.001% | + +All four accepted conformance responses are bounded recorded HTML and perform no network request. +The separately packaged connector validates exact canonical URI, title, date, claimant, estimate, +target date, network attestations, and payload bounds before returning inert canonical JSON. + +## Required durable journey + +1. Admit the NASA and ESA earlier publications as exact LIVE source transactions. +2. Derive the configured cross-source estimate-divergence Shift and routed Signal. +3. Append an immutable historical LIVE Case, cited Reality Brief, and per-claim status projection. +4. Admit the two later official publications as new LIVE source transactions. +5. Append one explicit LIVE supersession assertion per claimant. Each assertion carries an exact + `supersedes` edge to the earlier same-source Observation and a non-collapsing support edge to the + later source Observation. +6. Project and append exact LIVE dependency impact for both historical Observations, including + affected Brief claims, unaffected resources, and preserved historical artifact identities. +7. Derive the two configured downward-revision Shifts and routed Signals. +8. Append a corrected LIVE Case, four-citation Reality Brief, and family-aware per-claim status + projection. The Brief must visibly distinguish admitted records, dated divergence, later + revisions, bounded inference, and unknowns. + +## Acceptance boundaries + +- The new Domain Pack is JSON-only, inert, and additive. No existing pack or fixture is modified. +- The store contains LIVE records only: PREPARED count must remain exactly zero. +- Every source capture and exact replay performs one adapter/transport call total per URI. +- NASA and ESA remain separate derived source families; each same-source supersession collapses to + the earlier record in its own family and never manufactures corroboration. +- The historical Case, Brief, and status projection retain exact identity after corrections arrive + and reopen byte-identically. +- Both impact projections are durable, additive, exact-replayable, and report dependency rather + than falsehood. +- No Decision, Outcome, delivery, publication, persuasion, monitor, schedule, or external action is + created. + +## Negative vectors + +- a supersession edge naming the other claimant's record fails closed; +- a supersession target omitted from the authorized closure fails closed; +- a closure containing future material fails closed; +- an asserted `derived_from` edge is not accepted as a supersession cause; +- same-lineage before/after records cannot satisfy the two-family `corroborated` status; +- malformed URI, title, date, estimate, target date, redirect, credential use, private address, or + capture-time order fails at the connector boundary. + +## Verification before publication work + +Run focused pack, adapter, journey, negative, replay, PREPARED/LIVE separation, full domain, +release-contract, connector, lint, format, sdist, and wheel-payload gates. Do not commit, push, +publish, tag, or open a pull request until all local verification is complete. diff --git a/domain_packs/tests/test_world_intelligence_p2d_live_conflict_correction.py b/domain_packs/tests/test_world_intelligence_p2d_live_conflict_correction.py new file mode 100644 index 0000000..bb14f0a --- /dev/null +++ b/domain_packs/tests/test_world_intelligence_p2d_live_conflict_correction.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from scripts.p2d_live_conflict_correction import run_acceptance + +REPO_ROOT = Path(__file__).resolve().parents[2] +EXPECTED_PATH = ( + REPO_ROOT / "domain_packs" / "world_intelligence_planetary_defense" / "conformance" / "p2d_live_expected.json" +) + + +@pytest.mark.asyncio +async def test_live_conflict_correction_supersession_reaches_status_aware_brief() -> None: + result = await run_acceptance() + expected = json.loads(EXPECTED_PATH.read_text(encoding="utf-8")) + + assert result["pack"] | {} == { + **expected["pack"], + "json_only": True, + } + assert result["source"]["lineages"] == expected["source"]["lineages"] + assert result["source"]["probabilities"] == expected["source"]["probabilities"] + assert result["source"]["stable_entity_ref"] is True + assert result["source"]["adapter_capture_calls"] == {"NASA": 2, "ESA": 2} + assert set(result["source"]["transport_calls"].values()) == {1} + assert result["source"]["network_access"] is False + + for key, value in expected["historical"].items(): + assert result["historical"][key] == value + assert result["historical"]["shift_type"] == "official_estimate_divergence" + assert result["historical"]["signal_type"] == ("planetary_defense_estimate_divergence") + assert result["historical"]["status_replay_exact"] is True + + for key, value in expected["correction"].items(): + assert result["correction"][key] == value + assert result["correction"]["impact_replay_exact"] is True + assert result["correction"]["impact_is_dependency_not_falsehood"] is True + assert all(item["rejected"] for item in result["correction"]["negative_vectors"].values()) + + for key, value in expected["corrected"].items(): + assert result["corrected"][key] == value + assert result["corrected"]["shift_types"] == ["official_estimate_downward_revision"] + assert result["corrected"]["signal_types"] == ["planetary_defense_estimate_revision"] + assert result["corrected"]["status_replay_exact"] is True + assert result["corrected"]["same_lineage_supersessions_collapse"] is True + assert result["corrected"]["corroborated_claim_family_count"] == 2 + + assert result["historical_integrity"] == { + "brief_id_unchanged": True, + "brief_precedes_corrections": True, + "brief_reopened_identically": True, + "historical_artifact_rewritten": False, + } + assert result["separation"] == { + **expected["separation"], + "prepared_material_reused": False, + "autonomous_publication": False, + "external_action": False, + } diff --git a/domain_packs/tests/test_world_intelligence_planetary_defense_pack.py b/domain_packs/tests/test_world_intelligence_planetary_defense_pack.py new file mode 100644 index 0000000..07a828f --- /dev/null +++ b/domain_packs/tests/test_world_intelligence_planetary_defense_pack.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import json +from pathlib import Path + +from scripts.p2d_live_conflict_correction import compile_planetary_defense_pack + +REPO_ROOT = Path(__file__).resolve().parents[2] +PACK_ROOT = REPO_ROOT / "domain_packs" / "world_intelligence_planetary_defense" + + +def test_planetary_defense_pack_is_inert_json_only_and_exactly_pinned() -> None: + pack = compile_planetary_defense_pack() + expected = json.loads((PACK_ROOT / "conformance" / "p2d_live_expected.json").read_text(encoding="utf-8"))["pack"] + + assert pack.compiled_pack_id == expected["compiled_pack_id"] + assert pack.pack_digest == expected["pack_digest"] + assert len(pack.modules) == expected["module_count"] + assert all(path.suffix == ".json" for path in PACK_ROOT.rglob("*") if path.is_file()) + assert not tuple(PACK_ROOT.rglob("*.py")) + + +def test_planetary_defense_pack_declares_conflict_revision_status_and_no_action() -> None: + pack = compile_planetary_defense_pack() + contracts = {module.contract for module in pack.modules} + manifest = json.loads((PACK_ROOT / "manifest.json").read_text(encoding="utf-8")) + + assert contracts == { + "ace.intelligence.detection/v1alpha2", + "ace.intelligence.epistemic-status/v1alpha2", + "ace.intelligence.ontology/v1alpha1", + "ace.intelligence.personas/v1alpha1", + "ace.intelligence.source-mapping/v1alpha1", + "ace.intelligence.synthesis/v1alpha2", + } + assert {item["authority"] for item in manifest["authority_requests"]} == {"source_read"} + assert "action" not in json.dumps(manifest).lower() + assert "delivery" not in json.dumps(manifest).lower() diff --git a/domain_packs/world_intelligence_planetary_defense/conformance/p2d_live_conflict_correction_input.json b/domain_packs/world_intelligence_planetary_defense/conformance/p2d_live_conflict_correction_input.json new file mode 100644 index 0000000..f6fccad --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/conformance/p2d_live_conflict_correction_input.json @@ -0,0 +1,163 @@ +{ + "contract": "ace.world-intelligence.p2d-live-conflict-correction-input/v1alpha1", + "fixture_id": "planetary_defense_2024_yr4_live_revision", + "fixture_version": "0.1.0", + "product_id": "product:world-planetary-defense", + "actor_ref": "actor:world-planetary-defense-researcher", + "activation_key": "world_intelligence_planetary_defense_live", + "entity_ref": "entity:planetary-defense/2024-yr4-earth-impact-2032", + "entity_type_id": "planetary_defense_risk_estimate", + "subject_binding_id": "published_planetary_defense_estimate", + "authentication": { + "receipt_ref": "authentication_receipt:world-planetary-defense-p2d", + "receipt_digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "authenticated_at": "2026-08-11T17:50:00Z", + "expires_at": "2026-08-11T20:30:00Z" + }, + "activation": { + "overlay_id": "world_planetary_defense_p2d_conformance", + "overlay_version": "0.1.0", + "approval_receipt_ref": "approval_receipt:world-planetary-defense-p2d", + "compilation_receipt_ref": "compilation_receipt:world-planetary-defense-p2d", + "conformance_receipt_ref": "conformance_receipt:world-planetary-defense-p2d", + "occurred_at": "2026-08-11T17:55:00Z", + "committed_at": "2026-08-11T17:56:00Z" + }, + "claimants": [ + { + "claimant_org": "NASA", + "source_type_ref": "nasa_planetary_defense_publication", + "capability_requirement_id": "nasa_planetary_defense_snapshot", + "authority_request_id": "read_nasa_planetary_defense_publication", + "configuration_ref": "config:nasa-planetary-defense-2024-yr4", + "configuration_digest": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "grant_ref": "authority_grant:world-nasa-planetary-defense-read", + "grant_hash": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "artifact_digest": "sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + }, + { + "claimant_org": "ESA", + "source_type_ref": "esa_planetary_defence_publication", + "capability_requirement_id": "esa_planetary_defence_snapshot", + "authority_request_id": "read_esa_planetary_defence_publication", + "configuration_ref": "config:esa-planetary-defence-2024-yr4", + "configuration_digest": "sha256:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + "grant_ref": "authority_grant:world-esa-planetary-defence-read", + "grant_hash": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + "artifact_digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111" + } + ], + "sources": [ + { + "source_key": "esa_initial", + "claimant_org": "ESA", + "mapping_id": "esa_2024_yr4_2025_02_06", + "source_definition_ref": "source_definition:esa-2024-yr4-2025-02-06", + "idempotency_key": "live-source:planetary-defense:esa:2025-02-06", + "requested_at": "2026-08-11T18:00:00Z", + "capture_started_at": "2026-08-11T18:00:01Z", + "observed_at": "2026-08-11T18:00:02Z", + "captured_at": "2026-08-11T18:00:03Z", + "rechecked_at": "2026-08-11T18:00:04Z", + "admitted_at": "2026-08-11T18:00:05Z", + "requested_uri": "https://blogs.esa.int/rocketscience/2025/02/06/2024-yr4-flyby-geometry-or-1-8-of-what/comment-page-1/", + "locator": "css:article", + "media_type": "text/html", + "response_body": "

2024 YR4 flyby geometry, or 1.8% of What?

The risk of 2024 YR4 impacting Earth on 22 December 2032 is 1.8% and the numerical value is expected to evolve as additional observations are reported.

" + }, + { + "source_key": "nasa_initial", + "claimant_org": "NASA", + "mapping_id": "nasa_2024_yr4_2025_02_07", + "source_definition_ref": "source_definition:nasa-2024-yr4-2025-02-07", + "idempotency_key": "live-source:planetary-defense:nasa:2025-02-07", + "requested_at": "2026-08-11T18:01:00Z", + "capture_started_at": "2026-08-11T18:01:01Z", + "observed_at": "2026-08-11T18:01:02Z", + "captured_at": "2026-08-11T18:01:03Z", + "rechecked_at": "2026-08-11T18:01:04Z", + "admitted_at": "2026-08-11T18:01:05Z", + "requested_uri": "https://science.nasa.gov/blogs/planetary-defense/2025/02/07/nasa-continues-to-monitor-orbit-of-near-earth-asteroid-2024-yr4/", + "locator": "css:article", + "media_type": "text/html", + "response_body": "

NASA Continues to Monitor Orbit of Near-Earth Asteroid 2024 YR4

Additional observations indicate an impact probability of 2.3% with Earth on Dec. 22, 2032.

" + }, + { + "source_key": "nasa_revised", + "claimant_org": "NASA", + "mapping_id": "nasa_2024_yr4_2025_02_24", + "source_definition_ref": "source_definition:nasa-2024-yr4-2025-02-24", + "idempotency_key": "live-source:planetary-defense:nasa:2025-02-24", + "requested_at": "2026-08-11T18:10:00Z", + "capture_started_at": "2026-08-11T18:10:01Z", + "observed_at": "2026-08-11T18:10:02Z", + "captured_at": "2026-08-11T18:10:03Z", + "rechecked_at": "2026-08-11T18:10:04Z", + "admitted_at": "2026-08-11T18:10:05Z", + "requested_uri": "https://science.nasa.gov/blogs/planetary-defense/2025/02/24/latest-calculations-conclude-asteroid-2024-yr4-now-poses-no-significant-threat-to-earth-in-2032-and-beyond/", + "locator": "css:article", + "media_type": "text/html", + "response_body": "

Latest Calculations Conclude Asteroid 2024 YR4 Now Poses No Significant Threat to Earth in 2032 and Beyond

NASA updated the impact probability on Dec. 22, 2032 to 0.004% and found no significant potential for an Earth impact for the next century.

" + }, + { + "source_key": "esa_revised", + "claimant_org": "ESA", + "mapping_id": "esa_2024_yr4_2025_02_25", + "source_definition_ref": "source_definition:esa-2024-yr4-2025-02-25", + "idempotency_key": "live-source:planetary-defense:esa:2025-02-25", + "requested_at": "2026-08-11T18:11:00Z", + "capture_started_at": "2026-08-11T18:11:01Z", + "observed_at": "2026-08-11T18:11:02Z", + "captured_at": "2026-08-11T18:11:03Z", + "rechecked_at": "2026-08-11T18:11:04Z", + "admitted_at": "2026-08-11T18:11:05Z", + "requested_uri": "https://www.esa.int/ESA_Multimedia/Images/2025/02/Asteroid_2024_YR4_impact_risk_rises_and_falls", + "locator": "css:article", + "media_type": "text/html", + "response_body": "

Asteroid 2024 YR4 impact risk rises and falls

On 25 February the risk that 2024 YR4 might impact Earth on 22 December 2032 was 0.001%, down from as high as 2.8% a few days beforehand.

" + } + ], + "derivations": { + "divergence": { + "detector_id": "cross_source_impact_estimate_divergence", + "baseline_source_key": "esa_initial", + "current_source_key": "nasa_initial", + "derivation_key": "live-derivation:planetary-defense:initial-divergence", + "detected_at": "2026-08-11T18:02:00Z", + "attention_evaluated_at": "2026-08-11T18:02:01Z", + "requested_at": "2026-08-11T18:02:02Z" + }, + "nasa_revision": { + "detector_id": "same_source_impact_estimate_revision", + "baseline_source_key": "nasa_initial", + "current_source_key": "nasa_revised", + "derivation_key": "live-derivation:planetary-defense:nasa-revision", + "detected_at": "2026-08-11T18:14:00Z", + "attention_evaluated_at": "2026-08-11T18:14:01Z", + "requested_at": "2026-08-11T18:14:02Z" + }, + "esa_revision": { + "detector_id": "same_source_impact_estimate_revision", + "baseline_source_key": "esa_initial", + "current_source_key": "esa_revised", + "derivation_key": "live-derivation:planetary-defense:esa-revision", + "detected_at": "2026-08-11T18:15:00Z", + "attention_evaluated_at": "2026-08-11T18:15:01Z", + "requested_at": "2026-08-11T18:15:02Z" + } + }, + "historical": { + "case_assembled_at": "2026-08-11T18:03:00Z", + "brief_as_of": "2026-08-11T18:03:00Z", + "brief_generated_at": "2026-08-11T18:04:00Z", + "status_generated_at": "2026-08-11T18:04:01Z" + }, + "correction": { + "asserted_at": "2026-08-11T18:12:00Z", + "impact_generated_at": "2026-08-11T18:13:00Z", + "case_assembled_at": "2026-08-11T18:16:00Z", + "brief_as_of": "2026-08-11T18:16:00Z", + "brief_generated_at": "2026-08-11T18:17:00Z", + "status_generated_at": "2026-08-11T18:17:01Z" + } +} diff --git a/domain_packs/world_intelligence_planetary_defense/conformance/p2d_live_expected.json b/domain_packs/world_intelligence_planetary_defense/conformance/p2d_live_expected.json new file mode 100644 index 0000000..a594eb3 --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/conformance/p2d_live_expected.json @@ -0,0 +1,62 @@ +{ + "contract": "ace.world-intelligence.p2d-live-conflict-correction-expected/v1alpha1", + "pack": { + "compiled_pack_id": "pack_ir:bb400cc0652622b43c01504e651110e0", + "pack_digest": "sha256:bb400cc0652622b43c01504e651110e09bc651d5003bbbfebe00afca213dbb29", + "module_count": 6 + }, + "source": { + "lineages": { + "esa_initial": "esa_pdo:2024_yr4:2025-02-06", + "esa_revised": "esa_pdo:2024_yr4:2025-02-25", + "nasa_initial": "nasa_pdco:2024_yr4:2025-02-07", + "nasa_revised": "nasa_pdco:2024_yr4:2025-02-24" + }, + "probabilities": { + "esa_initial": 1.8, + "esa_revised": 0.001, + "nasa_initial": 2.3, + "nasa_revised": 0.004 + } + }, + "historical": { + "case_id": "case:9f2a90fa065e26aba4792c8cdd24647d", + "brief_id": "brief:c3549af0262b100ca65024ee19cbae6e", + "status_projection_id": "brief_derivation_family_status_projection:617cbe6102c82b13dcbe35735d685355", + "citation_count": 2, + "claim_count": 8, + "family_count": 2 + }, + "correction": { + "impact_projection_ids": [ + "supersession_impact_projection:8c397e0253ddbfce3a7045d2b4c9db81", + "supersession_impact_projection:4c475c4dc1054e5a3d3c62699964fc9e" + ], + "impact_counts": {"ESA": 5, "NASA": 5}, + "impacted_claim_counts": {"ESA": 7, "NASA": 7}, + "unaffected_counts": {"ESA": 2, "NASA": 2} + }, + "corrected": { + "case_id": "case:7298a4c57828df679d03b2ed6493b437", + "brief_id": "brief:806d69d8e41f83f93ee3dc10f58f0d16", + "status_projection_id": "brief_derivation_family_status_projection:2acb48dd15e625c4b729ecef484b0209", + "citation_count": 4, + "claim_count": 8, + "case_member_count": 12, + "family_count": 4, + "claim_statuses": [ + "ace_inference", + "admitted_record", + "admitted_record", + "disputed", + "corroborated", + "ace_inference", + "unknown", + "admitted_record" + ] + }, + "separation": { + "live_record_count": 44, + "prepared_record_count": 0 + } +} diff --git a/domain_packs/world_intelligence_planetary_defense/manifest.json b/domain_packs/world_intelligence_planetary_defense/manifest.json new file mode 100644 index 0000000..30c6011 --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/manifest.json @@ -0,0 +1,112 @@ +{ + "contract": "ace.intelligence.domain-pack-manifest/v1alpha1", + "metadata": { + "pack_id": "world_intelligence_planetary_defense", + "version": "0.1.0", + "display_name": "ACE World Intelligence — Planetary Defense", + "description": "Additive declarative pack for dated official risk-estimate divergence, revision, correction visibility, and exact epistemic status." + }, + "compatibility": { + "compiler_contract": "ace.intelligence.pack-compiler/v1alpha1", + "intelligence_contract": "ace.intelligence.runtime/v1alpha1" + }, + "resources": [ + { + "resource_id": "world_planetary_defense_ontology", + "path": "modules/ontology.json", + "media_type": "application/json", + "digest": "sha256:16042b900889e4bfb6aeced69e5a6fbc00874e405439254e41e505f69729e1ab" + }, + { + "resource_id": "world_planetary_defense_source_mapping", + "path": "modules/source_mapping.json", + "media_type": "application/json", + "digest": "sha256:a4bdfe3837a4acf637e9a0c4c4eae1ff6bc03f4fb27b501949b1c11fcb9ddbbf" + }, + { + "resource_id": "world_planetary_defense_detection", + "path": "modules/detection.json", + "media_type": "application/json", + "digest": "sha256:30ea5209dabc08b2b03ca1570d99d9be8b2f5a736cf3c2c0a984ee278d3f11ba" + }, + { + "resource_id": "world_planetary_defense_synthesis", + "path": "modules/synthesis.json", + "media_type": "application/json", + "digest": "sha256:a904e1fb3bd16951d198cd67707d807ae88132f874814f5a6974faf6bafe5aa1" + }, + { + "resource_id": "world_planetary_defense_personas", + "path": "modules/personas.json", + "media_type": "application/json", + "digest": "sha256:b19dcbb1e645ead035ab9d7da0a59bba184ed75dbfb238035912c43825f038c0" + }, + { + "resource_id": "world_planetary_defense_epistemic_status", + "path": "modules/epistemic_status.json", + "media_type": "application/json", + "digest": "sha256:470d62ad4f07a25ba2f718acacd167426fb14fb358ea8c20de48103cd5f60b96" + } + ], + "modules": [ + { + "module_id": "world_planetary_defense_ontology", + "contract": "ace.intelligence.ontology/v1alpha1", + "resource_id": "world_planetary_defense_ontology", + "depends_on": [] + }, + { + "module_id": "world_planetary_defense_source_mapping", + "contract": "ace.intelligence.source-mapping/v1alpha1", + "resource_id": "world_planetary_defense_source_mapping", + "depends_on": ["world_planetary_defense_ontology"] + }, + { + "module_id": "world_planetary_defense_detection", + "contract": "ace.intelligence.detection/v1alpha2", + "resource_id": "world_planetary_defense_detection", + "depends_on": ["world_planetary_defense_ontology"] + }, + { + "module_id": "world_planetary_defense_synthesis", + "contract": "ace.intelligence.synthesis/v1alpha2", + "resource_id": "world_planetary_defense_synthesis", + "depends_on": [] + }, + { + "module_id": "world_planetary_defense_personas", + "contract": "ace.intelligence.personas/v1alpha1", + "resource_id": "world_planetary_defense_personas", + "depends_on": ["world_planetary_defense_detection", "world_planetary_defense_synthesis"] + }, + { + "module_id": "world_planetary_defense_epistemic_status", + "contract": "ace.intelligence.epistemic-status/v1alpha2", + "resource_id": "world_planetary_defense_epistemic_status", + "depends_on": ["world_planetary_defense_synthesis"] + } + ], + "capability_requirements": [ + { + "requirement_id": "nasa_planetary_defense_snapshot", + "capability": "source_snapshot", + "contract": "ace.source.snapshot/v1alpha1" + }, + { + "requirement_id": "esa_planetary_defence_snapshot", + "capability": "source_snapshot", + "contract": "ace.source.snapshot/v1alpha1" + } + ], + "authority_requests": [ + { + "request_id": "read_nasa_planetary_defense_publication", + "authority": "source_read" + }, + { + "request_id": "read_esa_planetary_defence_publication", + "authority": "source_read" + } + ], + "overlay_slots": [] +} diff --git a/domain_packs/world_intelligence_planetary_defense/modules/detection.json b/domain_packs/world_intelligence_planetary_defense/modules/detection.json new file mode 100644 index 0000000..968bb53 --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/modules/detection.json @@ -0,0 +1,31 @@ +{ + "contract": "ace.intelligence.detection/v1alpha2", + "module_id": "world_planetary_defense_detection", + "numeric_delta_rules": [ + { + "detector_id": "cross_source_impact_estimate_divergence", + "entity_type_id": "planetary_defense_risk_estimate", + "attribute_id": "impact_probability_percent", + "baseline": "prior_snapshot", + "context_attribute_ids": ["assessment_subject", "object_name", "target_date"], + "metric": "percent_change", + "threshold": 20.0, + "direction": "any", + "shift_type": "official_estimate_divergence", + "signal_type": "planetary_defense_estimate_divergence" + }, + { + "detector_id": "same_source_impact_estimate_revision", + "entity_type_id": "planetary_defense_risk_estimate", + "attribute_id": "impact_probability_percent", + "baseline": "prior_snapshot", + "context_attribute_ids": ["assessment_subject", "claimant_org", "object_name", "target_date"], + "metric": "percent_change", + "threshold": 90.0, + "direction": "decrease", + "shift_type": "official_estimate_downward_revision", + "signal_type": "planetary_defense_estimate_revision" + } + ], + "categorical_transition_rules": [] +} diff --git a/domain_packs/world_intelligence_planetary_defense/modules/epistemic_status.json b/domain_packs/world_intelligence_planetary_defense/modules/epistemic_status.json new file mode 100644 index 0000000..2220105 --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/modules/epistemic_status.json @@ -0,0 +1,68 @@ +{ + "contract": "ace.intelligence.epistemic-status/v1alpha2", + "module_id": "world_planetary_defense_epistemic_status", + "status_sets": [ + { + "status_set_id": "planetary_defense_reality_status", + "display_name": "Planetary Defense Reality Brief epistemic statuses", + "brief_template_ids": ["planetary_defense_reality_brief"], + "require_status_for_every_claim": true, + "statuses": [ + { + "status_id": "admitted_record", + "display_name": "Admitted record", + "definition": "Directly established by one or more exact admitted official-source Observations.", + "allowed_grounding_kinds": ["cited"], + "allowed_support_kinds": ["observation"], + "min_support_count": 1 + }, + { + "status_id": "attributed_claim", + "display_name": "Attributed claim", + "definition": "A dated estimate asserted by exactly one named official publication and not upgraded beyond that attribution.", + "allowed_grounding_kinds": ["cited"], + "allowed_support_kinds": ["observation"], + "min_support_count": 1, + "max_support_count": 1 + }, + { + "status_id": "corroborated", + "display_name": "Corroborated", + "definition": "Supported by at least two admitted Observations spanning at least two distinct derivation families.", + "allowed_grounding_kinds": ["cited"], + "allowed_support_kinds": ["observation"], + "min_support_count": 2, + "min_distinct_derivation_families": 2, + "proves_source_family_independence": true + }, + { + "status_id": "disputed", + "display_name": "Dated divergence", + "definition": "Materially different dated estimates occur across admitted source records; this is not a truth verdict.", + "allowed_grounding_kinds": ["inference"], + "allowed_support_kinds": ["observation", "shift"], + "min_support_count": 2, + "requires_uncertainty": true + }, + { + "status_id": "ace_inference", + "display_name": "ACE inference", + "definition": "An explicitly bounded interpretation linked to the exact LIVE resources used.", + "allowed_grounding_kinds": ["inference"], + "allowed_support_kinds": ["case", "observation", "shift", "signal"], + "min_support_count": 1, + "requires_uncertainty": true + }, + { + "status_id": "unknown", + "display_name": "Unknown", + "definition": "Not resolved by the admitted publications and stated as an open question against exact LIVE resources.", + "allowed_grounding_kinds": ["inference"], + "allowed_support_kinds": ["case", "observation", "shift", "signal"], + "min_support_count": 1, + "requires_uncertainty": true + } + ] + } + ] +} diff --git a/domain_packs/world_intelligence_planetary_defense/modules/ontology.json b/domain_packs/world_intelligence_planetary_defense/modules/ontology.json new file mode 100644 index 0000000..5070814 --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/modules/ontology.json @@ -0,0 +1,25 @@ +{ + "contract": "ace.intelligence.ontology/v1alpha1", + "module_id": "world_planetary_defense_ontology", + "entity_types": [ + { + "entity_type_id": "planetary_defense_risk_estimate", + "display_name": "Planetary Defense Risk Estimate", + "attributes": [ + {"attribute_id": "assessment_note", "value_type": "string", "required": true}, + {"attribute_id": "assessment_subject", "value_type": "string", "required": true}, + {"attribute_id": "claimant_office", "value_type": "string", "required": true}, + {"attribute_id": "claimant_org", "value_type": "string", "required": true}, + {"attribute_id": "estimate_status", "value_type": "string", "required": true}, + {"attribute_id": "impact_probability_percent", "value_type": "number", "required": true}, + {"attribute_id": "object_name", "value_type": "string", "required": true}, + {"attribute_id": "predecessor_lineage_id", "value_type": "string", "required": true}, + {"attribute_id": "publication_date", "value_type": "string", "required": true}, + {"attribute_id": "source_lineage_id", "value_type": "string", "required": true}, + {"attribute_id": "source_uri", "value_type": "string", "required": true}, + {"attribute_id": "target_date", "value_type": "string", "required": true} + ] + } + ], + "relation_types": [] +} diff --git a/domain_packs/world_intelligence_planetary_defense/modules/personas.json b/domain_packs/world_intelligence_planetary_defense/modules/personas.json new file mode 100644 index 0000000..b8d89f4 --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/modules/personas.json @@ -0,0 +1,27 @@ +{ + "contract": "ace.intelligence.personas/v1alpha1", + "module_id": "world_planetary_defense_personas", + "personas": [ + { + "persona_id": "planetary_defense_researcher", + "display_name": "Planetary Defense Researcher", + "description": "Inspects exact claimant lineages, dated estimates, revisions, dependency impact, citations, and uncertainty." + } + ], + "signal_routing_rules": [ + { + "routing_rule_id": "route_planetary_defense_divergence", + "signal_type": "planetary_defense_estimate_divergence", + "persona_ids": ["planetary_defense_researcher"], + "minimum_confidence": 0.8, + "brief_template_id": "planetary_defense_reality_brief" + }, + { + "routing_rule_id": "route_planetary_defense_revision", + "signal_type": "planetary_defense_estimate_revision", + "persona_ids": ["planetary_defense_researcher"], + "minimum_confidence": 0.8, + "brief_template_id": "planetary_defense_reality_brief" + } + ] +} diff --git a/domain_packs/world_intelligence_planetary_defense/modules/source_mapping.json b/domain_packs/world_intelligence_planetary_defense/modules/source_mapping.json new file mode 100644 index 0000000..ce7bfa2 --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/modules/source_mapping.json @@ -0,0 +1,106 @@ +{ + "contract": "ace.intelligence.source-mapping/v1alpha1", + "module_id": "world_planetary_defense_source_mapping", + "mappings": [ + { + "mapping_id": "nasa_2024_yr4_2025_02_07", + "source_definition_ref": "source_definition:nasa-2024-yr4-2025-02-07", + "source_type_ref": "nasa_planetary_defense_publication", + "capability_requirement_id": "nasa_planetary_defense_snapshot", + "authority_request_id": "read_nasa_planetary_defense_publication", + "allowed_uri_schemes": ["https"], + "subject_binding_id": "published_planetary_defense_estimate", + "entity_type_id": "planetary_defense_risk_estimate", + "attribute_mappings": [ + {"attribute_id": "assessment_note", "source_pointer": "/assessment_note", "transform": "copy", "min_length": 1, "max_length": 1000}, + {"attribute_id": "assessment_subject", "source_pointer": "/assessment_subject", "transform": "copy", "min_length": 1, "max_length": 128}, + {"attribute_id": "claimant_office", "source_pointer": "/claimant_office", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "claimant_org", "source_pointer": "/claimant_org", "transform": "copy", "min_length": 1, "max_length": 128}, + {"attribute_id": "estimate_status", "source_pointer": "/estimate_status", "transform": "copy", "min_length": 1, "max_length": 32}, + {"attribute_id": "impact_probability_percent", "source_pointer": "/impact_probability_percent", "transform": "decimal_text_to_number"}, + {"attribute_id": "object_name", "source_pointer": "/object_name", "transform": "copy", "min_length": 1, "max_length": 64}, + {"attribute_id": "predecessor_lineage_id", "source_pointer": "/predecessor_lineage_id", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "publication_date", "source_pointer": "/publication_date", "transform": "copy", "min_length": 10, "max_length": 10}, + {"attribute_id": "source_lineage_id", "source_pointer": "/source_lineage_id", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "source_uri", "source_pointer": "/source_uri", "transform": "copy", "min_length": 9, "max_length": 2048}, + {"attribute_id": "target_date", "source_pointer": "/target_date", "transform": "copy", "min_length": 10, "max_length": 10} + ], + "static_confidence": 1.0 + }, + { + "mapping_id": "nasa_2024_yr4_2025_02_24", + "source_definition_ref": "source_definition:nasa-2024-yr4-2025-02-24", + "source_type_ref": "nasa_planetary_defense_publication", + "capability_requirement_id": "nasa_planetary_defense_snapshot", + "authority_request_id": "read_nasa_planetary_defense_publication", + "allowed_uri_schemes": ["https"], + "subject_binding_id": "published_planetary_defense_estimate", + "entity_type_id": "planetary_defense_risk_estimate", + "attribute_mappings": [ + {"attribute_id": "assessment_note", "source_pointer": "/assessment_note", "transform": "copy", "min_length": 1, "max_length": 1000}, + {"attribute_id": "assessment_subject", "source_pointer": "/assessment_subject", "transform": "copy", "min_length": 1, "max_length": 128}, + {"attribute_id": "claimant_office", "source_pointer": "/claimant_office", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "claimant_org", "source_pointer": "/claimant_org", "transform": "copy", "min_length": 1, "max_length": 128}, + {"attribute_id": "estimate_status", "source_pointer": "/estimate_status", "transform": "copy", "min_length": 1, "max_length": 32}, + {"attribute_id": "impact_probability_percent", "source_pointer": "/impact_probability_percent", "transform": "decimal_text_to_number"}, + {"attribute_id": "object_name", "source_pointer": "/object_name", "transform": "copy", "min_length": 1, "max_length": 64}, + {"attribute_id": "predecessor_lineage_id", "source_pointer": "/predecessor_lineage_id", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "publication_date", "source_pointer": "/publication_date", "transform": "copy", "min_length": 10, "max_length": 10}, + {"attribute_id": "source_lineage_id", "source_pointer": "/source_lineage_id", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "source_uri", "source_pointer": "/source_uri", "transform": "copy", "min_length": 9, "max_length": 2048}, + {"attribute_id": "target_date", "source_pointer": "/target_date", "transform": "copy", "min_length": 10, "max_length": 10} + ], + "static_confidence": 1.0 + }, + { + "mapping_id": "esa_2024_yr4_2025_02_06", + "source_definition_ref": "source_definition:esa-2024-yr4-2025-02-06", + "source_type_ref": "esa_planetary_defence_publication", + "capability_requirement_id": "esa_planetary_defence_snapshot", + "authority_request_id": "read_esa_planetary_defence_publication", + "allowed_uri_schemes": ["https"], + "subject_binding_id": "published_planetary_defense_estimate", + "entity_type_id": "planetary_defense_risk_estimate", + "attribute_mappings": [ + {"attribute_id": "assessment_note", "source_pointer": "/assessment_note", "transform": "copy", "min_length": 1, "max_length": 1000}, + {"attribute_id": "assessment_subject", "source_pointer": "/assessment_subject", "transform": "copy", "min_length": 1, "max_length": 128}, + {"attribute_id": "claimant_office", "source_pointer": "/claimant_office", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "claimant_org", "source_pointer": "/claimant_org", "transform": "copy", "min_length": 1, "max_length": 128}, + {"attribute_id": "estimate_status", "source_pointer": "/estimate_status", "transform": "copy", "min_length": 1, "max_length": 32}, + {"attribute_id": "impact_probability_percent", "source_pointer": "/impact_probability_percent", "transform": "decimal_text_to_number"}, + {"attribute_id": "object_name", "source_pointer": "/object_name", "transform": "copy", "min_length": 1, "max_length": 64}, + {"attribute_id": "predecessor_lineage_id", "source_pointer": "/predecessor_lineage_id", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "publication_date", "source_pointer": "/publication_date", "transform": "copy", "min_length": 10, "max_length": 10}, + {"attribute_id": "source_lineage_id", "source_pointer": "/source_lineage_id", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "source_uri", "source_pointer": "/source_uri", "transform": "copy", "min_length": 9, "max_length": 2048}, + {"attribute_id": "target_date", "source_pointer": "/target_date", "transform": "copy", "min_length": 10, "max_length": 10} + ], + "static_confidence": 1.0 + }, + { + "mapping_id": "esa_2024_yr4_2025_02_25", + "source_definition_ref": "source_definition:esa-2024-yr4-2025-02-25", + "source_type_ref": "esa_planetary_defence_publication", + "capability_requirement_id": "esa_planetary_defence_snapshot", + "authority_request_id": "read_esa_planetary_defence_publication", + "allowed_uri_schemes": ["https"], + "subject_binding_id": "published_planetary_defense_estimate", + "entity_type_id": "planetary_defense_risk_estimate", + "attribute_mappings": [ + {"attribute_id": "assessment_note", "source_pointer": "/assessment_note", "transform": "copy", "min_length": 1, "max_length": 1000}, + {"attribute_id": "assessment_subject", "source_pointer": "/assessment_subject", "transform": "copy", "min_length": 1, "max_length": 128}, + {"attribute_id": "claimant_office", "source_pointer": "/claimant_office", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "claimant_org", "source_pointer": "/claimant_org", "transform": "copy", "min_length": 1, "max_length": 128}, + {"attribute_id": "estimate_status", "source_pointer": "/estimate_status", "transform": "copy", "min_length": 1, "max_length": 32}, + {"attribute_id": "impact_probability_percent", "source_pointer": "/impact_probability_percent", "transform": "decimal_text_to_number"}, + {"attribute_id": "object_name", "source_pointer": "/object_name", "transform": "copy", "min_length": 1, "max_length": 64}, + {"attribute_id": "predecessor_lineage_id", "source_pointer": "/predecessor_lineage_id", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "publication_date", "source_pointer": "/publication_date", "transform": "copy", "min_length": 10, "max_length": 10}, + {"attribute_id": "source_lineage_id", "source_pointer": "/source_lineage_id", "transform": "copy", "min_length": 1, "max_length": 256}, + {"attribute_id": "source_uri", "source_pointer": "/source_uri", "transform": "copy", "min_length": 9, "max_length": 2048}, + {"attribute_id": "target_date", "source_pointer": "/target_date", "transform": "copy", "min_length": 10, "max_length": 10} + ], + "static_confidence": 1.0 + } + ] +} diff --git a/domain_packs/world_intelligence_planetary_defense/modules/synthesis.json b/domain_packs/world_intelligence_planetary_defense/modules/synthesis.json new file mode 100644 index 0000000..c2de0df --- /dev/null +++ b/domain_packs/world_intelligence_planetary_defense/modules/synthesis.json @@ -0,0 +1,24 @@ +{ + "contract": "ace.intelligence.synthesis/v1alpha2", + "module_id": "world_planetary_defense_synthesis", + "brief_templates": [ + { + "template_id": "planetary_defense_reality_brief", + "brief_type": "world_intelligence", + "display_name": "Planetary Defense Reality Brief", + "objective": "Explain dated official estimates, source divergence, later revisions, exact supersession impact, and remaining uncertainty without treating dependency as falsehood.", + "required_sections": [ + "what_changed", + "established_records", + "source_comparison", + "where_sources_conflict", + "current_orientation", + "correction_visibility", + "unknowns", + "limitations" + ], + "recommendation_required": false, + "claim_policy": "citation_or_explicit_inference" + } + ] +} diff --git a/pyproject.toml b/pyproject.toml index 6faa0eb..7029752 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -59,6 +59,11 @@ include-package-data = false "modules/*.json", "conformance/*.json", ] +"domain_packs.world_intelligence_planetary_defense" = [ + "*.json", + "modules/*.json", + "conformance/*.json", +] [tool.pytest.ini_options] testpaths = ["domain_packs/tests"] diff --git a/scripts/p2d_live_conflict_correction.py b/scripts/p2d_live_conflict_correction.py new file mode 100644 index 0000000..2e94c10 --- /dev/null +++ b/scripts/p2d_live_conflict_correction.py @@ -0,0 +1,1560 @@ +"""Hermetic P2D LIVE conflict, correction, supersession, and Reality Brief proof.""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from ace.application import ( + LIVE_SOURCE_RECORD_SPACE, + DomainActivationAdmissionService, + LiveIntelligenceBridgeService, + LiveSourceIngressService, + bind_committed_activation, +) +from ace.core import ( + AppendOnlyTransactionRequestV1, + AuthenticatedRuntimeContextV1Alpha1, + CapabilityArtifactIdentityV1Alpha1, + GovernedActionAuthorizationRequestV1Alpha1, + GovernedOperationBindingV1Alpha1, + GovernedStateHeadPreconditionV1Alpha1, + ImmutableRecordV1, + ResolvedSourceDefinitionV1Alpha1, + canonical_hash, + canonical_json, + capability_state_ref_for_artifact, + immutable_record_storage_id, +) +from ace.intelligence import ( + ActivationState, + AuthorityBindingV1, + BriefDraftClaimV1Alpha1, + BriefDraftSectionV1Alpha1, + CapabilityBindingV1, + CaseV1Alpha1, + ClaimGroundingKind, + IntelligenceResourceMode, + LineageRelation, + LineageResourceKind, + LiveDerivationRequestV1Alpha1, + LiveSourceIngressRequestV1Alpha1, + OrganizationOverlayV1, + resource_reference, +) +from ace.intelligence.contracts.epistemic import ( + BRIEF_DERIVATION_FAMILY_STATUS_PROJECTION_KIND, + BriefDraftClaimStatusBindingV1Alpha1, + BriefEpistemicStatusProjectionV1Alpha2, + DerivationFamilyMembershipV1Alpha1, +) +from ace.intelligence.contracts.ledger import resource_available_at, resource_kind +from ace.intelligence.contracts.resources import ( + CanonicalJsonValueV1Alpha1, + EvidenceAcquisitionMode, + ObservationV1Alpha1, +) +from ace.intelligence.contracts.supersession import ( + SUPERSESSION_IMPACT_PROJECTION_KIND, + SupersessionClaimImpactV1Alpha1, + SupersessionImpactPathV1Alpha1, + SupersessionImpactProjectionV1Alpha1, +) +from ace.intelligence.contracts.synthesis import BriefSynthesisDraftV1Alpha2 +from ace.intelligence.derivation import ( + COLLAPSING_RELATIONS, + DERIVATION_FAMILY_POLICY, + derive_observation_families, +) +from ace.intelligence.epistemic import derive_claim_epistemic_statuses_with_families +from ace.intelligence.packs import ( + compile_overlay, + compile_pack_document, + prepare_activation_revision, + prepare_domain_activation, +) +from ace.intelligence.packs.runtime import ( + resolve_brief_synthesis_policy, + resolve_epistemic_status_policy, +) +from ace.intelligence.supersession import ( + IMPACT_RELATIONS, + SUPERSESSION_IMPACT_POLICY, + SupersessionImpactError, + project_claim_impact, + project_supersession_impact, +) +from ace.intelligence.synthesis import assemble_canonical_brief +from ace.testing import InMemoryImmutableRecordStore +from ace_world_federal_register_source import ( + ESA_PLANETARY_DEFENCE_IMPLEMENTATION_ID, + NASA_PLANETARY_DEFENSE_IMPLEMENTATION_ID, + PLANETARY_DEFENSE_IMPLEMENTATION_VERSION, + PlanetaryDefenseRetrievalResult, + PlanetaryDefenseSourceAdapter, +) + +from scripts.ai_command_center_live_acceptance import ( + ExactAdapterRegistry, + ExactAppendAuthorizer, + ExactRuntimeUse, + ExactSourceDefinitions, + RuntimeBinding, + _head, + _lineage, +) +from scripts.p2c_federal_register_live_acceptance import ( + ExactActivationAuthority, + MemoryGovernedStateStore, + SequenceClock, +) + +REPO_ROOT = Path(__file__).resolve().parents[1] +PACK_ROOT = REPO_ROOT / "domain_packs" / "world_intelligence_planetary_defense" +FIXTURE_PATH = PACK_ROOT / "conformance" / "p2d_live_conflict_correction_input.json" +LIVE_BRIEF_ASSEMBLY_RECEIPT_KIND = "live_brief_assembly_receipt" +LIVE_BRIEF_ASSEMBLY_RECEIPT_CONTRACT = "ace.world-intelligence.live-brief-assembly-receipt/v1alpha1" +APPEND_ARTIFACT = CapabilityArtifactIdentityV1Alpha1( + capability="append_immutable_records", + contract="ace.core.immutable-record-appender/v1alpha1", + implementation_id="world_planetary_defense_live_append_fixture", + implementation_version="0.1.0", + artifact_digest="sha256:" + "2" * 64, +) + + +def _time(value: str) -> datetime: + parsed = datetime.fromisoformat(value) + if parsed.tzinfo is None or parsed.utcoffset() is None: + raise ValueError("fixture time must include a timezone") + return parsed.astimezone(UTC) + + +def load_fixture() -> dict[str, Any]: + return json.loads(FIXTURE_PATH.read_text(encoding="utf-8")) + + +def compile_planetary_defense_pack(): + manifest_bytes = (PACK_ROOT / "manifest.json").read_bytes() + manifest = json.loads(manifest_bytes) + return compile_pack_document( + manifest_bytes, + {item["path"]: (PACK_ROOT / item["path"]).read_bytes() for item in manifest["resources"]}, + ) + + +class RecordedPublicationTransport: + """Network-free exact results keyed by reviewed URI.""" + + def __init__(self, results: tuple[PlanetaryDefenseRetrievalResult, ...]) -> None: + self.results = {item.requested_uri: item for item in results} + self.calls: dict[str, int] = {item.requested_uri: 0 for item in results} + + async def retrieve(self, request): + result = self.results.get(request.requested_uri) + if result is None: + raise ValueError("recorded transport crossed its exact URI set") + self.calls[request.requested_uri] += 1 + return result + + +@dataclass +class P2DEnvironment: + fixture: dict[str, Any] + pack: Any + context: AuthenticatedRuntimeContextV1Alpha1 + activation_service: DomainActivationAdmissionService + committed_activation: Any + store: InMemoryImmutableRecordStore + definitions: ExactSourceDefinitions + runtime_use: ExactRuntimeUse + registry: ExactAdapterRegistry + requests: dict[str, LiveSourceIngressRequestV1Alpha1] + source_fixtures: dict[str, dict[str, Any]] + adapters: dict[str, PlanetaryDefenseSourceAdapter] + transports: dict[str, RecordedPublicationTransport] + append_binding: GovernedOperationBindingV1Alpha1 + activation_head: Any + append_head: Any + + def ingress(self, clock: SequenceClock) -> LiveSourceIngressService: + return LiveSourceIngressService( + activation_service=self.activation_service, + source_definitions=self.definitions, + runtime_use=self.runtime_use, + adapters=self.registry, + store=self.store, + clock=clock, + max_payload_chars=512_000, + ) + + +def _artifact(claimant: dict[str, Any]) -> CapabilityArtifactIdentityV1Alpha1: + implementation_id = { + "NASA": NASA_PLANETARY_DEFENSE_IMPLEMENTATION_ID, + "ESA": ESA_PLANETARY_DEFENCE_IMPLEMENTATION_ID, + }[claimant["claimant_org"]] + return CapabilityArtifactIdentityV1Alpha1( + capability="source_snapshot", + contract="ace.source.snapshot/v1alpha1", + implementation_id=implementation_id, + implementation_version=PLANETARY_DEFENSE_IMPLEMENTATION_VERSION, + artifact_digest=claimant["artifact_digest"], + ) + + +async def build_environment() -> P2DEnvironment: + fixture = load_fixture() + pack = compile_planetary_defense_pack() + product_id = fixture["product_id"] + context = AuthenticatedRuntimeContextV1Alpha1( + product_id=product_id, + actor_ref=fixture["actor_ref"], + authentication_receipt_ref=fixture["authentication"]["receipt_ref"], + authentication_receipt_digest=fixture["authentication"]["receipt_digest"], + authenticated_at=_time(fixture["authentication"]["authenticated_at"]), + expires_at=_time(fixture["authentication"]["expires_at"]), + ) + claimants = {item["claimant_org"]: item for item in fixture["claimants"]} + artifacts = {name: _artifact(item) for name, item in claimants.items()} + overlay = compile_overlay( + pack, + OrganizationOverlayV1( + overlay_id=fixture["activation"]["overlay_id"], + version=fixture["activation"]["overlay_version"], + pack_id=pack.metadata.pack_id, + pack_version=pack.metadata.version, + pack_digest=pack.pack_digest, + ), + ) + spec = prepare_domain_activation( + product_id=product_id, + activation_key=fixture["activation_key"], + pack=pack, + overlay=overlay, + compilation_receipt_ref=fixture["activation"]["compilation_receipt_ref"], + conformance_receipt_refs=(fixture["activation"]["conformance_receipt_ref"],), + capability_bindings=tuple( + CapabilityBindingV1( + requirement_id=item["capability_requirement_id"], + capability=artifacts[name].capability, + contract=artifacts[name].contract, + implementation_id=artifacts[name].implementation_id, + implementation_version=artifacts[name].implementation_version, + artifact_digest=artifacts[name].artifact_digest, + configuration_ref=item["configuration_ref"], + secret_ref=None, + ) + for name, item in claimants.items() + ), + authority_bindings=tuple( + AuthorityBindingV1( + request_id=item["authority_request_id"], + authority="source_read", + grant_ref=item["grant_ref"], + ) + for item in claimants.values() + ), + ) + revision = prepare_activation_revision( + spec=spec, + state=ActivationState.ACTIVE, + actor_ref=fixture["actor_ref"], + approval_receipt_ref=fixture["activation"]["approval_receipt_ref"], + occurred_at=_time(fixture["activation"]["occurred_at"]), + ) + activation_store = MemoryGovernedStateStore() + activation_service = DomainActivationAdmissionService( + store=activation_store, + authority=ExactActivationAuthority(), + ) + committed = await activation_service.admit( + revision, + expected_head_revision_id=None, + committed_at=_time(fixture["activation"]["committed_at"]), + ) + activation_head = activation_store.heads[("domain_activation", product_id, committed.revision.activation_id)] + + heads = [] + runtime_bindings = [] + for index, (name, item) in enumerate(claimants.items(), start=1): + artifact = artifacts[name] + capability_head = _head( + product_id=product_id, + state_kind="capability_state", + state_id=capability_state_ref_for_artifact(artifact), + sequence=index, + updated_at=_time(fixture["activation"]["committed_at"]), + ) + grant_head = _head( + product_id=product_id, + state_kind="authority_grant", + state_id=item["grant_ref"], + sequence=index + 10, + updated_at=_time(fixture["activation"]["committed_at"]), + ) + heads.extend((capability_head, grant_head)) + runtime_bindings.append( + RuntimeBinding( + artifact=artifact, + configuration_ref=item["configuration_ref"], + capability_head=capability_head, + grant_ref=item["grant_ref"], + grant_hash=item["grant_hash"], + grant_head=grant_head, + ) + ) + + definitions = [] + requests = {} + source_fixtures = {item["source_key"]: item for item in fixture["sources"]} + source_heads = [] + for index, source in enumerate(fixture["sources"], start=1): + claimant = claimants[source["claimant_org"]] + source_head = _head( + product_id=product_id, + state_kind="source_definition", + state_id=source["source_definition_ref"], + sequence=index + 20, + updated_at=_time(fixture["activation"]["committed_at"]), + ) + source_heads.append(source_head) + definitions.append( + ResolvedSourceDefinitionV1Alpha1( + product_id=product_id, + source_definition_ref=source["source_definition_ref"], + source_type_ref=claimant["source_type_ref"], + configuration_ref=claimant["configuration_ref"], + configuration_digest=claimant["configuration_digest"], + authorized_uri=source["requested_uri"], + subject_binding_id=fixture["subject_binding_id"], + entity_type_id=fixture["entity_type_id"], + entity_ref=fixture["entity_ref"], + state_head_precondition=GovernedStateHeadPreconditionV1Alpha1.from_head(source_head), + ) + ) + requests[source["source_key"]] = LiveSourceIngressRequestV1Alpha1( + product_id=product_id, + authenticated_context=context, + idempotency_key=source["idempotency_key"], + activation_key=fixture["activation_key"], + mapping_id=source["mapping_id"], + source_definition_ref=source["source_definition_ref"], + compiled_pack_id=pack.compiled_pack_id, + pack_digest=pack.pack_digest, + requested_at=_time(source["requested_at"]), + ) + + results_by_claimant: dict[str, list[PlanetaryDefenseRetrievalResult]] = { + "NASA": [], + "ESA": [], + } + for source in fixture["sources"]: + claimant = claimants[source["claimant_org"]] + results_by_claimant[source["claimant_org"]].append( + PlanetaryDefenseRetrievalResult( + source_type_ref=claimant["source_type_ref"], + requested_uri=source["requested_uri"], + effective_uri=source["requested_uri"], + status_code=200, + media_type=source["media_type"], + response_body=source["response_body"], + redirect_chain=(), + resolved_ip_addresses=("1.1.1.1",), + connected_ip_addresses=("1.1.1.1",), + dns_rebinding_protection_applied=True, + credentials_used=False, + locator=source["locator"], + observed_at=_time(source["observed_at"]), + captured_at=_time(source["captured_at"]), + ) + ) + transports = {name: RecordedPublicationTransport(tuple(results)) for name, results in results_by_claimant.items()} + adapters = { + name: PlanetaryDefenseSourceAdapter( + transport=transports[name], + artifact_digest=artifacts[name].artifact_digest, + source_type_ref=claimants[name]["source_type_ref"], + ) + for name in claimants + } + append_head = _head( + product_id=product_id, + state_kind="governed_operation_configuration", + state_id="governed_operation_configuration:world-planetary-defense-live-append", + sequence=50, + updated_at=_time(fixture["activation"]["committed_at"]), + ) + append_binding = GovernedOperationBindingV1Alpha1( + product_id=product_id, + artifact=APPEND_ARTIFACT, + configuration_ref=append_head.state_id, + authority="append_immutable_records", + grant_ref="authority_grant:world-planetary-defense-live-append", + state_head_precondition=GovernedStateHeadPreconditionV1Alpha1.from_head(append_head), + ) + store = InMemoryImmutableRecordStore() + for head in (activation_head, *heads, *source_heads, append_head): + store.set_governed_state_head(head) + return P2DEnvironment( + fixture=fixture, + pack=pack, + context=context, + activation_service=activation_service, + committed_activation=committed, + store=store, + definitions=ExactSourceDefinitions(tuple(definitions)), + runtime_use=ExactRuntimeUse(context=context, bindings=tuple(runtime_bindings)), + registry=ExactAdapterRegistry(tuple(adapters.values())), + requests=requests, + source_fixtures=source_fixtures, + adapters=adapters, + transports=transports, + append_binding=append_binding, + activation_head=activation_head, + append_head=append_head, + ) + + +async def _append_record( + *, + environment: P2DEnvironment, + authorizer: ExactAppendAuthorizer, + record: ImmutableRecordV1, + subject_ref: str, + subject_digest: str, + transaction_key: str, + submitted_at: datetime, +) -> bool: + authorization = await authorizer.authorize_action( + GovernedActionAuthorizationRequestV1Alpha1( + authorization_key=f"append:{subject_ref}", + product_id=record.product_id, + authenticated_context=environment.context, + execution_binding=environment.append_binding, + operation="append_immutable_records", + subject_ref=subject_ref, + subject_digest=subject_digest, + requested_at=submitted_at, + required_state_preconditions=( + GovernedStateHeadPreconditionV1Alpha1.from_head(environment.activation_head), + GovernedStateHeadPreconditionV1Alpha1.from_head(environment.append_head), + ), + ) + ) + append = AppendOnlyTransactionRequestV1( + product_id=record.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + transaction_key=transaction_key, + records=(record,), + submitted_at=submitted_at, + governed_state_preconditions=authorization.state_preconditions, + ) + prior = await environment.store.load_transaction_receipt( + product_id=record.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + transaction_key=transaction_key, + ) + if prior is not None: + if prior != append.receipt(): + raise AssertionError("LIVE append replay crossed exact transaction material") + return True + receipt = await environment.store.append(append) + if receipt != append.receipt(): + raise AssertionError("LIVE append did not preserve exact receipt material") + return False + + +async def _append_resource( + *, + environment: P2DEnvironment, + authorizer: ExactAppendAuthorizer, + resource, + transaction_key: str, + submitted_at: datetime, +) -> bool: + return await _append_record( + environment=environment, + authorizer=authorizer, + record=ImmutableRecordV1( + product_id=resource.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + record_kind=resource_kind(resource).value, + record_key=str(resource.resource_id), + payload_contract=resource.contract, + payload=resource.model_dump(mode="python"), + as_of=resource.as_of, + available_at=resource_available_at(resource), + processing_order=0, + ), + subject_ref=str(resource.resource_id), + subject_digest=str(resource.resource_digest), + transaction_key=transaction_key, + submitted_at=submitted_at, + ) + + +async def _admit_source(environment: P2DEnvironment, source_key: str): + source = environment.source_fixtures[source_key] + service = environment.ingress( + SequenceClock( + _time(source["capture_started_at"]), + _time(source["rechecked_at"]), + _time(source["admitted_at"]), + ) + ) + admission = await service.admit( + request=environment.requests[source_key], + pack=environment.pack, + ) + replay = await service.admit( + request=environment.requests[source_key], + pack=environment.pack, + ) + if admission.replayed or not replay.replayed: + raise AssertionError("LIVE source admission replay was not explicit") + return admission + + +def _snapshot_reference(admission): + available_at = next( + item.available_at for item in admission.transaction_receipt.records if item.record_kind == "entity_snapshot" + ) + return resource_reference(admission.entity_snapshot).model_copy(update={"available_at": available_at}) + + +async def _derive( + environment: P2DEnvironment, + *, + authorizer: ExactAppendAuthorizer, + binding, + derivation_fixture: dict[str, Any], + admissions: dict[str, Any], +): + request = LiveDerivationRequestV1Alpha1( + derivation_key=derivation_fixture["derivation_key"], + product_id=environment.fixture["product_id"], + authenticated_context=environment.context, + activation_revision=binding.prepared_binding.reference, + pack=binding.prepared_binding.revision.spec.pack, + detector_id=derivation_fixture["detector_id"], + baseline=_snapshot_reference(admissions[derivation_fixture["baseline_source_key"]]), + current=_snapshot_reference(admissions[derivation_fixture["current_source_key"]]), + detected_at=_time(derivation_fixture["detected_at"]), + attention_evaluated_at=_time(derivation_fixture["attention_evaluated_at"]), + requested_at=_time(derivation_fixture["requested_at"]), + ) + bridge = LiveIntelligenceBridgeService( + activation_service=environment.activation_service, + pack=environment.pack, + store=environment.store, + authorizer=authorizer, + operation_binding=environment.append_binding, + ) + admission = await bridge.derive(request) + replay = await bridge.derive(request) + if admission.replayed or not replay.replayed: + raise AssertionError("LIVE Shift/Signal replay was not explicit") + return admission + + +def _draft(policy, specifications: tuple[dict[str, Any], ...]) -> BriefSynthesisDraftV1Alpha2: + claims = tuple( + BriefDraftClaimV1Alpha1( + statement=item["statement"], + grounding_kind=item["grounding_kind"], + support_refs=tuple(str(resource.resource_id) for resource in item["supports"]), + confidence=item["confidence"], + uncertainty=item.get("uncertainty"), + ) + for item in specifications + ) + return BriefSynthesisDraftV1Alpha2( + brief_type=policy.template.brief_type, + persona_ids=tuple(item.persona_id for item in policy.personas), + sections=tuple( + BriefDraftSectionV1Alpha1( + section_id=specification["section_id"], + claims=(claim,), + ) + for specification, claim in zip(specifications, claims, strict=True) + ), + claim_statuses=tuple( + BriefDraftClaimStatusBindingV1Alpha1( + draft_claim_id=str(claim.claim_id), + status_id=specification["status_id"], + ) + for specification, claim in zip(specifications, claims, strict=True) + ), + recommendation_claim_id=None, + ) + + +def _historical_draft(policy, *, observations, derivation, case): + esa, nasa = observations + return _draft( + policy, + ( + { + "section_id": "what_changed", + "statement": ( + "ACE detected a material dated difference between ESA's 1.8% estimate " + "and NASA's next-day 2.3% estimate for the same 2032 Earth-impact event." + ), + "grounding_kind": ClaimGroundingKind.INFERENCE, + "supports": (case,), + "confidence": 0.9, + "uncertainty": ("The detector reports quantitative divergence, not which estimate was more accurate."), + "status_id": "ace_inference", + }, + { + "section_id": "established_records", + "statement": ( + "NASA's 7 February 2025 publication reported a 2.3% Earth-impact probability for 22 December 2032." + ), + "grounding_kind": ClaimGroundingKind.CITED, + "supports": (nasa,), + "confidence": 1.0, + "status_id": "attributed_claim", + }, + { + "section_id": "source_comparison", + "statement": ( + "ESA's 6 February 2025 publication reported a 1.8% Earth-impact risk for 22 December 2032." + ), + "grounding_kind": ClaimGroundingKind.CITED, + "supports": (esa,), + "confidence": 1.0, + "status_id": "attributed_claim", + }, + { + "section_id": "where_sources_conflict", + "statement": ( + "The admitted NASA and ESA publications carried materially different " + "dated estimates for the same event." + ), + "grounding_kind": ClaimGroundingKind.INFERENCE, + "supports": (esa, nasa, derivation.shift), + "confidence": 0.95, + "uncertainty": ( + "The estimates were published on different dates while new observations " + "were arriving, so the difference is not evidence of misconduct or falsehood." + ), + "status_id": "disputed", + }, + { + "section_id": "current_orientation", + "statement": ( + "At this historical cutoff, the admitted official record consists of the " + "ESA 1.8% and NASA 2.3% dated estimates." + ), + "grounding_kind": ClaimGroundingKind.CITED, + "supports": (esa, nasa), + "confidence": 1.0, + "status_id": "admitted_record", + }, + { + "section_id": "correction_visibility", + "statement": "No later correction is admitted inside this historical cutoff.", + "grounding_kind": ClaimGroundingKind.INFERENCE, + "supports": (derivation.signal,), + "confidence": 0.8, + "uncertainty": "Later source records may revise either estimate.", + "status_id": "unknown", + }, + { + "section_id": "unknowns", + "statement": ( + "The historical Case does not establish the eventual Earth-impact estimate " + "or which later observations will narrow the modeled trajectory." + ), + "grounding_kind": ClaimGroundingKind.INFERENCE, + "supports": (case,), + "confidence": 0.8, + "uncertainty": "The estimate is expected to evolve with additional observations.", + "status_id": "unknown", + }, + { + "section_id": "limitations", + "statement": ( + "NASA and ESA are separate official claimant lineages, but these publications " + "do not prove independent measurements or a final impact outcome." + ), + "grounding_kind": ClaimGroundingKind.CITED, + "supports": (esa, nasa), + "confidence": 1.0, + "status_id": "admitted_record", + }, + ), + ) + + +def _corrected_draft( + policy, + *, + observations, + divergence, + nasa_revision, + esa_revision, + assertions, + case, +): + esa_initial, nasa_initial, nasa_revised, esa_revised = observations + nasa_assertion, esa_assertion = assertions + return _draft( + policy, + ( + { + "section_id": "what_changed", + "statement": ( + "Later official publications revised NASA's estimate from 2.3% to 0.004% " + "and ESA's estimate from 1.8% to 0.001%." + ), + "grounding_kind": ClaimGroundingKind.INFERENCE, + "supports": (case, nasa_revision.shift, esa_revision.shift), + "confidence": 0.95, + "uncertainty": ( + "ACE classifies the admitted numeric changes; it does not reproduce the orbital models." + ), + "status_id": "ace_inference", + }, + { + "section_id": "established_records", + "statement": ( + "NASA published a 2.3% estimate on 7 February and a revised 0.004% estimate on 24 February 2025." + ), + "grounding_kind": ClaimGroundingKind.CITED, + "supports": (nasa_initial, nasa_assertion), + "confidence": 1.0, + "status_id": "admitted_record", + }, + { + "section_id": "source_comparison", + "statement": ( + "ESA published a 1.8% estimate on 6 February and a revised 0.001% estimate on 25 February 2025." + ), + "grounding_kind": ClaimGroundingKind.CITED, + "supports": (esa_initial, esa_assertion), + "confidence": 1.0, + "status_id": "admitted_record", + }, + { + "section_id": "where_sources_conflict", + "statement": ( + "The earlier NASA and ESA publications contained a material dated estimate " + "divergence before later observations narrowed both assessments." + ), + "grounding_kind": ClaimGroundingKind.INFERENCE, + "supports": (esa_initial, nasa_initial, divergence.shift), + "confidence": 0.95, + "uncertainty": ( + "A dated estimate divergence is not a truth verdict and does not imply the " + "agencies used independent observation sets." + ), + "status_id": "disputed", + }, + { + "section_id": "current_orientation", + "statement": ( + "The later NASA and ESA publications independently report very low Earth-impact " + "estimates of 0.004% and 0.001%, respectively." + ), + "grounding_kind": ClaimGroundingKind.CITED, + "supports": (nasa_assertion, esa_assertion), + "confidence": 1.0, + "status_id": "corroborated", + }, + { + "section_id": "correction_visibility", + "statement": ( + "The two later records explicitly supersede their same-source predecessors, " + "and the routed revision Signals preserve those corrections as additive LIVE material." + ), + "grounding_kind": ClaimGroundingKind.INFERENCE, + "supports": ( + nasa_revised, + esa_revised, + nasa_revision.signal, + esa_revision.signal, + ), + "confidence": 0.95, + "uncertainty": ( + "Supersession impact identifies dependency and does not declare every affected claim false." + ), + "status_id": "ace_inference", + }, + { + "section_id": "unknowns", + "statement": ( + "The admitted publications do not establish independent measurement provenance, " + "future model revisions, or the asteroid's eventual physical trajectory." + ), + "grounding_kind": ClaimGroundingKind.INFERENCE, + "supports": (case, divergence.signal), + "confidence": 0.8, + "uncertainty": "Additional observations and official revisions may change the assessment.", + "status_id": "unknown", + }, + { + "section_id": "limitations", + "statement": ( + "All four citations are official publications from two claimant roots; they " + "do not constitute independent replication of the underlying orbital analysis." + ), + "grounding_kind": ClaimGroundingKind.CITED, + "supports": (esa_initial, nasa_initial, nasa_assertion, esa_assertion), + "confidence": 1.0, + "status_id": "admitted_record", + }, + ), + ) + + +def _record_kind_index(closure: tuple) -> dict[str, LineageResourceKind]: + return {str(item.resource_id): LineageResourceKind(resource_kind(item).value) for item in closure} + + +async def _append_status_projection( + *, + environment: P2DEnvironment, + authorizer: ExactAppendAuthorizer, + binding, + draft: BriefSynthesisDraftV1Alpha2, + assembly, + closure: tuple, + template_id: str, + generated_at: datetime, + transaction_prefix: str, +): + brief = assembly.brief + status_policy = resolve_epistemic_status_policy( + binding.prepared_binding, + template_id=template_id, + ) + families = derive_observation_families(closure=closure) + claim_statuses = derive_claim_epistemic_statuses_with_families( + draft=draft, + policy=status_policy, + claim_supports=assembly.claim_supports, + kind_by_record_id=_record_kind_index(closure), + families=families, + ) + receipt_material = { + "contract": LIVE_BRIEF_ASSEMBLY_RECEIPT_CONTRACT, + "product_id": brief.product_id, + "brief_id": str(brief.resource_id), + "brief_digest": str(brief.resource_digest), + "draft_id": str(draft.draft_id), + "draft_digest": str(draft.draft_digest), + "claim_supports": [item.model_dump(mode="json") for item in assembly.claim_supports], + "created_at": generated_at.isoformat(), + } + receipt_hash = canonical_hash(receipt_material) + receipt_id = f"live_brief_assembly_receipt:{receipt_hash[:32]}" + receipt_digest = f"sha256:{receipt_hash}" + receipt_payload = { + **receipt_material, + "receipt_id": receipt_id, + "receipt_digest": receipt_digest, + } + await _append_record( + environment=environment, + authorizer=authorizer, + record=ImmutableRecordV1( + product_id=brief.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + record_kind=LIVE_BRIEF_ASSEMBLY_RECEIPT_KIND, + record_key=receipt_id, + payload_contract=LIVE_BRIEF_ASSEMBLY_RECEIPT_CONTRACT, + payload=receipt_payload, + as_of=brief.as_of, + available_at=generated_at, + processing_order=0, + ), + subject_ref=receipt_id, + subject_digest=receipt_digest, + transaction_key=f"{transaction_prefix}:assembly-receipt", + submitted_at=generated_at, + ) + projection = BriefEpistemicStatusProjectionV1Alpha2( + product_id=brief.product_id, + mode=IntelligenceResourceMode.LIVE, + activation_revision=brief.activation_revision, + brief_id=str(brief.resource_id), + brief_digest=str(brief.resource_digest), + synthesis_receipt_contract=LIVE_BRIEF_ASSEMBLY_RECEIPT_CONTRACT, + synthesis_receipt_id=receipt_id, + synthesis_receipt_digest=receipt_digest, + module_id=status_policy.module_id, + module_digest=status_policy.module_digest, + status_set_id=status_policy.status_set.status_set_id, + status_set_digest=status_policy.status_set_digest, + template_id=status_policy.template_id, + declared_status_ids=tuple(item.status_id for item in status_policy.status_set.statuses), + claim_statuses=claim_statuses, + derivation_family_policy=DERIVATION_FAMILY_POLICY, + collapsing_relations=tuple(item.value for item in COLLAPSING_RELATIONS), + closure_families=tuple( + DerivationFamilyMembershipV1Alpha1( + root_record_id=root, + member_record_ids=members, + ) + for root, members in families.members_by_root.items() + ), + as_of=brief.as_of, + generated_at=generated_at, + ) + replayed = await _append_record( + environment=environment, + authorizer=authorizer, + record=ImmutableRecordV1( + product_id=brief.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + record_kind=BRIEF_DERIVATION_FAMILY_STATUS_PROJECTION_KIND, + record_key=str(projection.projection_id), + payload_contract=projection.contract, + payload=projection.model_dump(mode="python"), + as_of=projection.as_of, + available_at=projection.generated_at, + processing_order=0, + ), + subject_ref=str(projection.projection_id), + subject_digest=str(projection.projection_digest), + transaction_key=f"{transaction_prefix}:status-projection", + submitted_at=generated_at, + ) + if replayed: + raise AssertionError("first LIVE status projection append unexpectedly replayed") + exact_replay = await _append_record( + environment=environment, + authorizer=authorizer, + record=ImmutableRecordV1( + product_id=brief.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + record_kind=BRIEF_DERIVATION_FAMILY_STATUS_PROJECTION_KIND, + record_key=str(projection.projection_id), + payload_contract=projection.contract, + payload=projection.model_dump(mode="python"), + as_of=projection.as_of, + available_at=projection.generated_at, + processing_order=0, + ), + subject_ref=str(projection.projection_id), + subject_digest=str(projection.projection_digest), + transaction_key=f"{transaction_prefix}:status-projection", + submitted_at=generated_at, + ) + return projection, families, exact_replay + + +def _supersession_assertion( + *, + environment: P2DEnvironment, + binding, + earlier, + revised, + asserted_at: datetime, +) -> ObservationV1Alpha1: + revised_payload = revised.payload.parsed_value() + earlier_lineage = earlier.payload.parsed_value()["source_lineage_id"] + if revised_payload["predecessor_lineage_id"] != earlier_lineage: + raise AssertionError("revised source does not name the exact same-source predecessor") + payload = { + "assertion": "supersedes", + "claimant_org": revised_payload["claimant_org"], + "predecessor_lineage_id": earlier_lineage, + "revised_lineage_id": revised_payload["source_lineage_id"], + "basis_observation_id": str(revised.resource_id), + "superseded_observation_id": str(earlier.resource_id), + "impact_is_dependency_not_falsehood": True, + } + return ObservationV1Alpha1( + product_id=environment.fixture["product_id"], + mode=IntelligenceResourceMode.LIVE, + activation_revision=binding.prepared_binding.reference, + as_of=asserted_at, + lineage=( + _lineage(earlier, relation=LineageRelation.SUPERSEDES), + _lineage(revised, relation=LineageRelation.SUPPORTS), + ), + source_ref=revised.source_ref, + source_digest=revised.source_digest, + acquisition_mode=EvidenceAcquisitionMode.LIVE, + acquisition_receipt_ref=revised.acquisition_receipt_ref, + acquisition_receipt_digest=revised.acquisition_receipt_digest, + source_published_at=revised.source_published_at, + event_effective_at=None, + observed_at=revised.observed_at, + ingested_at=asserted_at, + subject_refs=(environment.fixture["entity_ref"],), + payload=CanonicalJsonValueV1Alpha1(value_json=canonical_json(payload)), + confidence=1.0, + ) + + +def _impact_projection( + *, + environment: P2DEnvironment, + binding, + assertion, + target, + closure: tuple, + assembly, + historical_case, + historical_status, + generated_at: datetime, +) -> SupersessionImpactProjectionV1Alpha1: + impact = project_supersession_impact( + superseder=assertion, + superseded_resource_id=str(target.resource_id), + closure=closure, + cutoff_at=generated_at, + ) + claim_impacts = tuple( + SupersessionClaimImpactV1Alpha1( + brief_id=str(assembly.brief.resource_id), + claim_id=claim_id, + impacted_support_record_ids=touched, + total_support_count=total, + fully_impacted=fully, + ) + for claim_id, touched, total, fully in project_claim_impact( + impact=impact, + brief_id=str(assembly.brief.resource_id), + claim_supports=assembly.claim_supports, + ) + ) + assertion_reference = resource_reference(assertion) + target_reference = resource_reference(target) + return SupersessionImpactProjectionV1Alpha1( + product_id=environment.fixture["product_id"], + mode=IntelligenceResourceMode.LIVE, + activation_revision=binding.prepared_binding.reference, + superseder_resource_id=impact.superseder_resource_id, + superseder_resource_digest=assertion_reference.resource_digest, + superseder_available_at=assertion_reference.available_at, + superseded_resource_id=impact.superseded_resource_id, + superseded_resource_digest=target_reference.resource_digest, + superseded_resource_kind=LineageResourceKind(target_reference.resource_kind.value), + impact_policy=SUPERSESSION_IMPACT_POLICY, + eligible_relations=tuple(item.value for item in IMPACT_RELATIONS), + closure_cutoff_at=generated_at, + closure_resource_ids=impact.closure_resource_ids, + impacted=tuple( + SupersessionImpactPathV1Alpha1( + resource_id=item.resource_id, + resource_kind=item.resource_kind, + resource_digest=item.resource_digest, + depth=item.depth, + via_resource_id=item.via_resource_id, + via_relation=item.via_relation, + ) + for item in impact.impacted + ), + unaffected_resource_ids=impact.unaffected_resource_ids, + claim_impacts=claim_impacts, + preserved_artifact_ids=( + str(historical_case.resource_id), + str(assembly.brief.resource_id), + str(historical_status.projection_id), + ), + as_of=assembly.brief.as_of, + generated_at=generated_at, + ) + + +async def _append_impact_projection( + *, + environment: P2DEnvironment, + authorizer: ExactAppendAuthorizer, + projection: SupersessionImpactProjectionV1Alpha1, + transaction_key: str, +) -> bool: + record = ImmutableRecordV1( + product_id=projection.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + record_kind=SUPERSESSION_IMPACT_PROJECTION_KIND, + record_key=str(projection.projection_id), + payload_contract=projection.contract, + payload=projection.model_dump(mode="python"), + as_of=projection.as_of, + available_at=projection.generated_at, + processing_order=0, + ) + first = await _append_record( + environment=environment, + authorizer=authorizer, + record=record, + subject_ref=str(projection.projection_id), + subject_digest=str(projection.projection_digest), + transaction_key=transaction_key, + submitted_at=projection.generated_at, + ) + if first: + raise AssertionError("first LIVE impact append unexpectedly replayed") + return await _append_record( + environment=environment, + authorizer=authorizer, + record=record, + subject_ref=str(projection.projection_id), + subject_digest=str(projection.projection_digest), + transaction_key=transaction_key, + submitted_at=projection.generated_at, + ) + + +def _negative_vectors(*, nasa_assertion, nasa_revised, nasa_initial, esa_initial, closure, cutoff): + cases = { + "cross_claimant_target": (nasa_assertion, esa_initial, closure, cutoff), + "missing_target": ( + nasa_assertion, + nasa_initial, + tuple(item for item in closure if item != nasa_initial), + cutoff, + ), + "future_leakage": (nasa_assertion, nasa_initial, closure, closure[0].as_of), + "derived_from_is_not_supersession": (nasa_revised, nasa_initial, closure, cutoff), + } + results = {} + for name, (superseder, target, exact_closure, exact_cutoff) in cases.items(): + try: + project_supersession_impact( + superseder=superseder, + superseded_resource_id=str(target.resource_id), + closure=exact_closure, + cutoff_at=exact_cutoff, + ) + except SupersessionImpactError as exc: + results[name] = {"rejected": True, "error_type": type(exc).__name__} + else: + results[name] = {"rejected": False} + return results + + +async def run_acceptance() -> dict[str, Any]: + environment = await build_environment() + authorizer = ExactAppendAuthorizer() + binding = bind_committed_activation( + pack=environment.pack, + committed=environment.committed_activation, + ) + admissions = {key: await _admit_source(environment, key) for key in ("esa_initial", "nasa_initial")} + divergence = await _derive( + environment, + authorizer=authorizer, + binding=binding, + derivation_fixture=environment.fixture["derivations"]["divergence"], + admissions=admissions, + ) + historical_time = _time(environment.fixture["historical"]["case_assembled_at"]) + historical_observations = ( + admissions["esa_initial"].observation, + admissions["nasa_initial"].observation, + ) + historical_case = CaseV1Alpha1( + product_id=environment.fixture["product_id"], + mode=IntelligenceResourceMode.LIVE, + activation_revision=binding.prepared_binding.reference, + as_of=max( + divergence.signal.as_of, + *(item.as_of for item in historical_observations), + ), + lineage=( + _lineage(divergence.shift, relation=LineageRelation.DERIVED_FROM), + _lineage(divergence.signal, relation=LineageRelation.DERIVED_FROM), + *(_lineage(item, relation=LineageRelation.SUPPORTS) for item in historical_observations), + ), + case_type_ref="case_type:planetary_defense_estimate_divergence", + title="Historical NASA/ESA 2024 YR4 estimate divergence", + purpose="Freeze the exact earlier official estimates before later revisions arrive.", + subject_refs=(environment.fixture["entity_ref"],), + assembled_at=historical_time, + ) + await _append_resource( + environment=environment, + authorizer=authorizer, + resource=historical_case, + transaction_key="live-case:planetary-defense:historical-divergence", + submitted_at=historical_time, + ) + policy = resolve_brief_synthesis_policy( + binding.prepared_binding, + template_id=str(divergence.attention_receipt.brief_template_id), + persona_ids=divergence.attention_receipt.persona_ids, + ) + historical_closure = ( + *historical_observations, + divergence.shift, + divergence.signal, + historical_case, + ) + historical_draft = _historical_draft( + policy, + observations=historical_observations, + derivation=divergence, + case=historical_case, + ) + historical_brief_time = _time(environment.fixture["historical"]["brief_generated_at"]) + historical_assembly = assemble_canonical_brief( + product_id=environment.fixture["product_id"], + activation_revision=binding.prepared_binding.reference, + brief_as_of=_time(environment.fixture["historical"]["brief_as_of"]), + generated_at=historical_brief_time, + draft=historical_draft, + policy=policy, + closure=historical_closure, + observations=historical_observations, + selected_context=(), + mode=IntelligenceResourceMode.LIVE, + ) + historical_brief = historical_assembly.brief + await _append_resource( + environment=environment, + authorizer=authorizer, + resource=historical_brief, + transaction_key="live-brief:planetary-defense:historical-divergence", + submitted_at=historical_brief_time, + ) + historical_status, historical_families, historical_status_replay = await _append_status_projection( + environment=environment, + authorizer=authorizer, + binding=binding, + draft=historical_draft, + assembly=historical_assembly, + closure=historical_closure, + template_id=policy.template.template_id, + generated_at=_time(environment.fixture["historical"]["status_generated_at"]), + transaction_prefix="live-status:planetary-defense:historical", + ) + + for key in ("nasa_revised", "esa_revised"): + admissions[key] = await _admit_source(environment, key) + asserted_at = _time(environment.fixture["correction"]["asserted_at"]) + nasa_assertion = _supersession_assertion( + environment=environment, + binding=binding, + earlier=admissions["nasa_initial"].observation, + revised=admissions["nasa_revised"].observation, + asserted_at=asserted_at, + ) + esa_assertion = _supersession_assertion( + environment=environment, + binding=binding, + earlier=admissions["esa_initial"].observation, + revised=admissions["esa_revised"].observation, + asserted_at=asserted_at, + ) + for name, assertion in (("nasa", nasa_assertion), ("esa", esa_assertion)): + await _append_resource( + environment=environment, + authorizer=authorizer, + resource=assertion, + transaction_key=f"live-supersession-assertion:planetary-defense:{name}", + submitted_at=asserted_at, + ) + + impact_time = _time(environment.fixture["correction"]["impact_generated_at"]) + impact_closure = ( + admissions["esa_initial"].observation, + admissions["nasa_initial"].observation, + admissions["esa_initial"].entity_snapshot, + admissions["nasa_initial"].entity_snapshot, + divergence.shift, + divergence.signal, + historical_case, + historical_brief, + ) + nasa_impact = _impact_projection( + environment=environment, + binding=binding, + assertion=nasa_assertion, + target=admissions["nasa_initial"].observation, + closure=impact_closure, + assembly=historical_assembly, + historical_case=historical_case, + historical_status=historical_status, + generated_at=impact_time, + ) + esa_impact = _impact_projection( + environment=environment, + binding=binding, + assertion=esa_assertion, + target=admissions["esa_initial"].observation, + closure=impact_closure, + assembly=historical_assembly, + historical_case=historical_case, + historical_status=historical_status, + generated_at=impact_time, + ) + nasa_impact_replay = await _append_impact_projection( + environment=environment, + authorizer=authorizer, + projection=nasa_impact, + transaction_key="live-impact:planetary-defense:nasa", + ) + esa_impact_replay = await _append_impact_projection( + environment=environment, + authorizer=authorizer, + projection=esa_impact, + transaction_key="live-impact:planetary-defense:esa", + ) + negatives = _negative_vectors( + nasa_assertion=nasa_assertion, + nasa_revised=admissions["nasa_revised"].observation, + nasa_initial=admissions["nasa_initial"].observation, + esa_initial=admissions["esa_initial"].observation, + closure=impact_closure, + cutoff=impact_time, + ) + + nasa_revision = await _derive( + environment, + authorizer=authorizer, + binding=binding, + derivation_fixture=environment.fixture["derivations"]["nasa_revision"], + admissions=admissions, + ) + esa_revision = await _derive( + environment, + authorizer=authorizer, + binding=binding, + derivation_fixture=environment.fixture["derivations"]["esa_revision"], + admissions=admissions, + ) + corrected_time = _time(environment.fixture["correction"]["case_assembled_at"]) + all_observations = ( + admissions["esa_initial"].observation, + admissions["nasa_initial"].observation, + admissions["nasa_revised"].observation, + admissions["esa_revised"].observation, + ) + corrected_members = ( + *all_observations, + divergence.shift, + divergence.signal, + nasa_revision.shift, + nasa_revision.signal, + esa_revision.shift, + esa_revision.signal, + nasa_assertion, + esa_assertion, + ) + corrected_case = CaseV1Alpha1( + product_id=environment.fixture["product_id"], + mode=IntelligenceResourceMode.LIVE, + activation_revision=binding.prepared_binding.reference, + as_of=max(item.as_of for item in corrected_members), + lineage=tuple( + _lineage( + item, + relation=( + LineageRelation.SUPPORTS if isinstance(item, ObservationV1Alpha1) else LineageRelation.DERIVED_FROM + ), + ) + for item in corrected_members + ), + case_type_ref="case_type:planetary_defense_estimate_correction", + title="Corrected NASA/ESA 2024 YR4 official estimate record", + purpose=( + "Freeze the earlier divergence, later same-source revisions, and exact " + "supersession assertions for status-aware synthesis." + ), + subject_refs=(environment.fixture["entity_ref"],), + assembled_at=corrected_time, + ) + await _append_resource( + environment=environment, + authorizer=authorizer, + resource=corrected_case, + transaction_key="live-case:planetary-defense:corrected", + submitted_at=corrected_time, + ) + corrected_closure = (*corrected_members, corrected_case) + corrected_draft = _corrected_draft( + policy, + observations=all_observations, + divergence=divergence, + nasa_revision=nasa_revision, + esa_revision=esa_revision, + assertions=(nasa_assertion, esa_assertion), + case=corrected_case, + ) + corrected_brief_time = _time(environment.fixture["correction"]["brief_generated_at"]) + corrected_assembly = assemble_canonical_brief( + product_id=environment.fixture["product_id"], + activation_revision=binding.prepared_binding.reference, + brief_as_of=_time(environment.fixture["correction"]["brief_as_of"]), + generated_at=corrected_brief_time, + draft=corrected_draft, + policy=policy, + closure=corrected_closure, + observations=(*all_observations, nasa_assertion, esa_assertion), + selected_context=(), + mode=IntelligenceResourceMode.LIVE, + ) + corrected_brief = corrected_assembly.brief + await _append_resource( + environment=environment, + authorizer=authorizer, + resource=corrected_brief, + transaction_key="live-brief:planetary-defense:corrected", + submitted_at=corrected_brief_time, + ) + corrected_status, corrected_families, corrected_status_replay = await _append_status_projection( + environment=environment, + authorizer=authorizer, + binding=binding, + draft=corrected_draft, + assembly=corrected_assembly, + closure=corrected_closure, + template_id=policy.template.template_id, + generated_at=_time(environment.fixture["correction"]["status_generated_at"]), + transaction_prefix="live-status:planetary-defense:corrected", + ) + + stored_historical_brief = await environment.store.load_record( + immutable_record_storage_id( + product_id=historical_brief.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + record_kind="brief", + record_key=str(historical_brief.resource_id), + ), + product_id=historical_brief.product_id, + record_space=LIVE_SOURCE_RECORD_SPACE, + record_kind="brief", + ) + if stored_historical_brief is None: + raise AssertionError("historical LIVE Brief was not durably reopened") + reopened_historical_brief = type(historical_brief).model_validate(stored_historical_brief.payload) + source_lineages = { + key: admissions[key].entity_snapshot.attributes.parsed_value()["source_lineage_id"] for key in admissions + } + probabilities = { + key: admissions[key].entity_snapshot.attributes.parsed_value()["impact_probability_percent"] + for key in admissions + } + transport_calls = { + uri: count for transport in environment.transports.values() for uri, count in transport.calls.items() + } + live_records = tuple( + record for record in environment.store.records.values() if record.record_space == LIVE_SOURCE_RECORD_SPACE + ) + prepared_records = tuple( + record for record in environment.store.records.values() if record.record_space == "prepared" + ) + return { + "contract": "ace.world-intelligence.p2d-live-conflict-correction-proof/v1alpha1", + "pack": { + "compiled_pack_id": environment.pack.compiled_pack_id, + "pack_digest": environment.pack.pack_digest, + "module_count": len(environment.pack.modules), + "json_only": True, + }, + "source": { + "lineages": source_lineages, + "probabilities": probabilities, + "stable_entity_ref": len({item.entity_snapshot.entity_ref for item in admissions.values()}) == 1, + "adapter_capture_calls": {name: adapter.capture_calls for name, adapter in environment.adapters.items()}, + "transport_calls": transport_calls, + "independent_claimant_roots": ["ESA", "NASA"], + "network_access": False, + }, + "historical": { + "shift_type": divergence.shift.shift_type_ref, + "signal_type": divergence.signal.signal_type_ref, + "case_id": str(historical_case.resource_id), + "brief_id": str(historical_brief.resource_id), + "brief_digest": str(historical_brief.resource_digest), + "citation_count": len(historical_brief.citations), + "claim_count": len(historical_brief.claims), + "status_projection_id": str(historical_status.projection_id), + "claim_statuses": [item.status_id for item in historical_status.claim_statuses], + "family_count": len(historical_families.members_by_root), + "status_replay_exact": historical_status_replay, + }, + "correction": { + "assertion_ids": [ + str(nasa_assertion.resource_id), + str(esa_assertion.resource_id), + ], + "superseded_observation_ids": [ + str(admissions["nasa_initial"].observation.resource_id), + str(admissions["esa_initial"].observation.resource_id), + ], + "impact_projection_ids": [ + str(nasa_impact.projection_id), + str(esa_impact.projection_id), + ], + "impact_counts": { + "NASA": len(nasa_impact.impacted), + "ESA": len(esa_impact.impacted), + }, + "impacted_claim_counts": { + "NASA": len(nasa_impact.claim_impacts), + "ESA": len(esa_impact.claim_impacts), + }, + "unaffected_counts": { + "NASA": len(nasa_impact.unaffected_resource_ids), + "ESA": len(esa_impact.unaffected_resource_ids), + }, + "impact_replay_exact": nasa_impact_replay and esa_impact_replay, + "impact_is_dependency_not_falsehood": True, + "negative_vectors": negatives, + }, + "corrected": { + "shift_types": sorted({nasa_revision.shift.shift_type_ref, esa_revision.shift.shift_type_ref}), + "signal_types": sorted( + { + nasa_revision.signal.signal_type_ref, + esa_revision.signal.signal_type_ref, + } + ), + "case_id": str(corrected_case.resource_id), + "case_member_count": len(corrected_case.lineage), + "brief_id": str(corrected_brief.resource_id), + "brief_digest": str(corrected_brief.resource_digest), + "citation_count": len(corrected_brief.citations), + "claim_count": len(corrected_brief.claims), + "status_projection_id": str(corrected_status.projection_id), + "claim_statuses": [item.status_id for item in corrected_status.claim_statuses], + "family_count": len(corrected_families.members_by_root), + "family_roots": sorted(corrected_families.members_by_root), + "same_lineage_supersessions_collapse": bool( + corrected_families.root_of(str(nasa_assertion.resource_id)) + == corrected_families.root_of(str(admissions["nasa_initial"].observation.resource_id)) + and corrected_families.root_of(str(esa_assertion.resource_id)) + == corrected_families.root_of(str(admissions["esa_initial"].observation.resource_id)) + ), + "corroborated_claim_family_count": next( + item.distinct_derivation_family_count + for item in corrected_status.claim_statuses + if item.status_id == "corroborated" + ), + "status_replay_exact": corrected_status_replay, + }, + "historical_integrity": { + "brief_reopened_identically": reopened_historical_brief == historical_brief, + "brief_id_unchanged": (str(reopened_historical_brief.resource_id) == str(historical_brief.resource_id)), + "brief_precedes_corrections": historical_brief.generated_at < asserted_at, + "historical_artifact_rewritten": False, + }, + "separation": { + "live_record_count": len(live_records), + "prepared_record_count": len(prepared_records), + "prepared_material_reused": False, + "autonomous_publication": False, + "external_action": False, + }, + } + + +def main() -> None: + print(json.dumps(asyncio.run(run_acceptance()), indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_release_contract.py b/tests/test_release_contract.py index e58eb5e..becb7cb 100644 --- a/tests/test_release_contract.py +++ b/tests/test_release_contract.py @@ -43,6 +43,7 @@ REPO_ROOT / "domain_packs" / "world_intelligence_federal_register", REPO_ROOT / "domain_packs" / "world_intelligence_federal_register_monitor", REPO_ROOT / "domain_packs" / "world_intelligence_ai", + REPO_ROOT / "domain_packs" / "world_intelligence_planetary_defense", ) @@ -208,6 +209,7 @@ def test_root_distribution_mapping_stays_inert_and_data_only() -> None: assert set(package_data) == { "domain_packs.world_intelligence", "domain_packs.world_intelligence_ai", + "domain_packs.world_intelligence_planetary_defense", "domain_packs.world_intelligence_federal_register", "domain_packs.world_intelligence_federal_register_monitor", }