diff --git a/docs/NBGA_RUNTIME_CONTRACT_V0.1.md b/docs/NBGA_RUNTIME_CONTRACT_V0.1.md new file mode 100644 index 00000000..cefb4aab --- /dev/null +++ b/docs/NBGA_RUNTIME_CONTRACT_V0.1.md @@ -0,0 +1,161 @@ +# NBG-A Public Runtime Contract v0.1 + +**Status:** experimental, additive, read-only boundary +**Scope:** PhiOS consumption of normalized PhiKernel continuity and memory observations +**Non-goal:** publication of PhiKernel or TIEKAT implementation internals + +NBG-A is the working name for the Nested Bubble/Gear Architecture used by the A-TEAM +memory lifecycle: + +- **Anchor** preserves continuity-critical invariants. +- **Triage** classifies incoming state without granting authority. +- **Episodic** represents bounded events and their evidence. +- **Abstract** exposes higher-order observables while retaining provenance. +- **Manifest** reconstructs usable working state from trusted continuity roots. + +PhiOS consumes only the normalized boundary described here. Storage engines, graph +algorithms, decay rules, routing logic, model prompts, private state, and TIEKAT +implementation details remain behind the PhiKernel boundary. + +## Contract invariants + +1. **Identity is not the model.** +2. **An observable is not the internal state.** +3. **Capability is not authority.** +4. **A trusted memory retains a path to why it is trusted.** +5. **Public observations do not grant write, promotion, routing, or execution authority.** +6. **Unknown fields fail closed rather than silently widening the contract.** + +v0.1 intentionally exposes no mutation operation. Anchor promotion, triage decisions, +decay, consolidation, manifest commits, and continuity-root updates remain internal and +governed. A later public mutation contract requires a separate reviewed rung. + +## Memory Receipt + +Schema: + +`phikernel.nbga.memory-receipt.v1` + +A Memory Receipt carries one normalized observable and enough public lineage to explain +how it was retrieved: + +```json +{ + "schema_version": "phikernel.nbga.memory-receipt.v1", + "bubble_id": "bubble:project:decision", + "bubble_version": 3, + "observable": "Normalized human-readable state", + "trust_state": "verified", + "confidence": 1.0, + "evidence": ["event:123"], + "gear_path": [ + { + "gear_id": "gear:evidence", + "transform": "evidence", + "source": "bubble:project", + "destination": "bubble:project:decision" + } + ], + "event_head": "event:123", + "provenance_root": "sha256:..." +} +``` + +### Bubble + +At the public boundary, a Bubble is identified by `bubble_id` and `bubble_version`. +PhiOS receives its `observable`, not its private payload or internal state. + +### Gear path + +A Gear Hop is a directional, named transformation between two public Bubble identities: + +```text +source --[transform / gear_id]--> destination +``` + +The public contract describes the path. It does not expose how PhiKernel implements the +transformation. + +### Evidence and provenance + +`evidence`, `event_head`, and `provenance_root` make retrieval proof-carrying. +They are references, not an authority grant. PhiOS may present or compare them but may +not infer permission to mutate PhiKernel state. + +## Bubble Zero Status + +Schema: + +`phikernel.nbga.bubble-zero-status.v1` + +Bubble Zero is exposed only as a minimal continuity projection: + +```json +{ + "schema_version": "phikernel.nbga.bubble-zero-status.v1", + "system_id": "phios", + "epoch": 7, + "verified": true, + "governance_root": "sha256:...", + "event_log_head": "sha256:...", + "topology_root": "sha256:...", + "anchor_root": "sha256:...", + "commitment_root": "sha256:...", + "last_checkpoint": "checkpoint:7" +} +``` + +This projection answers only: + +- which continuity identity is being observed, +- which epoch is current, +- whether the exposed root set verified, +- and which normalized roots/checkpoint identify that state. + +It does not expose secrets, raw state, internal payload references, capability grants, +or authority grants. + +## Fail-closed fields + +The PhiOS parser rejects public payloads containing known private/authority-bearing +fields such as `internal_state`, `raw_state`, `private_state`, `payload`, +`payload_ref`, `secret`, `authority`, `authority_grant`, or +`capability_grant`. + +It also rejects unknown top-level fields. Contract growth therefore requires an explicit +schema revision instead of accidental widening. + +## First acceptance target + +The first end-to-end NBG-A acceptance experiment should use already-understood PhiOS +qualification evidence: + +1. ingest a bounded compatibility/qualification episode, +2. expose a higher-order verified observable, +3. retain evidence and a directional Gear path, +4. restart the runtime, +5. recover Bubble Zero, +6. retrieve the observable again with the same provenance lineage. + +The experiment is successful only if restart/reconstruction preserves the trusted +observable and its evidence path without making the model, vector index, or PhiOS +presentation layer authoritative. + +## Rollout + +v0.1 is intentionally additive: + +```text +qualified PhiOS/Linux candidate + | + v +existing PhiKernel adapter + | + +--> existing runtime behavior (unchanged) + | + +--> NBG-A normalized parser (new, read-only) +``` + +No existing adapter is promoted, no routing default changes, and no release authority is +implied by this contract. diff --git a/phios/adapters/nbga.py b/phios/adapters/nbga.py new file mode 100644 index 00000000..cc306486 --- /dev/null +++ b/phios/adapters/nbga.py @@ -0,0 +1,238 @@ +"""Normalized public NBG-A contract for PhiOS <-> PhiKernel integration. + +This module intentionally models only the stable, observable boundary. It does not +encode PhiKernel storage, routing, decay, or TIEKAT implementation internals. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import Mapping + +MEMORY_RECEIPT_SCHEMA = "phikernel.nbga.memory-receipt.v1" +BUBBLE_ZERO_STATUS_SCHEMA = "phikernel.nbga.bubble-zero-status.v1" + +_FORBIDDEN_FIELDS = frozenset( + { + "authority", + "authority_grant", + "capability_grant", + "internal_state", + "payload", + "payload_ref", + "private_state", + "raw_state", + "secret", + "secrets", + } +) + + +class NBGContractError(ValueError): + """Raised when an NBG-A public-contract payload is invalid or overexposes state.""" + + +def _require_mapping(value: object, field: str) -> Mapping[str, object]: + if not isinstance(value, Mapping): + raise NBGContractError(f"{field} must be an object") + return value + + +def _validate_keys( + payload: Mapping[str, object], + *, + required: frozenset[str], + optional: frozenset[str] = frozenset(), +) -> None: + keys = set(payload) + leaked = keys & _FORBIDDEN_FIELDS + if leaked: + raise NBGContractError( + "public NBG-A payload exposes forbidden field(s): " + ", ".join(sorted(leaked)) + ) + missing = required - keys + if missing: + raise NBGContractError("missing required field(s): " + ", ".join(sorted(missing))) + unknown = keys - required - optional + if unknown: + raise NBGContractError("unknown public-contract field(s): " + ", ".join(sorted(unknown))) + + +def _require_str(value: object, field: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise NBGContractError(f"{field} must be a non-empty string") + return value + + +def _require_int(value: object, field: str, *, minimum: int = 0) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise NBGContractError(f"{field} must be an integer >= {minimum}") + return value + + +def _require_bool(value: object, field: str) -> bool: + if not isinstance(value, bool): + raise NBGContractError(f"{field} must be a boolean") + return value + + +def _require_confidence(value: object) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise NBGContractError("confidence must be a number from 0 to 1") + result = float(value) + if not math.isfinite(result) or not 0.0 <= result <= 1.0: + raise NBGContractError("confidence must be a finite number from 0 to 1") + return result + + +def _require_string_tuple(value: object, field: str) -> tuple[str, ...]: + if not isinstance(value, list): + raise NBGContractError(f"{field} must be an array") + return tuple(_require_str(item, f"{field}[]") for item in value) + + +@dataclass(frozen=True, slots=True) +class GearHop: + """One normalized directional transformation in a proof-carrying retrieval path.""" + + gear_id: str + transform: str + source: str + destination: str + + @classmethod + def from_payload(cls, value: object) -> "GearHop": + payload = _require_mapping(value, "gear_path[]") + _validate_keys( + payload, + required=frozenset({"gear_id", "transform", "source", "destination"}), + ) + return cls( + gear_id=_require_str(payload["gear_id"], "gear_id"), + transform=_require_str(payload["transform"], "transform"), + source=_require_str(payload["source"], "source"), + destination=_require_str(payload["destination"], "destination"), + ) + + +@dataclass(frozen=True, slots=True) +class MemoryReceipt: + """Observable memory plus the path and evidence used to retrieve it.""" + + bubble_id: str + bubble_version: int + observable: str + trust_state: str + confidence: float | None + evidence: tuple[str, ...] + gear_path: tuple[GearHop, ...] + event_head: str + provenance_root: str + + @classmethod + def from_payload(cls, value: object) -> "MemoryReceipt": + payload = _require_mapping(value, "memory receipt") + _validate_keys( + payload, + required=frozenset( + { + "schema_version", + "bubble_id", + "bubble_version", + "observable", + "trust_state", + "evidence", + "gear_path", + "event_head", + "provenance_root", + } + ), + optional=frozenset({"confidence"}), + ) + if payload["schema_version"] != MEMORY_RECEIPT_SCHEMA: + raise NBGContractError("unsupported memory receipt schema_version") + + raw_path = payload["gear_path"] + if not isinstance(raw_path, list): + raise NBGContractError("gear_path must be an array") + + confidence = None + if "confidence" in payload and payload["confidence"] is not None: + confidence = _require_confidence(payload["confidence"]) + + return cls( + bubble_id=_require_str(payload["bubble_id"], "bubble_id"), + bubble_version=_require_int(payload["bubble_version"], "bubble_version", minimum=1), + observable=_require_str(payload["observable"], "observable"), + trust_state=_require_str(payload["trust_state"], "trust_state"), + confidence=confidence, + evidence=_require_string_tuple(payload["evidence"], "evidence"), + gear_path=tuple(GearHop.from_payload(item) for item in raw_path), + event_head=_require_str(payload["event_head"], "event_head"), + provenance_root=_require_str(payload["provenance_root"], "provenance_root"), + ) + + +@dataclass(frozen=True, slots=True) +class BubbleZeroStatus: + """Minimal continuity status exposed across the PhiKernel public boundary.""" + + system_id: str + epoch: int + verified: bool + governance_root: str + event_log_head: str + topology_root: str + anchor_root: str + commitment_root: str + last_checkpoint: str | None + + @classmethod + def from_payload(cls, value: object) -> "BubbleZeroStatus": + payload = _require_mapping(value, "Bubble Zero status") + _validate_keys( + payload, + required=frozenset( + { + "schema_version", + "system_id", + "epoch", + "verified", + "governance_root", + "event_log_head", + "topology_root", + "anchor_root", + "commitment_root", + "last_checkpoint", + } + ), + ) + if payload["schema_version"] != BUBBLE_ZERO_STATUS_SCHEMA: + raise NBGContractError("unsupported Bubble Zero schema_version") + + checkpoint = payload["last_checkpoint"] + if checkpoint is not None: + checkpoint = _require_str(checkpoint, "last_checkpoint") + + return cls( + system_id=_require_str(payload["system_id"], "system_id"), + epoch=_require_int(payload["epoch"], "epoch"), + verified=_require_bool(payload["verified"], "verified"), + governance_root=_require_str(payload["governance_root"], "governance_root"), + event_log_head=_require_str(payload["event_log_head"], "event_log_head"), + topology_root=_require_str(payload["topology_root"], "topology_root"), + anchor_root=_require_str(payload["anchor_root"], "anchor_root"), + commitment_root=_require_str(payload["commitment_root"], "commitment_root"), + last_checkpoint=checkpoint, + ) + + +__all__ = [ + "BUBBLE_ZERO_STATUS_SCHEMA", + "MEMORY_RECEIPT_SCHEMA", + "BubbleZeroStatus", + "GearHop", + "MemoryReceipt", + "NBGContractError", +] diff --git a/tests/test_nbga_contract_v01.py b/tests/test_nbga_contract_v01.py new file mode 100644 index 00000000..3147dc72 --- /dev/null +++ b/tests/test_nbga_contract_v01.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +import pytest + +from phios.adapters.nbga import ( + BUBBLE_ZERO_STATUS_SCHEMA, + MEMORY_RECEIPT_SCHEMA, + BubbleZeroStatus, + MemoryReceipt, + NBGContractError, +) + + +def memory_payload() -> dict[str, object]: + return { + "schema_version": MEMORY_RECEIPT_SCHEMA, + "bubble_id": "bubble:phios:vm-qualification", + "bubble_version": 3, + "observable": "The qualified candidate completed the VirtualBox compatibility path.", + "trust_state": "verified", + "confidence": 1.0, + "evidence": ["event:qualification:36916494462", "artifact:iso:33bfb342"], + "gear_path": [ + { + "gear_id": "gear:project-to-qualification", + "transform": "evidence", + "source": "bubble:phios", + "destination": "bubble:phios:vm-qualification", + } + ], + "event_head": "event:qualification:36916494462", + "provenance_root": "sha256:receipt-root", + } + + +def bubble_zero_payload() -> dict[str, object]: + return { + "schema_version": BUBBLE_ZERO_STATUS_SCHEMA, + "system_id": "phios", + "epoch": 7, + "verified": True, + "governance_root": "sha256:governance", + "event_log_head": "sha256:event-head", + "topology_root": "sha256:topology", + "anchor_root": "sha256:anchor", + "commitment_root": "sha256:commitments", + "last_checkpoint": "checkpoint:7", + } + + +def test_memory_receipt_accepts_only_normalized_observable_state() -> None: + receipt = MemoryReceipt.from_payload(memory_payload()) + + assert receipt.bubble_id == "bubble:phios:vm-qualification" + assert receipt.bubble_version == 3 + assert receipt.trust_state == "verified" + assert receipt.gear_path[0].transform == "evidence" + assert receipt.gear_path[0].source == "bubble:phios" + assert receipt.gear_path[0].destination == "bubble:phios:vm-qualification" + + +@pytest.mark.parametrize( + "field", + ["payload", "payload_ref", "internal_state", "raw_state", "private_state", "secret"], +) +def test_memory_receipt_rejects_private_or_internal_state(field: str) -> None: + payload = memory_payload() + payload[field] = "must-not-cross-boundary" + + with pytest.raises(NBGContractError, match="forbidden"): + MemoryReceipt.from_payload(payload) + + +@pytest.mark.parametrize("field", ["authority", "authority_grant", "capability_grant"]) +def test_memory_receipt_cannot_smuggle_authority(field: str) -> None: + payload = memory_payload() + payload[field] = "elevated" + + with pytest.raises(NBGContractError, match="forbidden"): + MemoryReceipt.from_payload(payload) + + +def test_memory_receipt_fails_closed_on_unknown_contract_fields() -> None: + payload = memory_payload() + payload["implementation_hint"] = "private-routing-algorithm" + + with pytest.raises(NBGContractError, match="unknown"): + MemoryReceipt.from_payload(payload) + + +@pytest.mark.parametrize("confidence", [-0.01, 1.01, float("inf"), float("nan"), True]) +def test_memory_receipt_rejects_invalid_confidence(confidence: object) -> None: + payload = memory_payload() + payload["confidence"] = confidence + + with pytest.raises(NBGContractError, match="confidence"): + MemoryReceipt.from_payload(payload) + + +def test_bubble_zero_status_is_minimal_continuity_projection() -> None: + status = BubbleZeroStatus.from_payload(bubble_zero_payload()) + + assert status.system_id == "phios" + assert status.epoch == 7 + assert status.verified is True + assert status.last_checkpoint == "checkpoint:7" + + +def test_bubble_zero_rejects_raw_state_and_authority() -> None: + for field in ("raw_state", "authority"): + payload = bubble_zero_payload() + payload[field] = "not-public" + with pytest.raises(NBGContractError, match="forbidden"): + BubbleZeroStatus.from_payload(payload) + + +def test_contract_schema_versions_are_explicit_and_fail_closed() -> None: + receipt = memory_payload() + receipt["schema_version"] = "phikernel.nbga.memory-receipt.v2" + with pytest.raises(NBGContractError, match="schema_version"): + MemoryReceipt.from_payload(receipt) + + status = bubble_zero_payload() + status["schema_version"] = "phikernel.nbga.bubble-zero-status.v2" + with pytest.raises(NBGContractError, match="schema_version"): + BubbleZeroStatus.from_payload(status)