From d5ffe065212b29be1df051a99f03fd30a3d17f1c Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:52:01 -0700 Subject: [PATCH 01/19] feat: parse and verify persisted policy admission receipts --- phios/macro_policy_admission.py | 119 ++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/phios/macro_policy_admission.py b/phios/macro_policy_admission.py index 1a9c340f..30ce532c 100644 --- a/phios/macro_policy_admission.py +++ b/phios/macro_policy_admission.py @@ -477,6 +477,125 @@ def to_dict(self) -> dict[str, object]: return payload + @classmethod + def from_dict( + cls, + payload: Mapping[str, object], + ) -> "GhostWalkPolicyAdmissionReceipt": + expected = { + "schema_version", + "projection_sha256", + "target_inference_receipt_sha256", + "accepted_intent_revision_sha256", + "policy_profile_sha256", + "decision", + "reason", + "request_authority_eligible", + "evaluated_at", + "effect_performed", + "desktop_effect_performed", + "authority_request_created", + "action_lease_created", + "policy_authority", + "operational_authority", + "action_authority", + "execution_authority", + "admission_receipt_sha256", + } + if set(payload) != expected: + raise GhostWalkPolicyAdmissionError( + "policy admission receipt fields do not match contract" + ) + claimed = _require_sha256( + payload.get("admission_receipt_sha256"), + "admission_receipt_sha256", + ) + for field in ( + "request_authority_eligible", + "effect_performed", + "desktop_effect_performed", + "authority_request_created", + "action_lease_created", + "policy_authority", + "operational_authority", + "action_authority", + "execution_authority", + ): + if not isinstance(payload.get(field), bool): + raise GhostWalkPolicyAdmissionError( + f"{field} must be Boolean" + ) + try: + decision = GhostWalkPolicyDecision( + _require_text( + payload.get("decision"), + "decision", + maximum=64, + ) + ) + reason = GhostWalkPolicyReason( + _require_text( + payload.get("reason"), + "reason", + maximum=64, + ) + ) + except ValueError as exc: + raise GhostWalkPolicyAdmissionError( + "policy admission receipt enum value is unsupported" + ) from exc + + receipt = cls( + projection_sha256=_require_sha256( + payload.get("projection_sha256"), + "projection_sha256", + ), + target_inference_receipt_sha256=_require_sha256( + payload.get("target_inference_receipt_sha256"), + "target_inference_receipt_sha256", + ), + accepted_intent_revision_sha256=_require_sha256( + payload.get("accepted_intent_revision_sha256"), + "accepted_intent_revision_sha256", + ), + policy_profile_sha256=_require_sha256( + payload.get("policy_profile_sha256"), + "policy_profile_sha256", + ), + decision=decision, + reason=reason, + request_authority_eligible=payload[ + "request_authority_eligible" + ], + evaluated_at=_require_timestamp( + payload.get("evaluated_at"), + "evaluated_at", + ), + effect_performed=payload["effect_performed"], + desktop_effect_performed=payload[ + "desktop_effect_performed" + ], + authority_request_created=payload[ + "authority_request_created" + ], + action_lease_created=payload["action_lease_created"], + policy_authority=payload["policy_authority"], + operational_authority=payload["operational_authority"], + action_authority=payload["action_authority"], + execution_authority=payload["execution_authority"], + schema_version=_require_text( + payload.get("schema_version"), + "schema_version", + maximum=128, + ), + ) + if receipt.admission_receipt_sha256 != claimed: + raise GhostWalkPolicyAdmissionError( + "policy admission receipt hash mismatch" + ) + return receipt + + class GhostWalkPolicyAdmissionService: """Evaluate accepted intent against server-owned, fail-closed policy.""" From 9bbe41910ce908f43758fba12f0444f10eeb061b Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:53:41 -0700 Subject: [PATCH 02/19] feat: add immutable zero-authority AuthorityRequest --- phios/macro_authority_request.py | 768 +++++++++++++++++++++++++++++++ 1 file changed, 768 insertions(+) create mode 100644 phios/macro_authority_request.py diff --git a/phios/macro_authority_request.py b/phios/macro_authority_request.py new file mode 100644 index 00000000..6eb9bc55 --- /dev/null +++ b/phios/macro_authority_request.py @@ -0,0 +1,768 @@ +"""Immutable zero-authority Ghost-Walk AuthorityRequest for v0.31. + +An AuthorityRequest records that bounded action authority was requested for one +exact accepted semantic intent under one exact ALLOW_REQUEST admission receipt. + +A request is not authorization, not an ActionLease, and not execution. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import threading +from dataclasses import dataclass +from datetime import UTC, datetime +from enum import StrEnum +from typing import Mapping + +from phios.macro_policy_admission import ( + GhostWalkPolicyAdmissionError, + GhostWalkPolicyAdmissionReceipt, + GhostWalkPolicyAdmissionService, + GhostWalkPolicyDecision, +) +from phios.spine.ledger import RealityLedger + +GHOSTWALK_AUTHORITY_REQUEST_SCHEMA_VERSION = ( + "phios.ghostwalk_authority_request.v0.31" +) +GHOSTWALK_AUTHORITY_REQUEST_READINESS_SCHEMA_VERSION = ( + "phios.ghostwalk_authority_request_readiness.v0.31" +) +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_INTENT_CODE_RE = re.compile(r"^[A-Z][A-Z0-9_]{2,127}$") + + +class GhostWalkAuthorityRequestError(ValueError): + """Raised when AuthorityRequest evidence or provenance is invalid.""" + + +class GhostWalkRequestedAuthorityKind(StrEnum): + ACTION_AUTHORITY = "ACTION_AUTHORITY" + + +class GhostWalkRequestScopeKind(StrEnum): + ACCEPTED_INTENT = "ACCEPTED_INTENT" + + +class GhostWalkAuthorityRequestState(StrEnum): + PENDING_AUTHORIZATION = "PENDING_AUTHORIZATION" + + +class GhostWalkAuthorityRequestReadinessReason(StrEnum): + READY = "READY" + POLICY_NOT_ALLOW_REQUEST = "POLICY_NOT_ALLOW_REQUEST" + ADMISSION_RECEIPT_REQUIRED = "ADMISSION_RECEIPT_REQUIRED" + ADMISSION_RECEIPT_STALE = "ADMISSION_RECEIPT_STALE" + REQUEST_ALREADY_EXISTS = "REQUEST_ALREADY_EXISTS" + + +def _require_text( + value: object, + field: str, + *, + maximum: int = 4096, +) -> str: + if not isinstance(value, str) or not value: + raise GhostWalkAuthorityRequestError( + f"{field} must be a non-empty string" + ) + if len(value) > maximum: + raise GhostWalkAuthorityRequestError( + f"{field} exceeds {maximum} characters" + ) + if any(ord(char) < 32 for char in value): + raise GhostWalkAuthorityRequestError( + f"{field} contains control characters" + ) + return value + + +def _require_sha256(value: object, field: str) -> str: + text = _require_text(value, field, maximum=64) + if not _SHA256_RE.fullmatch(text): + raise GhostWalkAuthorityRequestError( + f"{field} must be a lowercase SHA-256 digest" + ) + return text + + +def _optional_sha256(value: object, field: str) -> str | None: + if value is None: + return None + return _require_sha256(value, field) + + +def _require_timestamp(value: object, field: str) -> str: + text = _require_text(value, field, maximum=64) + try: + parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError as exc: + raise GhostWalkAuthorityRequestError( + f"{field} must be an ISO-8601 timestamp" + ) from exc + if parsed.tzinfo is None: + raise GhostWalkAuthorityRequestError( + f"{field} must include a timezone" + ) + return text + + +def _require_bool(value: object, field: str) -> bool: + if not isinstance(value, bool): + raise GhostWalkAuthorityRequestError( + f"{field} must be Boolean" + ) + return value + + +def _canonical_json(value: object) -> str: + try: + return json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ) + except (TypeError, ValueError) as exc: + raise GhostWalkAuthorityRequestError( + "AuthorityRequest payload must be canonical JSON" + ) from exc + + +def _canonical_sha256(value: object) -> str: + return hashlib.sha256(_canonical_json(value).encode("utf-8")).hexdigest() + + +def _utc_now() -> str: + return datetime.now(UTC).isoformat() + + +@dataclass(frozen=True, slots=True) +class GhostWalkAuthorityRequest: + admission_receipt_sha256: str + target_inference_receipt_sha256: str + accepted_intent_revision_sha256: str + policy_profile_sha256: str + intent_family: str + intent_code: str + requester_id: str + requested_authority_kind: GhostWalkRequestedAuthorityKind + requested_scope_kind: GhostWalkRequestScopeKind + requested_scope_value: str + request_state: GhostWalkAuthorityRequestState + requested_at: str + authorization_granted: bool = False + action_lease_created: bool = False + effect_performed: bool = False + policy_authority: bool = False + operational_authority: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = GHOSTWALK_AUTHORITY_REQUEST_SCHEMA_VERSION + + def __post_init__(self) -> None: + if self.schema_version != GHOSTWALK_AUTHORITY_REQUEST_SCHEMA_VERSION: + raise GhostWalkAuthorityRequestError( + "unsupported AuthorityRequest schema" + ) + for field, digest in ( + ("admission_receipt_sha256", self.admission_receipt_sha256), + ( + "target_inference_receipt_sha256", + self.target_inference_receipt_sha256, + ), + ( + "accepted_intent_revision_sha256", + self.accepted_intent_revision_sha256, + ), + ("policy_profile_sha256", self.policy_profile_sha256), + ): + _require_sha256(digest, field) + _require_text(self.intent_family, "intent_family", maximum=64) + code = _require_text(self.intent_code, "intent_code", maximum=128) + if not _INTENT_CODE_RE.fullmatch(code): + raise GhostWalkAuthorityRequestError( + "intent_code must be an uppercase symbolic identifier" + ) + _require_text(self.requester_id, "requester_id", maximum=512) + if self.requested_scope_value != self.intent_code: + raise GhostWalkAuthorityRequestError( + "AuthorityRequest scope must equal the accepted intent code" + ) + _require_timestamp(self.requested_at, "requested_at") + if ( + self.authorization_granted + or self.action_lease_created + or self.effect_performed + or self.policy_authority + or self.operational_authority + or self.action_authority + or self.execution_authority + ): + raise GhostWalkAuthorityRequestError( + "AuthorityRequest cannot carry grants, leases, effects, or authority" + ) + + def body_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "admission_receipt_sha256": self.admission_receipt_sha256, + "target_inference_receipt_sha256": ( + self.target_inference_receipt_sha256 + ), + "accepted_intent_revision_sha256": ( + self.accepted_intent_revision_sha256 + ), + "policy_profile_sha256": self.policy_profile_sha256, + "intent_family": self.intent_family, + "intent_code": self.intent_code, + "requester_id": self.requester_id, + "requested_authority_kind": self.requested_authority_kind.value, + "requested_scope_kind": self.requested_scope_kind.value, + "requested_scope_value": self.requested_scope_value, + "request_state": self.request_state.value, + "requested_at": self.requested_at, + "authorization_granted": self.authorization_granted, + "action_lease_created": self.action_lease_created, + "effect_performed": self.effect_performed, + "policy_authority": self.policy_authority, + "operational_authority": self.operational_authority, + "action_authority": self.action_authority, + "execution_authority": self.execution_authority, + } + + @property + def authority_request_sha256(self) -> str: + return _canonical_sha256(self.body_dict()) + + def to_dict(self) -> dict[str, object]: + payload = self.body_dict() + payload["authority_request_sha256"] = ( + self.authority_request_sha256 + ) + return payload + + @classmethod + def from_dict( + cls, + payload: Mapping[str, object], + ) -> "GhostWalkAuthorityRequest": + expected = { + "schema_version", + "admission_receipt_sha256", + "target_inference_receipt_sha256", + "accepted_intent_revision_sha256", + "policy_profile_sha256", + "intent_family", + "intent_code", + "requester_id", + "requested_authority_kind", + "requested_scope_kind", + "requested_scope_value", + "request_state", + "requested_at", + "authorization_granted", + "action_lease_created", + "effect_performed", + "policy_authority", + "operational_authority", + "action_authority", + "execution_authority", + "authority_request_sha256", + } + if set(payload) != expected: + raise GhostWalkAuthorityRequestError( + "AuthorityRequest fields do not match contract" + ) + claimed = _require_sha256( + payload.get("authority_request_sha256"), + "authority_request_sha256", + ) + try: + authority_kind = GhostWalkRequestedAuthorityKind( + _require_text( + payload.get("requested_authority_kind"), + "requested_authority_kind", + maximum=64, + ) + ) + scope_kind = GhostWalkRequestScopeKind( + _require_text( + payload.get("requested_scope_kind"), + "requested_scope_kind", + maximum=64, + ) + ) + request_state = GhostWalkAuthorityRequestState( + _require_text( + payload.get("request_state"), + "request_state", + maximum=64, + ) + ) + except ValueError as exc: + raise GhostWalkAuthorityRequestError( + "AuthorityRequest enum value is unsupported" + ) from exc + + request = cls( + admission_receipt_sha256=_require_sha256( + payload.get("admission_receipt_sha256"), + "admission_receipt_sha256", + ), + target_inference_receipt_sha256=_require_sha256( + payload.get("target_inference_receipt_sha256"), + "target_inference_receipt_sha256", + ), + accepted_intent_revision_sha256=_require_sha256( + payload.get("accepted_intent_revision_sha256"), + "accepted_intent_revision_sha256", + ), + policy_profile_sha256=_require_sha256( + payload.get("policy_profile_sha256"), + "policy_profile_sha256", + ), + intent_family=_require_text( + payload.get("intent_family"), + "intent_family", + maximum=64, + ), + intent_code=_require_text( + payload.get("intent_code"), + "intent_code", + maximum=128, + ), + requester_id=_require_text( + payload.get("requester_id"), + "requester_id", + maximum=512, + ), + requested_authority_kind=authority_kind, + requested_scope_kind=scope_kind, + requested_scope_value=_require_text( + payload.get("requested_scope_value"), + "requested_scope_value", + maximum=128, + ), + request_state=request_state, + requested_at=_require_timestamp( + payload.get("requested_at"), + "requested_at", + ), + authorization_granted=_require_bool( + payload.get("authorization_granted"), + "authorization_granted", + ), + action_lease_created=_require_bool( + payload.get("action_lease_created"), + "action_lease_created", + ), + effect_performed=_require_bool( + payload.get("effect_performed"), + "effect_performed", + ), + policy_authority=_require_bool( + payload.get("policy_authority"), + "policy_authority", + ), + operational_authority=_require_bool( + payload.get("operational_authority"), + "operational_authority", + ), + action_authority=_require_bool( + payload.get("action_authority"), + "action_authority", + ), + execution_authority=_require_bool( + payload.get("execution_authority"), + "execution_authority", + ), + schema_version=_require_text( + payload.get("schema_version"), + "schema_version", + maximum=128, + ), + ) + if request.authority_request_sha256 != claimed: + raise GhostWalkAuthorityRequestError( + "AuthorityRequest hash mismatch" + ) + return request + + +@dataclass(frozen=True, slots=True) +class GhostWalkAuthorityRequestReadiness: + target_inference_receipt_sha256: str + accepted_intent_revision_sha256: str + policy_profile_sha256: str + policy_decision: str + ready: bool + reason: GhostWalkAuthorityRequestReadinessReason + admission_receipt_sha256: str | None + existing_authority_request_sha256: str | None + authorization_granted: bool = False + action_lease_created: bool = False + effect_performed: bool = False + policy_authority: bool = False + operational_authority: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = ( + GHOSTWALK_AUTHORITY_REQUEST_READINESS_SCHEMA_VERSION + ) + + def __post_init__(self) -> None: + if ( + self.schema_version + != GHOSTWALK_AUTHORITY_REQUEST_READINESS_SCHEMA_VERSION + ): + raise GhostWalkAuthorityRequestError( + "unsupported AuthorityRequest readiness schema" + ) + for field, digest in ( + ( + "target_inference_receipt_sha256", + self.target_inference_receipt_sha256, + ), + ( + "accepted_intent_revision_sha256", + self.accepted_intent_revision_sha256, + ), + ("policy_profile_sha256", self.policy_profile_sha256), + ): + _require_sha256(digest, field) + _require_text(self.policy_decision, "policy_decision", maximum=64) + _optional_sha256( + self.admission_receipt_sha256, + "admission_receipt_sha256", + ) + _optional_sha256( + self.existing_authority_request_sha256, + "existing_authority_request_sha256", + ) + if self.ready is not ( + self.reason is GhostWalkAuthorityRequestReadinessReason.READY + ): + raise GhostWalkAuthorityRequestError( + "readiness Boolean must match readiness reason" + ) + if ( + self.authorization_granted + or self.action_lease_created + or self.effect_performed + or self.policy_authority + or self.operational_authority + or self.action_authority + or self.execution_authority + ): + raise GhostWalkAuthorityRequestError( + "AuthorityRequest readiness cannot carry grants, effects, or authority" + ) + + def to_dict(self) -> dict[str, object]: + payload = { + "schema_version": self.schema_version, + "target_inference_receipt_sha256": ( + self.target_inference_receipt_sha256 + ), + "accepted_intent_revision_sha256": ( + self.accepted_intent_revision_sha256 + ), + "policy_profile_sha256": self.policy_profile_sha256, + "policy_decision": self.policy_decision, + "ready": self.ready, + "reason": self.reason.value, + "admission_receipt_sha256": self.admission_receipt_sha256, + "existing_authority_request_sha256": ( + self.existing_authority_request_sha256 + ), + "authorization_granted": self.authorization_granted, + "action_lease_created": self.action_lease_created, + "effect_performed": self.effect_performed, + "policy_authority": self.policy_authority, + "operational_authority": self.operational_authority, + "action_authority": self.action_authority, + "execution_authority": self.execution_authority, + } + payload["readiness_sha256"] = _canonical_sha256(payload) + return payload + + +class GhostWalkAuthorityRequestService: + """Create one immutable zero-authority request per admission receipt.""" + + def __init__( + self, + *, + ledger: RealityLedger, + policy_admission: GhostWalkPolicyAdmissionService, + requester_id: str, + ) -> None: + if not isinstance(ledger, RealityLedger): + raise GhostWalkAuthorityRequestError( + "ledger must be a RealityLedger" + ) + self._ledger = ledger + self._policy_admission = policy_admission + self.requester_id = _require_text( + requester_id, + "requester_id", + maximum=512, + ) + self._lock = threading.RLock() + + def readiness( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorityRequestReadiness: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + try: + projection = self._policy_admission.project( + target_inference_receipt_sha256=target + ) + except GhostWalkPolicyAdmissionError as exc: + raise GhostWalkAuthorityRequestError(str(exc)) from exc + + if projection.decision is not GhostWalkPolicyDecision.ALLOW_REQUEST: + return GhostWalkAuthorityRequestReadiness( + target_inference_receipt_sha256=target, + accepted_intent_revision_sha256=( + projection.accepted_intent_revision_sha256 + ), + policy_profile_sha256=projection.policy_profile_sha256, + policy_decision=projection.decision.value, + ready=False, + reason=( + GhostWalkAuthorityRequestReadinessReason + .POLICY_NOT_ALLOW_REQUEST + ), + admission_receipt_sha256=None, + existing_authority_request_sha256=None, + ) + + matching, any_receipt = self._matching_admission_receipt( + target=target, + accepted_intent_revision_sha256=( + projection.accepted_intent_revision_sha256 + ), + policy_profile_sha256=projection.policy_profile_sha256, + ) + if matching is None: + reason = ( + GhostWalkAuthorityRequestReadinessReason + .ADMISSION_RECEIPT_STALE + if any_receipt + else GhostWalkAuthorityRequestReadinessReason + .ADMISSION_RECEIPT_REQUIRED + ) + return GhostWalkAuthorityRequestReadiness( + target_inference_receipt_sha256=target, + accepted_intent_revision_sha256=( + projection.accepted_intent_revision_sha256 + ), + policy_profile_sha256=projection.policy_profile_sha256, + policy_decision=projection.decision.value, + ready=False, + reason=reason, + admission_receipt_sha256=None, + existing_authority_request_sha256=None, + ) + + existing = self._request_for_admission( + matching.admission_receipt_sha256 + ) + if existing is not None: + return GhostWalkAuthorityRequestReadiness( + target_inference_receipt_sha256=target, + accepted_intent_revision_sha256=( + projection.accepted_intent_revision_sha256 + ), + policy_profile_sha256=projection.policy_profile_sha256, + policy_decision=projection.decision.value, + ready=False, + reason=( + GhostWalkAuthorityRequestReadinessReason + .REQUEST_ALREADY_EXISTS + ), + admission_receipt_sha256=( + matching.admission_receipt_sha256 + ), + existing_authority_request_sha256=( + existing.authority_request_sha256 + ), + ) + + return GhostWalkAuthorityRequestReadiness( + target_inference_receipt_sha256=target, + accepted_intent_revision_sha256=( + projection.accepted_intent_revision_sha256 + ), + policy_profile_sha256=projection.policy_profile_sha256, + policy_decision=projection.decision.value, + ready=True, + reason=GhostWalkAuthorityRequestReadinessReason.READY, + admission_receipt_sha256=matching.admission_receipt_sha256, + existing_authority_request_sha256=None, + ) + + def create( + self, + *, + target_inference_receipt_sha256: str, + expected_admission_receipt_sha256: str, + requested_at: str | None = None, + ) -> GhostWalkAuthorityRequest: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + expected_admission = _require_sha256( + expected_admission_receipt_sha256, + "expected_admission_receipt_sha256", + ) + timestamp = _require_timestamp( + _utc_now() if requested_at is None else requested_at, + "requested_at", + ) + + with self._lock: + readiness = self.readiness( + target_inference_receipt_sha256=target + ) + if not readiness.ready: + raise GhostWalkAuthorityRequestError( + f"AuthorityRequest not ready: {readiness.reason.value}" + ) + if readiness.admission_receipt_sha256 != expected_admission: + raise GhostWalkAuthorityRequestError( + "admission receipt changed before AuthorityRequest creation" + ) + + receipt = self._receipt_by_sha256(expected_admission) + if receipt is None: + raise GhostWalkAuthorityRequestError( + "admission receipt disappeared before AuthorityRequest creation" + ) + projection = self._policy_admission.project( + target_inference_receipt_sha256=target + ) + request = GhostWalkAuthorityRequest( + admission_receipt_sha256=( + receipt.admission_receipt_sha256 + ), + target_inference_receipt_sha256=target, + accepted_intent_revision_sha256=( + receipt.accepted_intent_revision_sha256 + ), + policy_profile_sha256=receipt.policy_profile_sha256, + intent_family=projection.intent_family, + intent_code=projection.intent_code, + requester_id=self.requester_id, + requested_authority_kind=( + GhostWalkRequestedAuthorityKind.ACTION_AUTHORITY + ), + requested_scope_kind=( + GhostWalkRequestScopeKind.ACCEPTED_INTENT + ), + requested_scope_value=projection.intent_code, + request_state=( + GhostWalkAuthorityRequestState.PENDING_AUTHORIZATION + ), + requested_at=timestamp, + ) + self._ledger.append_ghostwalk_authority_request(request) + return request + + def latest( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorityRequest | None: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + rows = self._ledger.ghostwalk_authority_requests( + target_inference_receipt_sha256=target + ) + requests = [ + GhostWalkAuthorityRequest.from_dict(row) + for row in rows + ] + return requests[-1] if requests else None + + def _matching_admission_receipt( + self, + *, + target: str, + accepted_intent_revision_sha256: str, + policy_profile_sha256: str, + ) -> tuple[GhostWalkPolicyAdmissionReceipt | None, bool]: + rows = self._ledger.ghostwalk_policy_admission_receipts( + target_inference_receipt_sha256=target + ) + any_receipt = bool(rows) + parsed: list[GhostWalkPolicyAdmissionReceipt] = [] + for row in rows: + try: + parsed.append( + GhostWalkPolicyAdmissionReceipt.from_dict(row) + ) + except GhostWalkPolicyAdmissionError as exc: + raise GhostWalkAuthorityRequestError( + "persisted policy admission receipt is invalid" + ) from exc + + for receipt in reversed(parsed): + if ( + receipt.decision is GhostWalkPolicyDecision.ALLOW_REQUEST + and receipt.request_authority_eligible + and ( + receipt.accepted_intent_revision_sha256 + == accepted_intent_revision_sha256 + ) + and receipt.policy_profile_sha256 == policy_profile_sha256 + ): + return receipt, any_receipt + return None, any_receipt + + def _receipt_by_sha256( + self, + receipt_sha256: str, + ) -> GhostWalkPolicyAdmissionReceipt | None: + for row in self._ledger.ghostwalk_policy_admission_receipts(): + try: + receipt = GhostWalkPolicyAdmissionReceipt.from_dict(row) + except GhostWalkPolicyAdmissionError as exc: + raise GhostWalkAuthorityRequestError( + "persisted policy admission receipt is invalid" + ) from exc + if receipt.admission_receipt_sha256 == receipt_sha256: + return receipt + return None + + def _request_for_admission( + self, + admission_receipt_sha256: str, + ) -> GhostWalkAuthorityRequest | None: + matches: list[GhostWalkAuthorityRequest] = [] + for row in self._ledger.ghostwalk_authority_requests(): + request = GhostWalkAuthorityRequest.from_dict(row) + if ( + request.admission_receipt_sha256 + == admission_receipt_sha256 + ): + matches.append(request) + if len(matches) > 1: + raise GhostWalkAuthorityRequestError( + "multiple AuthorityRequests exist for one admission receipt" + ) + return matches[0] if matches else None From 042ac72a7b6eb0675ca9efcfcdc8c3473c16dec2 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:53:43 -0700 Subject: [PATCH 03/19] test: cover Ghost-Walk AuthorityRequest service --- tests/test_macro_authority_request.py | 287 ++++++++++++++++++++++++++ 1 file changed, 287 insertions(+) create mode 100644 tests/test_macro_authority_request.py diff --git a/tests/test_macro_authority_request.py b/tests/test_macro_authority_request.py new file mode 100644 index 00000000..413a7574 --- /dev/null +++ b/tests/test_macro_authority_request.py @@ -0,0 +1,287 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import pytest + +from phios.macro_accepted_intent import ( + GhostWalkAcceptedIntentRegistry, + GhostWalkIntentFamily, +) +from phios.macro_authority_request import ( + GhostWalkAuthorityRequestError, + GhostWalkAuthorityRequestReadinessReason, + GhostWalkAuthorityRequestService, + GhostWalkAuthorityRequestState, +) +from phios.macro_ghostwalk_operator_editor import GhostWalkOperatorEditor +from phios.macro_operator_log import OperatorLog +from phios.macro_policy_admission import ( + GhostWalkPolicyAdmissionService, + GhostWalkPolicyProfile, +) +from phios.spine.ledger import RealityLedger + +ACTION = "b" * 64 +_INFERENCE_BODY = { + "status": "CANDIDATES", + "session_id": "demo", + "action_observation_sha256": ACTION, +} +TARGET = hashlib.sha256( + json.dumps( + _INFERENCE_BODY, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode("utf-8") +).hexdigest() + + +def _ledger(tmp_path: Path) -> RealityLedger: + return RealityLedger(tmp_path / "ledger" / "receipts.jsonl") + + +def _seed( + ledger: RealityLedger, +) -> tuple[ + GhostWalkPolicyAdmissionService, + str, +]: + ledger.path.parent.mkdir(parents=True, exist_ok=True) + inference_path = ( + ledger.path.parent / "transition-inference-receipts.jsonl" + ) + inference_path.write_text( + json.dumps( + { + **_INFERENCE_BODY, + "receipt_sha256": TARGET, + }, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + note = OperatorLog(ledger).create( + note_id=f"ghostwalk-transition:{ACTION}", + target_sha256=TARGET, + author_id="operator:local", + body="Opened network adapter properties.", + created_at="2026-09-27T07:20:00+00:00", + tags=( + "ghostwalk", + "operator-interpretation", + "transition-inference", + ), + ) + accepted = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + intent = accepted.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note.revision_sha256, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + accepted_at="2026-09-27T07:21:00+00:00", + ) + service = GhostWalkPolicyAdmissionService( + ledger=ledger, + accepted_intents=accepted, + operator_editor=GhostWalkOperatorEditor( + ledger=ledger, + author_id="operator:local", + ), + profile=GhostWalkPolicyProfile( + profile_id="ghostwalk-policy:test", + allow_request_intent_codes=( + "OPEN_NETWORK_ADAPTER_PROPERTIES", + ), + deny_intent_codes=(), + ), + ) + return service, intent.revision_sha256 + + +def test_readiness_requires_recorded_allow_request_admission( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + admission, _ = _seed(ledger) + requests = GhostWalkAuthorityRequestService( + ledger=ledger, + policy_admission=admission, + requester_id="operator:local", + ) + + readiness = requests.readiness( + target_inference_receipt_sha256=TARGET + ) + assert readiness.ready is False + assert ( + readiness.reason + is GhostWalkAuthorityRequestReadinessReason + .ADMISSION_RECEIPT_REQUIRED + ) + + +def test_create_binds_exact_admission_and_remains_zero_authority( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + admission, intent_sha = _seed(ledger) + receipt = admission.record( + target_inference_receipt_sha256=TARGET, + expected_accepted_intent_revision_sha256=intent_sha, + expected_policy_profile_sha256=admission.profile.profile_sha256, + evaluated_at="2026-09-27T07:22:00+00:00", + ) + requests = GhostWalkAuthorityRequestService( + ledger=ledger, + policy_admission=admission, + requester_id="operator:local", + ) + + readiness = requests.readiness( + target_inference_receipt_sha256=TARGET + ) + assert readiness.ready is True + assert readiness.admission_receipt_sha256 == ( + receipt.admission_receipt_sha256 + ) + + request = requests.create( + target_inference_receipt_sha256=TARGET, + expected_admission_receipt_sha256=( + receipt.admission_receipt_sha256 + ), + requested_at="2026-09-27T07:23:00+00:00", + ) + assert request.request_state is ( + GhostWalkAuthorityRequestState.PENDING_AUTHORIZATION + ) + assert request.authorization_granted is False + assert request.action_lease_created is False + assert request.action_authority is False + assert request.execution_authority is False + assert request.requested_scope_value == ( + "OPEN_NETWORK_ADAPTER_PROPERTIES" + ) + + +def test_one_request_per_admission_receipt(tmp_path: Path) -> None: + ledger = _ledger(tmp_path) + admission, intent_sha = _seed(ledger) + receipt = admission.record( + target_inference_receipt_sha256=TARGET, + expected_accepted_intent_revision_sha256=intent_sha, + expected_policy_profile_sha256=admission.profile.profile_sha256, + ) + requests = GhostWalkAuthorityRequestService( + ledger=ledger, + policy_admission=admission, + requester_id="operator:local", + ) + requests.create( + target_inference_receipt_sha256=TARGET, + expected_admission_receipt_sha256=( + receipt.admission_receipt_sha256 + ), + ) + + readiness = requests.readiness( + target_inference_receipt_sha256=TARGET + ) + assert readiness.ready is False + assert ( + readiness.reason + is GhostWalkAuthorityRequestReadinessReason + .REQUEST_ALREADY_EXISTS + ) + assert readiness.existing_authority_request_sha256 is not None + + +def test_stale_admission_cannot_seed_new_request( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + admission, intent_sha = _seed(ledger) + receipt = admission.record( + target_inference_receipt_sha256=TARGET, + expected_accepted_intent_revision_sha256=intent_sha, + expected_policy_profile_sha256=admission.profile.profile_sha256, + ) + current = OperatorLog(ledger).current( + note_id=f"ghostwalk-transition:{ACTION}" + ) + OperatorLog(ledger).edit( + note_id=current.note_id, + expected_current_revision_sha256=current.revision_sha256, + author_id="operator:local", + body="Newer interpretation.", + created_at="2026-09-27T07:24:00+00:00", + tags=current.tags, + ) + requests = GhostWalkAuthorityRequestService( + ledger=ledger, + policy_admission=admission, + requester_id="operator:local", + ) + + readiness = requests.readiness( + target_inference_receipt_sha256=TARGET + ) + assert readiness.ready is False + assert ( + readiness.reason + is GhostWalkAuthorityRequestReadinessReason + .POLICY_NOT_ALLOW_REQUEST + ) + + with pytest.raises( + GhostWalkAuthorityRequestError, + match="not ready", + ): + requests.create( + target_inference_receipt_sha256=TARGET, + expected_admission_receipt_sha256=( + receipt.admission_receipt_sha256 + ), + ) + + +def test_tampered_admission_receipt_fails_closed( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + admission, intent_sha = _seed(ledger) + admission.record( + target_inference_receipt_sha256=TARGET, + expected_accepted_intent_revision_sha256=intent_sha, + expected_policy_profile_sha256=admission.profile.profile_sha256, + ) + path = ledger.path.parent / "ghostwalk-policy-admission-receipts.jsonl" + row = json.loads(path.read_text(encoding="utf-8")) + row["reason"] = "INTENT_UNMAPPED" + path.write_text( + json.dumps(row, sort_keys=True) + "\n", + encoding="utf-8", + ) + requests = GhostWalkAuthorityRequestService( + ledger=ledger, + policy_admission=admission, + requester_id="operator:local", + ) + + with pytest.raises( + GhostWalkAuthorityRequestError, + match="admission receipt is invalid", + ): + requests.readiness( + target_inference_receipt_sha256=TARGET + ) From b35926cd5b92126e122bd9db30ae8f1298a30017 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:54:00 -0700 Subject: [PATCH 04/19] feat: persist Ghost-Walk AuthorityRequests --- phios/spine/ledger.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/phios/spine/ledger.py b/phios/spine/ledger.py index e3a7fb5c..72ecaf04 100644 --- a/phios/spine/ledger.py +++ b/phios/spine/ledger.py @@ -32,6 +32,7 @@ from phios.macro_operator_log import OperatorLogRevision from phios.macro_accepted_intent import GhostWalkAcceptedIntentRevision from phios.macro_policy_admission import GhostWalkPolicyAdmissionReceipt + from phios.macro_authority_request import GhostWalkAuthorityRequest from phios.macro_post_action_verification import ( PostActionVerificationReceipt, ) @@ -565,6 +566,42 @@ def ghostwalk_policy_admission_receipts( == target_inference_receipt_sha256 ] + def append_ghostwalk_authority_request( + self, + request: "GhostWalkAuthorityRequest", + ) -> None: + """Append one immutable Ghost-Walk authority request.""" + + path = self.path.parent / "ghostwalk-authority-requests.jsonl" + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write( + json.dumps(request.to_dict(), sort_keys=True) + "\n" + ) + + def ghostwalk_authority_requests( + self, + *, + target_inference_receipt_sha256: str | None = None, + ) -> list[dict[str, object]]: + """Return append-order Ghost-Walk AuthorityRequests.""" + + path = self.path.parent / "ghostwalk-authority-requests.jsonl" + if not path.exists(): + return [] + rows = [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + ] + if target_inference_receipt_sha256 is None: + return rows + return [ + row + for row in rows + if row.get("target_inference_receipt_sha256") + == target_inference_receipt_sha256 + ] + def append_interaction_guard_receipt( self, receipt: "InteractionGuardReceipt", From a3b3f181fae33c507ba13c8e99ad351476b4d119 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:54:40 -0700 Subject: [PATCH 05/19] feat: expose zero-authority AuthorityRequest sidecar API --- phios/macro_ghostwalk_control_server.py | 266 ++++++++++++++++++++++++ 1 file changed, 266 insertions(+) diff --git a/phios/macro_ghostwalk_control_server.py b/phios/macro_ghostwalk_control_server.py index 35b24643..5de069be 100644 --- a/phios/macro_ghostwalk_control_server.py +++ b/phios/macro_ghostwalk_control_server.py @@ -19,6 +19,12 @@ from typing import Callable, Mapping, Protocol from urllib.parse import parse_qs, urlsplit +from phios.macro_authority_request import ( + GhostWalkAuthorityRequest, + GhostWalkAuthorityRequestError, + GhostWalkAuthorityRequestReadiness, + GhostWalkAuthorityRequestService, +) from phios.macro_accepted_intent import ( GhostWalkAcceptedIntentError, GhostWalkAcceptedIntentRegistry, @@ -65,6 +71,10 @@ "phios.ghostwalk-policy-admission-transport.v0.30" ) POLICY_ADMISSION_TRANSPORT_IDENTITY = "phios-ghostwalk-policy-admission" +AUTHORITY_REQUEST_TRANSPORT_SCHEMA_VERSION = ( + "phios.ghostwalk-authority-request-transport.v0.31" +) +AUTHORITY_REQUEST_TRANSPORT_IDENTITY = "phios-ghostwalk-authority-request" DEFAULT_HOST_ID = "ghostwalk-host:local" DEFAULT_BASELINE_SERVICE_ID = "ghostwalk-baseline:local" DEFAULT_COORDINATOR_ID = "ghostwalk-coordinator:local" @@ -153,6 +163,28 @@ def record( +class GhostWalkAuthorityRequestPort(Protocol): + def readiness( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorityRequestReadiness: ... + + def latest( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorityRequest | None: ... + + def create( + self, + *, + target_inference_receipt_sha256: str, + expected_admission_receipt_sha256: str, + requested_at: str | None = None, + ) -> GhostWalkAuthorityRequest: ... + + def _utc_now() -> str: return datetime.now(UTC).isoformat() @@ -576,6 +608,114 @@ def parse_policy_admission_record_payload( return target, expected_intent, expected_profile +def _authority_request_transport_base( + *, + effect_performed: bool, +) -> dict[str, object]: + return { + "transportSchemaVersion": ( + AUTHORITY_REQUEST_TRANSPORT_SCHEMA_VERSION + ), + "transport": "loopback-http", + "transportIdentity": AUTHORITY_REQUEST_TRANSPORT_IDENTITY, + "localOnly": True, + "requestCreated": effect_performed, + "desktopEffectPerformed": False, + "authorizationGranted": False, + "actionLeaseCreated": False, + "policyAuthority": False, + "operationalAuthority": False, + "actionAuthority": False, + "executionAuthority": False, + "effectPerformed": effect_performed, + } + + +def authority_request_status_envelope( + service: GhostWalkAuthorityRequestPort, + *, + target_inference_receipt_sha256: str, +) -> dict[str, object]: + readiness = service.readiness( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + current = service.latest( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + payload = _authority_request_transport_base( + effect_performed=False + ) + payload.update( + { + "servedAt": _utc_now(), + "readiness": readiness.to_dict(), + "request": ( + None if current is None else current.to_dict() + ), + } + ) + return payload + + +def authority_request_create_envelope( + service: GhostWalkAuthorityRequestPort, + *, + target_inference_receipt_sha256: str, + expected_admission_receipt_sha256: str, +) -> dict[str, object]: + request = service.create( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_admission_receipt_sha256=( + expected_admission_receipt_sha256 + ), + ) + payload = _authority_request_transport_base( + effect_performed=True + ) + payload.update( + { + "servedAt": _utc_now(), + "request": request.to_dict(), + } + ) + return payload + + +def parse_authority_request_create_payload( + payload: object, +) -> tuple[str, str]: + if not isinstance(payload, Mapping): + raise GhostWalkControlBridgeError( + "AuthorityRequest body must be an object" + ) + expected_keys = { + "target_inference_receipt_sha256", + "expected_admission_receipt_sha256", + } + if set(payload) != expected_keys: + raise GhostWalkControlBridgeError( + "AuthorityRequest fields do not match contract" + ) + target = payload.get("target_inference_receipt_sha256") + admission = payload.get("expected_admission_receipt_sha256") + if ( + not isinstance(target, str) + or re.fullmatch(r"[0-9a-f]{64}", target) is None + or not isinstance(admission, str) + or re.fullmatch(r"[0-9a-f]{64}", admission) is None + ): + raise GhostWalkControlBridgeError( + "AuthorityRequest evidence hashes are invalid" + ) + return target, admission + + def status_envelope(surface: GhostWalkSurface) -> dict[str, object]: payload = _transport_base() payload.update( @@ -733,6 +873,17 @@ def _policy_admission_error( body.update({"error": code, "servedAt": _utc_now()}) self._json(status, body) + def _authority_request_error( + self, + status: HTTPStatus, + code: str, + ) -> None: + body = _authority_request_transport_base( + effect_performed=False + ) + body.update({"error": code, "servedAt": _utc_now()}) + self._json(status, body) + def _read_json( self, *, @@ -768,6 +919,58 @@ def _read_json( def do_GET(self) -> None: parsed = urlsplit(self.path) + if parsed.path == "/api/v1/ghostwalk/authority-request": + if self.server.authority_requests is None: + self._authority_request_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_authority_request_unavailable", + ) + return + try: + query = parse_qs( + parsed.query, + keep_blank_values=True, + strict_parsing=True, + ) + except ValueError: + self._authority_request_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_authority_request_status", + ) + return + targets = query.get("target") + if ( + set(query) != {"target"} + or targets is None + or len(targets) != 1 + or re.fullmatch(r"[0-9a-f]{64}", targets[0]) is None + ): + self._authority_request_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_authority_request_status", + ) + return + try: + request_status = authority_request_status_envelope( + self.server.authority_requests, + target_inference_receipt_sha256=targets[0], + ) + except GhostWalkAuthorityRequestError as exc: + code = ( + "ghostwalk_authority_request_not_ready" + if "does not exist" in str(exc) + else "ghostwalk_authority_request_invalid_evidence" + ) + self._authority_request_error( + HTTPStatus.NOT_FOUND + if code.endswith("not_ready") + else HTTPStatus.CONFLICT, + code, + ) + return + self._json(HTTPStatus.OK, request_status) + return + if parsed.path == "/api/v1/ghostwalk/policy-admission": if self.server.policy_admission is None: self._policy_admission_error( @@ -931,6 +1134,57 @@ def do_GET(self) -> None: def do_POST(self) -> None: parsed = urlsplit(self.path) + if parsed.path == "/api/v1/ghostwalk/authority-request/requests": + if parsed.query or parsed.fragment: + self._authority_request_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_authority_request_create", + ) + return + if self.server.authority_requests is None: + self._authority_request_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_authority_request_unavailable", + ) + return + try: + target, admission = ( + parse_authority_request_create_payload( + self._read_json() + ) + ) + except GhostWalkControlBridgeError: + self._authority_request_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_authority_request_create", + ) + return + try: + request_envelope = authority_request_create_envelope( + self.server.authority_requests, + target_inference_receipt_sha256=target, + expected_admission_receipt_sha256=admission, + ) + except GhostWalkAuthorityRequestError as exc: + conflict = ( + "changed before" in str(exc) + or "not ready" in str(exc) + or "already" in str(exc) + ) + self._authority_request_error( + HTTPStatus.CONFLICT + if conflict + else HTTPStatus.BAD_REQUEST, + ( + "ghostwalk_authority_request_conflict" + if conflict + else "ghostwalk_authority_request_rejected" + ), + ) + return + self._json(HTTPStatus.OK, request_envelope) + return + if parsed.path == "/api/v1/ghostwalk/policy-admission/evaluations": if parsed.query or parsed.fragment: self._policy_admission_error( @@ -1151,6 +1405,7 @@ def __init__( editor: GhostWalkOperatorEditorPort | None = None, accepted_intents: GhostWalkAcceptedIntentPort | None = None, policy_admission: GhostWalkPolicyAdmissionPort | None = None, + authority_requests: GhostWalkAuthorityRequestPort | None = None, stop_callback: Callable[[], object] | None = None, ) -> None: if address[0] != LOOPBACK_HOST: @@ -1161,6 +1416,7 @@ def __init__( self.editor = editor self.accepted_intents = accepted_intents self.policy_admission = policy_admission + self.authority_requests = authority_requests self._stop_callback = stop_callback super().__init__(address, GhostWalkControlHandler) @@ -1269,12 +1525,22 @@ def main() -> None: operator_editor=editor, profile=GhostWalkPolicyProfile.from_environment(os.environ), ) + authority_requests = GhostWalkAuthorityRequestService( + ledger=RealityLedger( + args.state_root.expanduser() + / "ledger" + / "receipts.jsonl" + ), + policy_admission=policy_admission, + requester_id=DEFAULT_OPERATOR_AUTHOR_ID, + ) server = GhostWalkControlServer( (LOOPBACK_HOST, args.port), surface=surface, editor=editor, accepted_intents=accepted_intents, policy_admission=policy_admission, + authority_requests=authority_requests, stop_callback=host.stop, ) From 2a603c1cbf8bc7f449803283e841b2061f100ccc Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:55:43 -0700 Subject: [PATCH 06/19] test: cover AuthorityRequest sidecar endpoints --- tests/test_macro_authority_request_server.py | 224 +++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 tests/test_macro_authority_request_server.py diff --git a/tests/test_macro_authority_request_server.py b/tests/test_macro_authority_request_server.py new file mode 100644 index 00000000..6d826ec3 --- /dev/null +++ b/tests/test_macro_authority_request_server.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import json +import threading +from http.client import HTTPConnection + +from phios.macro_authority_request import ( + GhostWalkAuthorityRequest, + GhostWalkAuthorityRequestReadiness, + GhostWalkAuthorityRequestReadinessReason, + GhostWalkAuthorityRequestState, + GhostWalkRequestScopeKind, + GhostWalkRequestedAuthorityKind, +) +from phios.macro_ghostwalk_control_server import ( + LOOPBACK_HOST, + GhostWalkControlServer, +) + +TARGET = "a" * 64 +ADMISSION = "b" * 64 +INTENT = "c" * 64 +PROFILE = "d" * 64 + + +class FakeSurface: + def snapshot(self) -> object: + raise AssertionError("status endpoint not used") + + +class FakeAuthorityRequests: + def __init__(self) -> None: + self.created: GhostWalkAuthorityRequest | None = None + self.calls: list[dict[str, str]] = [] + + def readiness( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorityRequestReadiness: + assert target_inference_receipt_sha256 == TARGET + return GhostWalkAuthorityRequestReadiness( + target_inference_receipt_sha256=TARGET, + accepted_intent_revision_sha256=INTENT, + policy_profile_sha256=PROFILE, + policy_decision="ALLOW_REQUEST", + ready=self.created is None, + reason=( + GhostWalkAuthorityRequestReadinessReason.READY + if self.created is None + else GhostWalkAuthorityRequestReadinessReason + .REQUEST_ALREADY_EXISTS + ), + admission_receipt_sha256=ADMISSION, + existing_authority_request_sha256=( + None + if self.created is None + else self.created.authority_request_sha256 + ), + ) + + def latest( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorityRequest | None: + assert target_inference_receipt_sha256 == TARGET + return self.created + + def create( + self, + *, + target_inference_receipt_sha256: str, + expected_admission_receipt_sha256: str, + requested_at: str | None = None, + ) -> GhostWalkAuthorityRequest: + self.calls.append( + { + "target": target_inference_receipt_sha256, + "admission": expected_admission_receipt_sha256, + } + ) + self.created = GhostWalkAuthorityRequest( + admission_receipt_sha256=ADMISSION, + target_inference_receipt_sha256=TARGET, + accepted_intent_revision_sha256=INTENT, + policy_profile_sha256=PROFILE, + intent_family="OPEN", + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + requester_id="operator:local", + requested_authority_kind=( + GhostWalkRequestedAuthorityKind.ACTION_AUTHORITY + ), + requested_scope_kind=( + GhostWalkRequestScopeKind.ACCEPTED_INTENT + ), + requested_scope_value=( + "OPEN_NETWORK_ADAPTER_PROPERTIES" + ), + request_state=( + GhostWalkAuthorityRequestState.PENDING_AUTHORIZATION + ), + requested_at="2026-09-27T07:30:00+00:00", + ) + return self.created + + +def _server( + service: FakeAuthorityRequests, +) -> tuple[GhostWalkControlServer, threading.Thread]: + server = GhostWalkControlServer( + (LOOPBACK_HOST, 0), + surface=FakeSurface(), # type: ignore[arg-type] + authority_requests=service, # type: ignore[arg-type] + ) + thread = threading.Thread( + target=server.serve_forever, + daemon=True, + ) + thread.start() + return server, thread + + +def _request( + server: GhostWalkControlServer, + method: str, + path: str, + body: dict[str, object] | None = None, +) -> tuple[int, dict[str, object]]: + connection = HTTPConnection( + LOOPBACK_HOST, + server.server_address[1], + timeout=2, + ) + encoded = None + headers: dict[str, str] = {"accept": "application/json"} + if body is not None: + encoded = json.dumps(body).encode("utf-8") + headers["content-type"] = "application/json" + headers["content-length"] = str(len(encoded)) + connection.request(method, path, body=encoded, headers=headers) + response = connection.getresponse() + payload = json.loads(response.read().decode("utf-8")) + connection.close() + return response.status, payload + + +def test_authority_request_status_is_read_only() -> None: + service = FakeAuthorityRequests() + server, thread = _server(service) + try: + status, payload = _request( + server, + "GET", + "/api/v1/ghostwalk/authority-request?target=" + TARGET, + ) + assert status == 200 + assert payload["requestCreated"] is False + assert payload["effectPerformed"] is False + assert payload["authorizationGranted"] is False + assert payload["actionLeaseCreated"] is False + assert payload["actionAuthority"] is False + assert payload["readiness"]["ready"] is True + assert payload["request"] is None + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_authority_request_creation_is_ledger_effect_only() -> None: + service = FakeAuthorityRequests() + server, thread = _server(service) + try: + status, payload = _request( + server, + "POST", + "/api/v1/ghostwalk/authority-request/requests", + { + "target_inference_receipt_sha256": TARGET, + "expected_admission_receipt_sha256": ADMISSION, + }, + ) + assert status == 200 + assert payload["requestCreated"] is True + assert payload["effectPerformed"] is True + assert payload["desktopEffectPerformed"] is False + assert payload["authorizationGranted"] is False + assert payload["actionLeaseCreated"] is False + assert payload["actionAuthority"] is False + assert ( + payload["request"]["request_state"] + == "PENDING_AUTHORIZATION" + ) + assert payload["request"]["authorization_granted"] is False + assert payload["request"]["action_authority"] is False + assert len(service.calls) == 1 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_browser_cannot_supply_requester_or_scope() -> None: + service = FakeAuthorityRequests() + server, thread = _server(service) + try: + status, _ = _request( + server, + "POST", + "/api/v1/ghostwalk/authority-request/requests", + { + "target_inference_receipt_sha256": TARGET, + "expected_admission_receipt_sha256": ADMISSION, + "requester_id": "browser:fake", + "requested_scope_value": "TOGGLE_AIRPLANE_MODE", + }, + ) + assert status == 400 + assert service.calls == [] + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) From 172b90af2c6e339284f766b16557b7700fd343aa Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:55:44 -0700 Subject: [PATCH 07/19] feat: add AuthorityRequest sidecar proxy --- .../host/ghostWalkAuthorityRequestProxy.mjs | 219 ++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 phishell/host/ghostWalkAuthorityRequestProxy.mjs diff --git a/phishell/host/ghostWalkAuthorityRequestProxy.mjs b/phishell/host/ghostWalkAuthorityRequestProxy.mjs new file mode 100644 index 00000000..698bf9c0 --- /dev/null +++ b/phishell/host/ghostWalkAuthorityRequestProxy.mjs @@ -0,0 +1,219 @@ +import { ghostWalkSidecarPort, GHOSTWALK_HOST } from "./ghostWalkControlProxy.mjs"; + +const SHA256 = /^[0-9a-f]{64}$/; +const INTENT_CODE = /^[A-Z][A-Z0-9_]{2,127}$/; + +function record(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function sha(value) { + return typeof value === "string" && SHA256.test(value); +} + +function timestamp(value) { + return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value)); +} + +function boundedString(value, maximum = 512) { + return typeof value === "string" && value.length > 0 && value.length <= maximum; +} + +function nullableSha(value) { + return value === null || sha(value); +} + +function zeroSnakeAuthority(value) { + return ( + record(value) && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false + ); +} + +function zeroTransportAuthority(value) { + return ( + record(value) && + value.policyAuthority === false && + value.operationalAuthority === false && + value.actionAuthority === false && + value.executionAuthority === false + ); +} + +export function validateGhostWalkAuthorityRequest(value) { + return ( + zeroSnakeAuthority(value) && + value.schema_version === "phios.ghostwalk_authority_request.v0.31" && + sha(value.admission_receipt_sha256) && + sha(value.target_inference_receipt_sha256) && + sha(value.accepted_intent_revision_sha256) && + sha(value.policy_profile_sha256) && + boundedString(value.intent_family, 64) && + typeof value.intent_code === "string" && + INTENT_CODE.test(value.intent_code) && + boundedString(value.requester_id) && + value.requested_authority_kind === "ACTION_AUTHORITY" && + value.requested_scope_kind === "ACCEPTED_INTENT" && + value.requested_scope_value === value.intent_code && + value.request_state === "PENDING_AUTHORIZATION" && + timestamp(value.requested_at) && + value.authorization_granted === false && + value.action_lease_created === false && + value.effect_performed === false && + sha(value.authority_request_sha256) + ); +} + +export function validateGhostWalkAuthorityRequestReadiness(value) { + if (!zeroSnakeAuthority(value)) return false; + if ( + value.schema_version !== "phios.ghostwalk_authority_request_readiness.v0.31" || + !sha(value.target_inference_receipt_sha256) || + !sha(value.accepted_intent_revision_sha256) || + !sha(value.policy_profile_sha256) || + !["ALLOW_REQUEST", "HOLD", "DENY"].includes(value.policy_decision) || + typeof value.ready !== "boolean" || + ![ + "READY", + "POLICY_NOT_ALLOW_REQUEST", + "ADMISSION_RECEIPT_REQUIRED", + "ADMISSION_RECEIPT_STALE", + "REQUEST_ALREADY_EXISTS", + ].includes(value.reason) || + !nullableSha(value.admission_receipt_sha256) || + !nullableSha(value.existing_authority_request_sha256) || + value.authorization_granted !== false || + value.action_lease_created !== false || + value.effect_performed !== false || + !sha(value.readiness_sha256) + ) { + return false; + } + return value.ready === (value.reason === "READY"); +} + +function validBase(value, created) { + return ( + zeroTransportAuthority(value) && + value.transportSchemaVersion === "phios.ghostwalk-authority-request-transport.v0.31" && + value.transport === "loopback-http" && + value.transportIdentity === "phios-ghostwalk-authority-request" && + value.localOnly === true && + value.requestCreated === created && + value.desktopEffectPerformed === false && + value.authorizationGranted === false && + value.actionLeaseCreated === false && + value.effectPerformed === created && + timestamp(value.servedAt) + ); +} + +export function validateGhostWalkAuthorityRequestStatusEnvelope(value) { + return ( + validBase(value, false) && + validateGhostWalkAuthorityRequestReadiness(value.readiness) && + ( + value.request === null || + validateGhostWalkAuthorityRequest(value.request) + ) + ); +} + +export function validateGhostWalkAuthorityRequestCreateEnvelope(value) { + return ( + validBase(value, true) && + validateGhostWalkAuthorityRequest(value.request) + ); +} + +export function validateGhostWalkAuthorityRequestCreatePayload(value) { + if (!record(value)) return false; + const keys = Object.keys(value).sort(); + const expected = [ + "expected_admission_receipt_sha256", + "target_inference_receipt_sha256", + ]; + return ( + keys.length === expected.length && + keys.every((key, index) => key === expected[index]) && + sha(value.target_inference_receipt_sha256) && + sha(value.expected_admission_receipt_sha256) + ); +} + +async function request(url, init, fetcher, timeoutMs) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), timeoutMs); + try { + return await fetcher(url, { ...init, signal: controller.signal }); + } catch { + return null; + } finally { + clearTimeout(timeout); + } +} + +export async function fetchGhostWalkAuthorityRequestStatus(targetSha256, { + fetcher = globalThis.fetch.bind(globalThis), + port = ghostWalkSidecarPort(), + timeoutMs = 1500, +} = {}) { + if (!sha(targetSha256)) return null; + const response = await request( + `http://${GHOSTWALK_HOST}:${port}/api/v1/ghostwalk/authority-request?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + headers: { accept: "application/json" }, + }, + fetcher, + timeoutMs, + ); + if (!response) return null; + if (response.status === 404) return { kind: "not_ready" }; + if (!response.ok) return null; + try { + const payload = await response.json(); + return validateGhostWalkAuthorityRequestStatusEnvelope(payload) + ? { kind: "found", envelope: payload } + : null; + } catch { + return null; + } +} + +export async function createGhostWalkAuthorityRequest(payload, { + fetcher = globalThis.fetch.bind(globalThis), + port = ghostWalkSidecarPort(), + timeoutMs = 2500, +} = {}) { + if (!validateGhostWalkAuthorityRequestCreatePayload(payload)) return null; + const response = await request( + `http://${GHOSTWALK_HOST}:${port}/api/v1/ghostwalk/authority-request/requests`, + { + method: "POST", + cache: "no-store", + headers: { + accept: "application/json", + "content-type": "application/json", + }, + body: JSON.stringify(payload), + }, + fetcher, + timeoutMs, + ); + if (!response) return null; + if (response.status === 409) return { kind: "conflict" }; + if (!response.ok) return null; + try { + const result = await response.json(); + return validateGhostWalkAuthorityRequestCreateEnvelope(result) + ? { kind: "created", envelope: result } + : null; + } catch { + return null; + } +} From b6e0369cc4ffa1ecd3fea730f8ae42ef8ac0f7e8 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:55:46 -0700 Subject: [PATCH 08/19] test: validate AuthorityRequest proxy --- .../ghostWalkAuthorityRequestProxy.test.mjs | 153 ++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 phishell/host/ghostWalkAuthorityRequestProxy.test.mjs diff --git a/phishell/host/ghostWalkAuthorityRequestProxy.test.mjs b/phishell/host/ghostWalkAuthorityRequestProxy.test.mjs new file mode 100644 index 00000000..335a3ace --- /dev/null +++ b/phishell/host/ghostWalkAuthorityRequestProxy.test.mjs @@ -0,0 +1,153 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + createGhostWalkAuthorityRequest, + fetchGhostWalkAuthorityRequestStatus, + validateGhostWalkAuthorityRequestCreateEnvelope, + validateGhostWalkAuthorityRequestCreatePayload, + validateGhostWalkAuthorityRequestStatusEnvelope, +} from "./ghostWalkAuthorityRequestProxy.mjs"; + +const request = { + schema_version: "phios.ghostwalk_authority_request.v0.31", + admission_receipt_sha256: "a".repeat(64), + target_inference_receipt_sha256: "b".repeat(64), + accepted_intent_revision_sha256: "c".repeat(64), + policy_profile_sha256: "d".repeat(64), + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + requester_id: "operator:local", + requested_authority_kind: "ACTION_AUTHORITY", + requested_scope_kind: "ACCEPTED_INTENT", + requested_scope_value: "OPEN_NETWORK_ADAPTER_PROPERTIES", + request_state: "PENDING_AUTHORIZATION", + requested_at: "2026-09-27T07:30:00.000Z", + authorization_granted: false, + action_lease_created: false, + effect_performed: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + authority_request_sha256: "e".repeat(64), +}; + +const readiness = { + schema_version: "phios.ghostwalk_authority_request_readiness.v0.31", + target_inference_receipt_sha256: "b".repeat(64), + accepted_intent_revision_sha256: "c".repeat(64), + policy_profile_sha256: "d".repeat(64), + policy_decision: "ALLOW_REQUEST", + ready: true, + reason: "READY", + admission_receipt_sha256: "a".repeat(64), + existing_authority_request_sha256: null, + authorization_granted: false, + action_lease_created: false, + effect_performed: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + readiness_sha256: "f".repeat(64), +}; + +const base = { + transportSchemaVersion: "phios.ghostwalk-authority-request-transport.v0.31", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-authority-request", + localOnly: true, + requestCreated: false, + desktopEffectPerformed: false, + authorizationGranted: false, + actionLeaseCreated: false, + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T07:30:00.000Z", +}; + +test("status envelope remains zero authority", () => { + assert.equal( + validateGhostWalkAuthorityRequestStatusEnvelope({ + ...base, + readiness, + request: null, + }), + true, + ); +}); + +test("creation envelope records request without granting it", () => { + assert.equal( + validateGhostWalkAuthorityRequestCreateEnvelope({ + ...base, + requestCreated: true, + effectPerformed: true, + request, + }), + true, + ); +}); + +test("browser payload cannot control requester or semantic scope", () => { + const payload = { + target_inference_receipt_sha256: "b".repeat(64), + expected_admission_receipt_sha256: "a".repeat(64), + }; + assert.equal(validateGhostWalkAuthorityRequestCreatePayload(payload), true); + assert.equal( + validateGhostWalkAuthorityRequestCreatePayload({ + ...payload, + requester_id: "browser:fake", + }), + false, + ); +}); + +test("status distinguishes not-ready", async () => { + const fetcher = async () => ({ status: 404, ok: false }); + assert.deepEqual( + await fetchGhostWalkAuthorityRequestStatus("b".repeat(64), { + fetcher, + port: 3973, + }), + { kind: "not_ready" }, + ); +}); + +test("create preserves conflict and validates success", async () => { + const payload = { + target_inference_receipt_sha256: "b".repeat(64), + expected_admission_receipt_sha256: "a".repeat(64), + }; + const conflictFetcher = async () => ({ status: 409, ok: false }); + assert.deepEqual( + await createGhostWalkAuthorityRequest(payload, { + fetcher: conflictFetcher, + port: 3973, + }), + { kind: "conflict" }, + ); + + const successFetcher = async () => ({ + status: 200, + ok: true, + async json() { + return { + ...base, + requestCreated: true, + effectPerformed: true, + request, + }; + }, + }); + const result = await createGhostWalkAuthorityRequest(payload, { + fetcher: successFetcher, + port: 3973, + }); + assert.equal(result?.kind, "created"); +}); From 094758d3d8828fa3170a4df3f505e466f916704d Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:56:14 -0700 Subject: [PATCH 09/19] feat: proxy AuthorityRequest through PhiShell --- phishell/host/localTransport.mjs | 114 +++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/phishell/host/localTransport.mjs b/phishell/host/localTransport.mjs index efb1c7d8..e5e1e4d1 100644 --- a/phishell/host/localTransport.mjs +++ b/phishell/host/localTransport.mjs @@ -37,6 +37,11 @@ import { recordGhostWalkPolicyAdmission, validateGhostWalkPolicyRecordPayload, } from "./ghostWalkPolicyAdmissionProxy.mjs"; +import { + createGhostWalkAuthorityRequest, + fetchGhostWalkAuthorityRequestStatus, + validateGhostWalkAuthorityRequestCreatePayload, +} from "./ghostWalkAuthorityRequestProxy.mjs"; import { createPersistRequest, fetchBrokerHealth, @@ -139,6 +144,8 @@ export function createLocalObservationServer({ ghostWalkAcceptedIntentMutator = applyGhostWalkAcceptedIntentMutation, ghostWalkPolicyAdmissionFetcher = fetchGhostWalkPolicyAdmission, ghostWalkPolicyAdmissionRecorder = recordGhostWalkPolicyAdmission, + ghostWalkAuthorityRequestFetcher = fetchGhostWalkAuthorityRequestStatus, + ghostWalkAuthorityRequestCreator = createGhostWalkAuthorityRequest, } = {}) { if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new Error("local observation port must be an integer between 0 and 65535"); @@ -148,6 +155,65 @@ export function createLocalObservationServer({ try { const url = new URL(request.url ?? "/", `http://${LOOPBACK_HOST}`); + if ( + request.method === "POST" && + url.pathname === "/api/v1/ghostwalk/authority-request/requests" + ) { + let payload; + try { + payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); + } catch { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_authority_request_body", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + if (!validateGhostWalkAuthorityRequestCreatePayload(payload)) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_authority_request_create", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + const result = await ghostWalkAuthorityRequestCreator(payload); + if (result?.kind === "conflict") { + jsonResponse(response, 409, { + error: "ghostwalk_authority_request_conflict", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "created") { + jsonResponse(response, 503, { + error: "ghostwalk_authority_request_unavailable", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + jsonResponse(response, 200, result.envelope); + return; + } + if ( request.method === "POST" && url.pathname === "/api/v1/ghostwalk/policy-admission/evaluations" @@ -452,6 +518,54 @@ export function createLocalObservationServer({ return; } + if (url.pathname === "/api/v1/ghostwalk/authority-request") { + const keys = [...url.searchParams.keys()]; + const target = url.searchParams.get("target"); + if ( + keys.length !== 1 || + keys[0] !== "target" || + typeof target !== "string" || + !/^[0-9a-f]{64}$/.test(target) + ) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_authority_request_status", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + const result = await ghostWalkAuthorityRequestFetcher(target); + if (result?.kind === "not_ready") { + jsonResponse(response, 404, { + error: "ghostwalk_authority_request_not_ready", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "found") { + jsonResponse(response, 503, { + error: "ghostwalk_authority_request_unavailable", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + jsonResponse(response, 200, result.envelope); + return; + } + if (url.pathname === "/api/v1/ghostwalk/policy-admission") { const keys = [...url.searchParams.keys()]; const target = url.searchParams.get("target"); From 72b5f6b347e62056c0c01ef199cfaf7bda0a0751 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:57:24 -0700 Subject: [PATCH 10/19] test: cover PhiShell AuthorityRequest routes --- ...alkAuthorityRequestLocalTransport.test.mjs | 128 ++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 phishell/host/ghostWalkAuthorityRequestLocalTransport.test.mjs diff --git a/phishell/host/ghostWalkAuthorityRequestLocalTransport.test.mjs b/phishell/host/ghostWalkAuthorityRequestLocalTransport.test.mjs new file mode 100644 index 00000000..c976955b --- /dev/null +++ b/phishell/host/ghostWalkAuthorityRequestLocalTransport.test.mjs @@ -0,0 +1,128 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { createLocalObservationServer } from "./localTransport.mjs"; + +const request = { + schema_version: "phios.ghostwalk_authority_request.v0.31", + admission_receipt_sha256: "a".repeat(64), + target_inference_receipt_sha256: "b".repeat(64), + accepted_intent_revision_sha256: "c".repeat(64), + policy_profile_sha256: "d".repeat(64), + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + requester_id: "operator:local", + requested_authority_kind: "ACTION_AUTHORITY", + requested_scope_kind: "ACCEPTED_INTENT", + requested_scope_value: "OPEN_NETWORK_ADAPTER_PROPERTIES", + request_state: "PENDING_AUTHORIZATION", + requested_at: "2026-09-27T07:30:00.000Z", + authorization_granted: false, + action_lease_created: false, + effect_performed: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + authority_request_sha256: "e".repeat(64), +}; +const readiness = { + schema_version: "phios.ghostwalk_authority_request_readiness.v0.31", + target_inference_receipt_sha256: "b".repeat(64), + accepted_intent_revision_sha256: "c".repeat(64), + policy_profile_sha256: "d".repeat(64), + policy_decision: "ALLOW_REQUEST", + ready: true, + reason: "READY", + admission_receipt_sha256: "a".repeat(64), + existing_authority_request_sha256: null, + authorization_granted: false, + action_lease_created: false, + effect_performed: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + readiness_sha256: "f".repeat(64), +}; +const base = { + transportSchemaVersion: "phios.ghostwalk-authority-request-transport.v0.31", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-authority-request", + localOnly: true, + requestCreated: false, + desktopEffectPerformed: false, + authorizationGranted: false, + actionLeaseCreated: false, + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T07:30:00.000Z", +}; + +test("local transport proxies AuthorityRequest readiness", async () => { + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkAuthorityRequestFetcher: async () => ({ + kind: "found", + envelope: { ...base, readiness, request: null }, + }), + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/authority-request?target=${"b".repeat(64)}`, + ); + assert.equal(response.status, 200); + const payload = await response.json(); + assert.equal(payload.readiness.ready, true); + assert.equal(payload.authorizationGranted, false); + } finally { + await transport.close(); + } +}); + +test("local transport creates request without granting authority", async () => { + const seen = []; + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkAuthorityRequestCreator: async (payload) => { + seen.push(payload); + return { + kind: "created", + envelope: { + ...base, + requestCreated: true, + effectPerformed: true, + request, + }, + }; + }, + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/authority-request/requests`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target_inference_receipt_sha256: "b".repeat(64), + expected_admission_receipt_sha256: "a".repeat(64), + }), + }, + ); + assert.equal(response.status, 200); + const payload = await response.json(); + assert.equal(payload.request.request_state, "PENDING_AUTHORIZATION"); + assert.equal(payload.authorizationGranted, false); + assert.equal(payload.actionLeaseCreated, false); + assert.equal(seen.length, 1); + } finally { + await transport.close(); + } +}); From de4890022aafc1592cb1c3c147fd4e6549538f27 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:57:26 -0700 Subject: [PATCH 11/19] feat: add typed AuthorityRequest browser client --- phishell/src/ghostwalk/authorityRequest.ts | 251 +++++++++++++++++++++ 1 file changed, 251 insertions(+) create mode 100644 phishell/src/ghostwalk/authorityRequest.ts diff --git a/phishell/src/ghostwalk/authorityRequest.ts b/phishell/src/ghostwalk/authorityRequest.ts new file mode 100644 index 00000000..5970538d --- /dev/null +++ b/phishell/src/ghostwalk/authorityRequest.ts @@ -0,0 +1,251 @@ +export interface GhostWalkAuthorityRequest { + schema_version: "phios.ghostwalk_authority_request.v0.31"; + admission_receipt_sha256: string; + target_inference_receipt_sha256: string; + accepted_intent_revision_sha256: string; + policy_profile_sha256: string; + intent_family: string; + intent_code: string; + requester_id: string; + requested_authority_kind: "ACTION_AUTHORITY"; + requested_scope_kind: "ACCEPTED_INTENT"; + requested_scope_value: string; + request_state: "PENDING_AUTHORIZATION"; + requested_at: string; + authorization_granted: false; + action_lease_created: false; + effect_performed: false; + policy_authority: false; + operational_authority: false; + action_authority: false; + execution_authority: false; + authority_request_sha256: string; +} + +export interface GhostWalkAuthorityRequestReadiness { + schema_version: "phios.ghostwalk_authority_request_readiness.v0.31"; + target_inference_receipt_sha256: string; + accepted_intent_revision_sha256: string; + policy_profile_sha256: string; + policy_decision: "ALLOW_REQUEST" | "HOLD" | "DENY"; + ready: boolean; + reason: + | "READY" + | "POLICY_NOT_ALLOW_REQUEST" + | "ADMISSION_RECEIPT_REQUIRED" + | "ADMISSION_RECEIPT_STALE" + | "REQUEST_ALREADY_EXISTS"; + admission_receipt_sha256: string | null; + existing_authority_request_sha256: string | null; + authorization_granted: false; + action_lease_created: false; + effect_performed: false; + policy_authority: false; + operational_authority: false; + action_authority: false; + execution_authority: false; + readiness_sha256: string; +} + +export type GhostWalkAuthorityRequestStatusResult = + | { + kind: "found"; + readiness: GhostWalkAuthorityRequestReadiness; + request: GhostWalkAuthorityRequest | null; + } + | { kind: "not_ready" } + | { kind: "unavailable" }; + +export type GhostWalkAuthorityRequestCreateResult = + | { kind: "created"; request: GhostWalkAuthorityRequest } + | { kind: "conflict" } + | { kind: "unavailable" }; + +function record(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function sha(value: unknown): value is string { + return typeof value === "string" && /^[0-9a-f]{64}$/.test(value); +} + +function timestamp(value: unknown): value is string { + return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value)); +} + +function isRequest(value: unknown): value is GhostWalkAuthorityRequest { + if (!record(value)) return false; + return ( + value.schema_version === "phios.ghostwalk_authority_request.v0.31" && + sha(value.admission_receipt_sha256) && + sha(value.target_inference_receipt_sha256) && + sha(value.accepted_intent_revision_sha256) && + sha(value.policy_profile_sha256) && + typeof value.intent_family === "string" && + typeof value.intent_code === "string" && + /^[A-Z][A-Z0-9_]{2,127}$/.test(value.intent_code) && + typeof value.requester_id === "string" && + value.requested_authority_kind === "ACTION_AUTHORITY" && + value.requested_scope_kind === "ACCEPTED_INTENT" && + value.requested_scope_value === value.intent_code && + value.request_state === "PENDING_AUTHORIZATION" && + timestamp(value.requested_at) && + value.authorization_granted === false && + value.action_lease_created === false && + value.effect_performed === false && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false && + sha(value.authority_request_sha256) + ); +} + +function isReadiness(value: unknown): value is GhostWalkAuthorityRequestReadiness { + if (!record(value)) return false; + const reason = value.reason; + return ( + value.schema_version === "phios.ghostwalk_authority_request_readiness.v0.31" && + sha(value.target_inference_receipt_sha256) && + sha(value.accepted_intent_revision_sha256) && + sha(value.policy_profile_sha256) && + (value.policy_decision === "ALLOW_REQUEST" || + value.policy_decision === "HOLD" || + value.policy_decision === "DENY") && + typeof value.ready === "boolean" && + (reason === "READY" || + reason === "POLICY_NOT_ALLOW_REQUEST" || + reason === "ADMISSION_RECEIPT_REQUIRED" || + reason === "ADMISSION_RECEIPT_STALE" || + reason === "REQUEST_ALREADY_EXISTS") && + (value.admission_receipt_sha256 === null || sha(value.admission_receipt_sha256)) && + (value.existing_authority_request_sha256 === null || + sha(value.existing_authority_request_sha256)) && + value.ready === (reason === "READY") && + value.authorization_granted === false && + value.action_lease_created === false && + value.effect_performed === false && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false && + sha(value.readiness_sha256) + ); +} + +function validBase(value: unknown, created: boolean): value is Record { + if (!record(value)) return false; + return ( + value.transportSchemaVersion === "phios.ghostwalk-authority-request-transport.v0.31" && + value.transport === "loopback-http" && + value.transportIdentity === "phios-ghostwalk-authority-request" && + value.localOnly === true && + value.requestCreated === created && + value.desktopEffectPerformed === false && + value.authorizationGranted === false && + value.actionLeaseCreated === false && + value.policyAuthority === false && + value.operationalAuthority === false && + value.actionAuthority === false && + value.executionAuthority === false && + value.effectPerformed === created && + timestamp(value.servedAt) + ); +} + +export function createGhostWalkAuthorityRequestClient({ + fetcher = globalThis.fetch.bind(globalThis), + timeoutMs = 2_500, +}: { + fetcher?: typeof fetch; + timeoutMs?: number; +} = {}) { + return { + async read(targetSha256: string): Promise { + if (!sha(targetSha256)) return { kind: "unavailable" }; + const controller = new AbortController(); + const timeout = globalThis.setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + `/api/v1/ghostwalk/authority-request?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + credentials: "same-origin", + headers: { accept: "application/json" }, + signal: controller.signal, + }, + ); + if (response.status === 404) return { kind: "not_ready" }; + if (!response.ok) return { kind: "unavailable" }; + const payload: unknown = await response.json(); + if (!validBase(payload, false) || !isReadiness(payload.readiness)) { + return { kind: "unavailable" }; + } + if (payload.request !== null && !isRequest(payload.request)) { + return { kind: "unavailable" }; + } + return { + kind: "found", + readiness: payload.readiness, + request: payload.request as GhostWalkAuthorityRequest | null, + }; + } catch { + return { kind: "unavailable" }; + } finally { + globalThis.clearTimeout(timeout); + } + }, + + async create({ + targetSha256, + expectedAdmissionReceiptSha256, + }: { + targetSha256: string; + expectedAdmissionReceiptSha256: string; + }): Promise { + if (!sha(targetSha256) || !sha(expectedAdmissionReceiptSha256)) { + return { kind: "unavailable" }; + } + const controller = new AbortController(); + const timeout = globalThis.setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + "/api/v1/ghostwalk/authority-request/requests", + { + method: "POST", + cache: "no-store", + credentials: "same-origin", + headers: { + accept: "application/json", + "content-type": "application/json", + }, + body: JSON.stringify({ + target_inference_receipt_sha256: targetSha256, + expected_admission_receipt_sha256: + expectedAdmissionReceiptSha256, + }), + signal: controller.signal, + }, + ); + if (response.status === 409) return { kind: "conflict" }; + if (!response.ok) return { kind: "unavailable" }; + const payload: unknown = await response.json(); + if ( + !validBase(payload, true) || + !isRequest(payload.request) + ) { + return { kind: "unavailable" }; + } + return { kind: "created", request: payload.request }; + } catch { + return { kind: "unavailable" }; + } finally { + globalThis.clearTimeout(timeout); + } + }, + }; +} + +export const ghostWalkAuthorityRequestClient = + createGhostWalkAuthorityRequestClient(); From bcc6de9997addd235559105b9311ea2e08306f5d Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:57:28 -0700 Subject: [PATCH 12/19] test: cover AuthorityRequest browser client --- .../src/ghostwalk/authorityRequest.test.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 phishell/src/ghostwalk/authorityRequest.test.ts diff --git a/phishell/src/ghostwalk/authorityRequest.test.ts b/phishell/src/ghostwalk/authorityRequest.test.ts new file mode 100644 index 00000000..0c733057 --- /dev/null +++ b/phishell/src/ghostwalk/authorityRequest.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it, vi } from "vitest"; +import { createGhostWalkAuthorityRequestClient } from "./authorityRequest"; + +describe("Ghost-Walk AuthorityRequest browser client", () => { + it("distinguishes not-ready status", async () => { + const fetcher = vi.fn(async () => new Response("", { status: 404 })); + const client = createGhostWalkAuthorityRequestClient({ + fetcher: fetcher as typeof fetch, + }); + await expect(client.read("a".repeat(64))).resolves.toEqual({ + kind: "not_ready", + }); + }); + + it("sends only target and admission receipt hashes", async () => { + const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { + const body = JSON.parse(String(init?.body)); + expect(body).toEqual({ + target_inference_receipt_sha256: "a".repeat(64), + expected_admission_receipt_sha256: "b".repeat(64), + }); + expect("requester_id" in body).toBe(false); + expect("requested_scope_value" in body).toBe(false); + return new Response("", { status: 409 }); + }); + const client = createGhostWalkAuthorityRequestClient({ + fetcher: fetcher as typeof fetch, + }); + await expect( + client.create({ + targetSha256: "a".repeat(64), + expectedAdmissionReceiptSha256: "b".repeat(64), + }), + ).resolves.toEqual({ kind: "conflict" }); + }); +}); From bd0b8f636f6bb6e994ec937b6a7d6c2a3435d8bc Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:57:29 -0700 Subject: [PATCH 13/19] feat: render Ghost-Walk AuthorityRequest card --- .../GhostWalkAuthorityRequestCard.tsx | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 phishell/src/components/GhostWalkAuthorityRequestCard.tsx diff --git a/phishell/src/components/GhostWalkAuthorityRequestCard.tsx b/phishell/src/components/GhostWalkAuthorityRequestCard.tsx new file mode 100644 index 00000000..88c7a229 --- /dev/null +++ b/phishell/src/components/GhostWalkAuthorityRequestCard.tsx @@ -0,0 +1,127 @@ +import { useCallback, useEffect, useState } from "react"; +import { + ghostWalkAuthorityRequestClient, + type GhostWalkAuthorityRequest, + type GhostWalkAuthorityRequestReadiness, +} from "../ghostwalk/authorityRequest"; + +function shortHash(value: string) { + return `${value.slice(0, 10)}…`; +} + +export function GhostWalkAuthorityRequestCard({ + targetSha256, + refreshToken, +}: { + targetSha256: string; + refreshToken: string; +}) { + const [readiness, setReadiness] = + useState(null); + const [request, setRequest] = + useState(null); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); + + const load = useCallback(async () => { + const result = await ghostWalkAuthorityRequestClient.read(targetSha256); + if (result.kind === "found") { + setReadiness(result.readiness); + setRequest(result.request); + setMessage(null); + return; + } + setReadiness(null); + setRequest(null); + setMessage( + result.kind === "not_ready" + ? "AuthorityRequest is not ready because accepted-intent or policy evidence is missing." + : "AuthorityRequest state is unavailable or invalid.", + ); + }, [targetSha256, refreshToken]); + + useEffect(() => { + void load(); + }, [load]); + + const createRequest = useCallback(async () => { + if (!readiness?.ready || !readiness.admission_receipt_sha256) return; + setBusy(true); + setMessage(null); + try { + const result = await ghostWalkAuthorityRequestClient.create({ + targetSha256, + expectedAdmissionReceiptSha256: + readiness.admission_receipt_sha256, + }); + if (result.kind === "conflict") { + setMessage( + "AuthorityRequest conflict: admission evidence changed or a request already exists. Reload first.", + ); + return; + } + if (result.kind === "unavailable") { + setMessage("AuthorityRequest creation was rejected or could not be validated."); + return; + } + setRequest(result.request); + setMessage( + `AuthorityRequest ${shortHash(result.request.authority_request_sha256)} created as PENDING_AUTHORIZATION. No authority was granted.`, + ); + await load(); + } finally { + setBusy(false); + } + }, [load, readiness, targetSha256]); + + return ( +
+
+
+ AUTHORITY REQUEST + {request?.request_state ?? readiness?.reason ?? "NOT READY"} +
+ ACTION AUTH 0 +
+ + {readiness && ( +
+ policy {readiness.policy_decision} + ready {readiness.ready ? "YES" : "NO"} + admission {readiness.admission_receipt_sha256 ? shortHash(readiness.admission_receipt_sha256) : "NONE"} + lease NONE +
+ )} + + {request && ( +
+ {request.requested_scope_value} + + {request.requested_authority_kind} · {shortHash(request.authority_request_sha256)} + + + requester {request.requester_id} · authorization NOT GRANTED + +
+ )} + + {readiness?.ready && !request && ( + + )} + + {message && ( +
{message}
+ )} + +
+ REQUEST != AUTHORIZATION · PENDING_AUTHORIZATION != ACTION AUTHORITY · ACTIONLEASE NOT CREATED +
+
+ ); +} From 007a69397182408a84223d6965374ce4936cff68 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:57:41 -0700 Subject: [PATCH 14/19] feat: mount AuthorityRequest under policy admission --- phishell/src/components/GhostWalkPolicyAdmissionCard.tsx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/phishell/src/components/GhostWalkPolicyAdmissionCard.tsx b/phishell/src/components/GhostWalkPolicyAdmissionCard.tsx index c9d379e3..62160710 100644 --- a/phishell/src/components/GhostWalkPolicyAdmissionCard.tsx +++ b/phishell/src/components/GhostWalkPolicyAdmissionCard.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useState } from "react"; +import { GhostWalkAuthorityRequestCard } from "./GhostWalkAuthorityRequestCard"; import { ghostWalkPolicyAdmissionClient, type GhostWalkPolicyProfile, @@ -121,6 +122,13 @@ export function GhostWalkPolicyAdmissionCard({
ALLOW_REQUEST != AUTHORITY REQUEST · POLICY ADMISSION != ACTIONLEASE · NO EXECUTION
+ + {projection && profile && ( + + )} ); } From 3a09b474f679b9efb53c9e7d9a08ab1ce5acf870 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:57:56 -0700 Subject: [PATCH 15/19] style: add Ghost-Walk AuthorityRequest card --- phishell/src/styles.css | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/phishell/src/styles.css b/phishell/src/styles.css index 4e0cef20..b48ee7f1 100644 --- a/phishell/src/styles.css +++ b/phishell/src/styles.css @@ -339,3 +339,14 @@ linear-gradient(135deg,rgba(13,32,42,.92),rgba(5,13,17,.96));box-shadow:inset 0 .ghostwalk-policy-receipt,.ghostwalk-policy-message{padding:7px 8px;border-radius:6px;font-size:7px;line-height:1.45}.ghostwalk-policy-receipt{border:1px solid rgba(32,229,192,.18);background:rgba(32,229,192,.02);color:var(--teal)}.ghostwalk-policy-message{border:1px solid rgba(243,182,75,.22);background:rgba(243,182,75,.025);color:#d7c18f} .ghostwalk-policy-boundary{padding:7px 8px;border:1px solid rgba(184,151,255,.2);border-radius:6px;background:rgba(184,151,255,.02);color:#c8adff;font:6px ui-monospace,monospace;letter-spacing:.04em;line-height:1.45} @media(max-width:780px){.ghostwalk-policy-grid{grid-template-columns:1fr}} + + +/* Macro Runtime v0.31 AuthorityRequest */ +.ghostwalk-authority-request{display:grid;gap:8px;margin-top:4px;padding:10px;border:1px solid rgba(255,123,196,.24);border-radius:8px;background:linear-gradient(155deg,rgba(38,12,28,.52),rgba(5,15,20,.92))} +.ghostwalk-authority-request-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.ghostwalk-authority-request-head small{display:block;color:#ff9bd2;font-size:7px;letter-spacing:.13em}.ghostwalk-authority-request-head b{display:block;margin-top:4px;color:var(--secondary);font:8px ui-monospace,monospace}.ghostwalk-authority-request-head>span{padding:4px 6px;border:1px solid rgba(255,123,196,.22);border-radius:4px;color:#ff9bd2;font:6px ui-monospace,monospace;letter-spacing:.05em} +.ghostwalk-authority-request-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:5px}.ghostwalk-authority-request-grid span{display:grid;gap:2px;padding:6px;border:1px solid rgba(255,123,196,.13);border-radius:5px;color:var(--muted);font:6px ui-monospace,monospace}.ghostwalk-authority-request-grid b{color:var(--secondary);font-size:7px;overflow-wrap:anywhere} +.ghostwalk-authority-request-current{display:grid;gap:3px;padding:8px;border:1px solid rgba(255,123,196,.16);border-radius:6px;background:rgba(255,123,196,.02)}.ghostwalk-authority-request-current b{color:#ff9bd2;font:8px ui-monospace,monospace;overflow-wrap:anywhere}.ghostwalk-authority-request-current span,.ghostwalk-authority-request-current small{color:var(--muted);font:6px ui-monospace,monospace} +.ghostwalk-authority-request-create{height:30px;border:1px solid rgba(255,123,196,.35);border-radius:6px;background:rgba(255,123,196,.04);color:#ff9bd2;font-size:6px;letter-spacing:.05em;cursor:pointer}.ghostwalk-authority-request-create:disabled{opacity:.4;cursor:not-allowed} +.ghostwalk-authority-request-message{padding:7px 8px;border:1px solid rgba(243,182,75,.22);border-radius:6px;background:rgba(243,182,75,.025);color:#d7c18f;font-size:7px;line-height:1.45} +.ghostwalk-authority-request-boundary{padding:7px 8px;border:1px solid rgba(255,123,196,.18);border-radius:6px;background:rgba(255,123,196,.02);color:#ff9bd2;font:6px ui-monospace,monospace;letter-spacing:.04em;line-height:1.45} +@media(max-width:780px){.ghostwalk-authority-request-grid{grid-template-columns:1fr}} From 47cf00f47b7e7a002f6484650199193826f13da3 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:58:25 -0700 Subject: [PATCH 16/19] fix: verify AuthorityRequest admission provenance --- phios/macro_authority_request.py | 57 ++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/phios/macro_authority_request.py b/phios/macro_authority_request.py index 6eb9bc55..751d1036 100644 --- a/phios/macro_authority_request.py +++ b/phios/macro_authority_request.py @@ -694,7 +694,7 @@ def latest( target_inference_receipt_sha256=target ) requests = [ - GhostWalkAuthorityRequest.from_dict(row) + self._parse_request_row(row) for row in rows ] return requests[-1] if requests else None @@ -755,7 +755,7 @@ def _request_for_admission( ) -> GhostWalkAuthorityRequest | None: matches: list[GhostWalkAuthorityRequest] = [] for row in self._ledger.ghostwalk_authority_requests(): - request = GhostWalkAuthorityRequest.from_dict(row) + request = self._parse_request_row(row) if ( request.admission_receipt_sha256 == admission_receipt_sha256 @@ -766,3 +766,56 @@ def _request_for_admission( "multiple AuthorityRequests exist for one admission receipt" ) return matches[0] if matches else None + + def _parse_request_row( + self, + row: Mapping[str, object], + ) -> GhostWalkAuthorityRequest: + try: + request = GhostWalkAuthorityRequest.from_dict(row) + except GhostWalkAuthorityRequestError as exc: + raise GhostWalkAuthorityRequestError( + "persisted AuthorityRequest is invalid" + ) from exc + self._validate_request_provenance(request) + return request + + def _validate_request_provenance( + self, + request: GhostWalkAuthorityRequest, + ) -> None: + receipt = self._receipt_by_sha256( + request.admission_receipt_sha256 + ) + if receipt is None: + raise GhostWalkAuthorityRequestError( + "AuthorityRequest admission receipt is missing" + ) + if ( + receipt.target_inference_receipt_sha256 + != request.target_inference_receipt_sha256 + ): + raise GhostWalkAuthorityRequestError( + "AuthorityRequest target does not match admission receipt" + ) + if ( + receipt.accepted_intent_revision_sha256 + != request.accepted_intent_revision_sha256 + ): + raise GhostWalkAuthorityRequestError( + "AuthorityRequest accepted intent does not match admission receipt" + ) + if ( + receipt.policy_profile_sha256 + != request.policy_profile_sha256 + ): + raise GhostWalkAuthorityRequestError( + "AuthorityRequest policy profile does not match admission receipt" + ) + if ( + receipt.decision is not GhostWalkPolicyDecision.ALLOW_REQUEST + or not receipt.request_authority_eligible + ): + raise GhostWalkAuthorityRequestError( + "AuthorityRequest admission receipt is not ALLOW_REQUEST" + ) From 54ccae27d709c3944b9b11773b70717d63adfa27 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:58:35 -0700 Subject: [PATCH 17/19] test: fail closed on tampered AuthorityRequest --- tests/test_macro_authority_request.py | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/test_macro_authority_request.py b/tests/test_macro_authority_request.py index 413a7574..9f773bff 100644 --- a/tests/test_macro_authority_request.py +++ b/tests/test_macro_authority_request.py @@ -285,3 +285,42 @@ def test_tampered_admission_receipt_fails_closed( requests.readiness( target_inference_receipt_sha256=TARGET ) + + +def test_tampered_authority_request_fails_closed( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + admission, intent_sha = _seed(ledger) + receipt = admission.record( + target_inference_receipt_sha256=TARGET, + expected_accepted_intent_revision_sha256=intent_sha, + expected_policy_profile_sha256=admission.profile.profile_sha256, + ) + requests = GhostWalkAuthorityRequestService( + ledger=ledger, + policy_admission=admission, + requester_id="operator:local", + ) + requests.create( + target_inference_receipt_sha256=TARGET, + expected_admission_receipt_sha256=( + receipt.admission_receipt_sha256 + ), + ) + + path = ledger.path.parent / "ghostwalk-authority-requests.jsonl" + row = json.loads(path.read_text(encoding="utf-8")) + row["requester_id"] = "tampered" + path.write_text( + json.dumps(row, sort_keys=True) + "\n", + encoding="utf-8", + ) + + with pytest.raises( + GhostWalkAuthorityRequestError, + match="persisted AuthorityRequest is invalid", + ): + requests.latest( + target_inference_receipt_sha256=TARGET + ) From 2416926177e3f2c53c72d060459ea573034fb139 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:59:14 -0700 Subject: [PATCH 18/19] fix: type-narrow persisted admission booleans --- phios/macro_policy_admission.py | 59 ++++++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/phios/macro_policy_admission.py b/phios/macro_policy_admission.py index 30ce532c..118e7bc6 100644 --- a/phios/macro_policy_admission.py +++ b/phios/macro_policy_admission.py @@ -92,6 +92,14 @@ def _require_sha256(value: object, field: str) -> str: return text +def _require_bool(value: object, field: str) -> bool: + if not isinstance(value, bool): + raise GhostWalkPolicyAdmissionError( + f"{field} must be Boolean" + ) + return value + + def _require_timestamp(value: object, field: str) -> str: text = _require_text(value, field, maximum=64) try: @@ -564,25 +572,46 @@ def from_dict( ), decision=decision, reason=reason, - request_authority_eligible=payload[ - "request_authority_eligible" - ], + request_authority_eligible=_require_bool( + payload.get("request_authority_eligible"), + "request_authority_eligible", + ), evaluated_at=_require_timestamp( payload.get("evaluated_at"), "evaluated_at", ), - effect_performed=payload["effect_performed"], - desktop_effect_performed=payload[ - "desktop_effect_performed" - ], - authority_request_created=payload[ - "authority_request_created" - ], - action_lease_created=payload["action_lease_created"], - policy_authority=payload["policy_authority"], - operational_authority=payload["operational_authority"], - action_authority=payload["action_authority"], - execution_authority=payload["execution_authority"], + effect_performed=_require_bool( + payload.get("effect_performed"), + "effect_performed", + ), + desktop_effect_performed=_require_bool( + payload.get("desktop_effect_performed"), + "desktop_effect_performed", + ), + authority_request_created=_require_bool( + payload.get("authority_request_created"), + "authority_request_created", + ), + action_lease_created=_require_bool( + payload.get("action_lease_created"), + "action_lease_created", + ), + policy_authority=_require_bool( + payload.get("policy_authority"), + "policy_authority", + ), + operational_authority=_require_bool( + payload.get("operational_authority"), + "operational_authority", + ), + action_authority=_require_bool( + payload.get("action_authority"), + "action_authority", + ), + execution_authority=_require_bool( + payload.get("execution_authority"), + "execution_authority", + ), schema_version=_require_text( payload.get("schema_version"), "schema_version", From 1aa47efe0bc198cbf0649d3e6eaadc9f985a503b Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sun, 27 Sep 2026 00:59:58 -0700 Subject: [PATCH 19/19] docs: define Macro Runtime v0.31 AuthorityRequest --- docs/MACRO_RUNTIME_V0.31.md | 359 ++++++++++++++++++++++++++++++++++++ 1 file changed, 359 insertions(+) create mode 100644 docs/MACRO_RUNTIME_V0.31.md diff --git a/docs/MACRO_RUNTIME_V0.31.md b/docs/MACRO_RUNTIME_V0.31.md new file mode 100644 index 00000000..429a2a6f --- /dev/null +++ b/docs/MACRO_RUNTIME_V0.31.md @@ -0,0 +1,359 @@ +# Macro Runtime v0.31 — Ghost-Walk AuthorityRequest + +v0.31 introduces an immutable zero-authority `AuthorityRequest` artifact. + +The request is created only from one exact current `ALLOW_REQUEST` policy +admission receipt. + +Core rule: + +```text +REQUESTING AUTHORITY +!= +HAVING AUTHORITY +``` + +## Architecture position + +The governed chain is now: + +```text +machine candidate + ↓ +human annotation + ↓ +accepted intent + ↓ +policy admission + ↓ +AuthorityRequest + ↓ +future explicit authorization decision + ↓ +future ActionLease + ↓ +existing governed execution +``` + +v0.31 stops at the AuthorityRequest. + +It does not create an authorization decision, EffectIntent, EnforcementProfile, +AuthorityEpoch, ActionLease, execution handoff, or desktop effect. + +## Why semantic scope only + +v0.31 does not ask the browser to invent: + +- capability IDs +- executable payloads +- permissions +- effects +- ActionLease parameters + +The evidence available at this layer proves what semantic intent the human +accepted and that current policy allows an authority request. + +It does not yet prove how that semantic intent should map into an executable +PhiOS capability. + +The request therefore asks for: + +```text +requested_authority_kind = ACTION_AUTHORITY +requested_scope_kind = ACCEPTED_INTENT +requested_scope_value = +``` + +Example: + +```text +requested_scope_value = OPEN_NETWORK_ADAPTER_PROPERTIES +``` + +A later authorization/effect-mapping rung may decide whether that semantic +scope has a valid executable representation. + +## Preconditions + +An AuthorityRequest can be created only when all of the following are true: + +1. current policy projection is `ALLOW_REQUEST` +2. the current accepted-intent revision is unchanged +3. the current policy profile is unchanged +4. a persisted policy-admission receipt exists for that exact combination +5. the admission receipt itself is canonical and hash-valid +6. the admission receipt records `ALLOW_REQUEST` +7. no AuthorityRequest already exists for that exact admission receipt + +If any condition fails, request creation fails closed. + +## Readiness reasons + +The read-only readiness projection reports: + +```text +READY +POLICY_NOT_ALLOW_REQUEST +ADMISSION_RECEIPT_REQUIRED +ADMISSION_RECEIPT_STALE +REQUEST_ALREADY_EXISTS +``` + +`READY` is the only state in which request creation is available. + +## One request per admission receipt + +v0.31 fixes: + +```text +one admission receipt + -> at most one AuthorityRequest +``` + +This prevents repeated request creation from one policy decision. + +If accepted intent or policy changes, a new policy-admission receipt is required +before another AuthorityRequest can be created. + +## AuthorityRequest identity + +Each immutable request binds: + +- exact admission-receipt SHA-256 +- transition-inference receipt SHA-256 +- accepted-intent revision SHA-256 +- policy-profile SHA-256 +- intent family +- exact intent code +- server-owned requester identity +- requested authority kind +- requested semantic scope +- request state +- request timestamp + +All fields participate in: + +```text +authority_request_sha256 +``` + +## Request state + +v0.31 has exactly one request state: + +```text +PENDING_AUTHORIZATION +``` + +The request asserts: + +```text +authorization_granted = false +action_lease_created = false +effect_performed = false + +policy_authority = false +operational_authority = false +action_authority = false +execution_authority = false +``` + +The request object itself carries no grant. + +## Provenance validation + +When a persisted AuthorityRequest is read, PhiOS verifies: + +```text +AuthorityRequest canonical hash + ↓ +bound admission receipt exists + ↓ +admission receipt canonical hash + ↓ +same transition target + ↓ +same accepted-intent revision + ↓ +same policy profile + ↓ +decision == ALLOW_REQUEST + ↓ +request_authority_eligible == true +``` + +A request cannot become a self-certified island detached from the evidence that +allowed it to exist. + +## Server-owned identity and scope + +The browser may submit only: + +```json +{ + "target_inference_receipt_sha256": "...", + "expected_admission_receipt_sha256": "..." +} +``` + +The browser cannot supply: + +- requester ID +- requested intent code +- requested authority kind +- requested scope kind +- permissions +- effects +- capability IDs +- ActionLease data +- authority flags + +The sidecar derives requester identity and semantic scope from governed state. + +## Transport + +Read request readiness/current request: + +```http +GET /api/v1/ghostwalk/authority-request?target= +``` + +Create one request: + +```http +POST /api/v1/ghostwalk/authority-request/requests +``` + +Creating the request performs a real ledger write, so the transport reports: + +```text +requestCreated = true +effectPerformed = true +``` + +while still fixing: + +```text +desktopEffectPerformed = false +authorizationGranted = false +actionLeaseCreated = false + +policyAuthority = false +operationalAuthority = false +actionAuthority = false +executionAuthority = false +``` + +The persisted AuthorityRequest artifact itself keeps: + +```text +effect_performed = false +``` + +because the artifact describes the requested authority, not the filesystem +operation that persisted it. + +## PhiShell + +The Policy Admission card now nests an AuthorityRequest card. + +Before an admission receipt exists: + +```text +AUTHORITY REQUEST +ADMISSION_RECEIPT_REQUIRED +ACTION AUTH 0 +``` + +After an `ALLOW_REQUEST` admission receipt is recorded: + +```text +AUTHORITY REQUEST +READY +ACTION AUTH 0 + +[ CREATE AUTHORITY REQUEST ] +``` + +After creation: + +```text +AUTHORITY REQUEST +PENDING_AUTHORIZATION +ACTION AUTH 0 + +scope OPEN_NETWORK_ADAPTER_PROPERTIES +lease NONE +authorization NOT GRANTED +``` + +There is deliberately no approve, lease, or execute control in v0.31. + +## Fail-closed behavior + +v0.31 rejects: + +- policy decisions other than `ALLOW_REQUEST` +- missing admission receipts +- stale admission receipts +- tampered admission receipts +- duplicate requests for one admission receipt +- tampered AuthorityRequests +- mismatched request/admission provenance +- browser-supplied requester identity +- browser-supplied semantic scope +- browser-supplied authority fields + +## Existing ActionLease boundary + +PhiOS already defines `ActionLease` as a separate primitive carrying bounded +action authority: + +```text +action_authority = true +execution_authority = false +``` + +AuthorityRequest remains strictly earlier in the chain: + +```text +AuthorityRequest + action_authority = false + + != + +ActionLease + action_authority = true +``` + +v0.31 never imports, constructs, issues, or evaluates an ActionLease. + +## Next rung + +v0.32 should introduce an immutable explicit **AuthorizationDecision** bound to +one exact AuthorityRequest. + +That decision should support at least: + +```text +APPROVE +DENY +HOLD +``` + +Even an APPROVE decision should not itself perform execution. + +A later bridge should translate an approved request into exact executable +effect evidence and only then reach the existing ActionLease issuance path. + +```text +AuthorityRequest + ↓ +AuthorizationDecision + ↓ +effect/capability binding + ↓ +ActionLease + ↓ +governed execution +```