diff --git a/docs/MACRO_RUNTIME_V0.29.md b/docs/MACRO_RUNTIME_V0.29.md new file mode 100644 index 00000000..427eabff --- /dev/null +++ b/docs/MACRO_RUNTIME_V0.29.md @@ -0,0 +1,299 @@ +# Macro Runtime v0.29 — Typed Accepted Intent + +v0.29 introduces a distinct append-only layer for human-confirmed intent. + +It sits between editable human interpretation and any future execution policy: + +```text +machine candidate + != +human annotation + != +accepted intent + != +execution policy +``` + +The purpose of accepted intent is to record what the human says a demonstrated +transition *means* without converting that declaration into permission to act. + +## Evidence chain + +An accepted-intent revision binds: + +```text +immutable transition inference receipt + + +exact OperatorLog revision SHA-256 + + +typed intent family + + +canonical intent code + + +human acceptance identity/time +``` + +Example: + +```text +inference: + semantic appeared / window changed + +OperatorLog: + "Correction: I opened network adapter properties." + +accepted intent: + family = OPEN + code = OPEN_NETWORK_ADAPTER_PROPERTIES +``` + +The accepted intent does not modify either source artifact. + +## Typed vocabulary + +v0.29 defines a small stable intent-family vocabulary: + +```text +NAVIGATE +OPEN +CLOSE +SELECT +TOGGLE +ENTER_TEXT +SUBMIT +CONFIRM +CANCEL +OTHER +``` + +Application-specific meaning is carried by a canonical uppercase +`intent_code`. + +Except for `OTHER`, the code must match its family prefix: + +```text +OPEN + -> OPEN_NETWORK_ADAPTER_PROPERTIES + +TOGGLE + -> TOGGLE_WIFI_ENABLED + +SELECT + -> SELECT_PRIMARY_ADAPTER +``` + +This gives PhiOS typed semantics without requiring one giant enum containing +every possible action in every application. + +## Accepted-intent revision contract + +Each revision contains: + +- target transition-inference receipt SHA-256 +- exact source OperatorLog revision SHA-256 +- revision number +- intent family +- intent code +- ACTIVE / REVOKED status +- server-owned accepting operator identity +- acceptance timestamp +- previous revision SHA-256 +- canonical revision SHA-256 + +It also asserts: + +```text +human_intent_confirmed = true +causation_proven = false + +policy_authority = false +operational_authority = false +action_authority = false +execution_authority = false +``` + +Human confirmation of meaning is not proof that the observed UI change was +caused solely by the demonstrated action. + +## OperatorLog binding + +A new or replacement ACTIVE intent can be accepted only from the exact current +ACTIVE OperatorLog revision. + +The registry rejects: + +- a stale OperatorLog revision SHA +- a retracted OperatorLog revision +- a tampered OperatorLog revision +- a missing or ambiguous source revision +- an OperatorLog revision targeting another inference + +If the OperatorLog is edited after intent acceptance, the existing accepted +intent remains intact as historical evidence. + +PhiShell labels that condition: + +```text +STALE BINDING +``` + +The operator can then append a new accepted-intent revision bound to the newer +human interpretation. + +## Append-only updates and revocation + +Intent classification changes append revisions: + +```text +r1 OPEN_NETWORK_ADAPTER_PROPERTIES + ↓ +r2 NAVIGATE_NETWORK_ADAPTER_PROPERTIES +``` + +Revocation also appends: + +```text +r2 ACTIVE + ↓ +r3 REVOKED +``` + +Nothing is deleted or rewritten. + +All updates use: + +```text +expected_current_revision_sha256 +``` + +to reject stale concurrent mutations. + +## Transport + +The Ghost-Walk sidecar exposes: + +```http +GET /api/v1/ghostwalk/accepted-intent?target= +POST /api/v1/ghostwalk/accepted-intent/revisions +``` + +An ACCEPT payload contains only: + +```json +{ + "operation": "ACCEPT", + "target_inference_receipt_sha256": "...", + "source_operator_note_revision_sha256": "...", + "intent_family": "OPEN", + "intent_code": "OPEN_NETWORK_ADAPTER_PROPERTIES", + "expected_current_revision_sha256": null +} +``` + +A REVOKE payload contains only: + +```json +{ + "operation": "REVOKE", + "target_inference_receipt_sha256": "...", + "expected_current_revision_sha256": "..." +} +``` + +The browser cannot supply: + +- `accepted_by` +- policy authority +- action authority +- execution authority + +Those fields are controlled by the governed runtime contract. + +## Effect semantics + +Reading accepted intent: + +```text +intentMutation = false +effectPerformed = false +desktopEffectPerformed = false +``` + +Appending or revoking: + +```text +intentMutation = true +effectPerformed = true +desktopEffectPerformed = false +``` + +The ledger append is a real persistent effect. + +It is not a desktop effect and does not grant execution policy. + +## PhiShell + +The OperatorLog editor now contains an Accepted Intent section showing: + +- current intent revision +- ACTIVE / REVOKED status +- canonical intent code +- intent family +- accepted-intent revision digest +- exact bound OperatorLog revision digest +- stale-binding warning + +The operator can: + +- accept the first typed intent +- append a reclassification +- revoke the current intent +- reload governed state + +## Fail-closed rules + +v0.29 rejects: + +- unknown or malformed target hashes +- stale current-intent hashes +- stale source OperatorLog hashes +- retracted human interpretation +- tampered accepted-intent history +- tampered source OperatorLog history +- mismatched intent family/code prefix +- browser-provided authority fields +- browser-provided acceptance identity +- malformed transport envelopes + +## Architectural boundary + +```text +ACCEPTED INTENT +!= +EXECUTION POLICY + +HUMAN INTENT CONFIRMED +!= +CAUSATION PROVEN + +KNOWN MEANING +!= +PERMISSION TO ACT +``` + +## Next rung + +v0.30 should introduce a separate policy-admission layer that can answer whether +an accepted intent is eligible to *request* execution under a bounded policy. + +That layer should still not perform the action itself: + +```text +accepted intent + ↓ +policy admission + ↓ +authority request + ↓ +existing governed execution path +``` diff --git a/phios/macro_accepted_intent.py b/phios/macro_accepted_intent.py new file mode 100644 index 00000000..86950a69 --- /dev/null +++ b/phios/macro_accepted_intent.py @@ -0,0 +1,632 @@ +"""Human-accepted Ghost-Walk intent classifications for Macro Runtime v0.29. + +Accepted intent is a separate append-only governance layer. It binds one typed +human declaration to an immutable transition inference and the exact active +OperatorLog revision used to interpret that transition. + +Accepted intent is not execution policy and carries no execution authority. +""" + +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_ghostwalk_operator_editor import GhostWalkOperatorEditor +from phios.macro_operator_log import ( + OperatorLogContractError, + OperatorLogRevision, + OperatorNoteStatus, +) +from phios.spine.ledger import RealityLedger + +GHOSTWALK_ACCEPTED_INTENT_SCHEMA_VERSION = ( + "phios.ghostwalk_accepted_intent_revision.v0.29" +) +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_INTENT_CODE_RE = re.compile(r"^[A-Z][A-Z0-9_]{2,127}$") + + +class GhostWalkAcceptedIntentError(ValueError): + """Raised when accepted-intent evidence or revision history is invalid.""" + + +class GhostWalkIntentFamily(StrEnum): + NAVIGATE = "NAVIGATE" + OPEN = "OPEN" + CLOSE = "CLOSE" + SELECT = "SELECT" + TOGGLE = "TOGGLE" + ENTER_TEXT = "ENTER_TEXT" + SUBMIT = "SUBMIT" + CONFIRM = "CONFIRM" + CANCEL = "CANCEL" + OTHER = "OTHER" + + +class GhostWalkAcceptedIntentStatus(StrEnum): + ACTIVE = "ACTIVE" + REVOKED = "REVOKED" + + +def _require_text( + value: object, + field: str, + *, + maximum: int = 4096, +) -> str: + if not isinstance(value, str) or not value: + raise GhostWalkAcceptedIntentError( + f"{field} must be a non-empty string" + ) + if len(value) > maximum: + raise GhostWalkAcceptedIntentError( + f"{field} exceeds {maximum} characters" + ) + if any(ord(char) < 32 for char in value): + raise GhostWalkAcceptedIntentError( + 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 GhostWalkAcceptedIntentError( + 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_bool(value: object, field: str) -> bool: + if not isinstance(value, bool): + raise GhostWalkAcceptedIntentError( + f"{field} must be Boolean" + ) + return value + + +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 GhostWalkAcceptedIntentError( + f"{field} must be an ISO-8601 timestamp" + ) from exc + if parsed.tzinfo is None: + raise GhostWalkAcceptedIntentError( + f"{field} must include a timezone" + ) + return text + + +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 GhostWalkAcceptedIntentError( + "accepted-intent 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() + + +def _require_intent_code( + family: GhostWalkIntentFamily, + value: object, +) -> str: + code = _require_text(value, "intent_code", maximum=128) + if not _INTENT_CODE_RE.fullmatch(code): + raise GhostWalkAcceptedIntentError( + "intent_code must be an uppercase symbolic identifier" + ) + if family is not GhostWalkIntentFamily.OTHER: + prefix = f"{family.value}_" + if not code.startswith(prefix): + raise GhostWalkAcceptedIntentError( + f"intent_code for {family.value} must start with {prefix}" + ) + return code + + +@dataclass(frozen=True, slots=True) +class GhostWalkAcceptedIntentRevision: + target_inference_receipt_sha256: str + source_operator_note_revision_sha256: str + revision: int + intent_family: GhostWalkIntentFamily + intent_code: str + status: GhostWalkAcceptedIntentStatus + accepted_by: str + accepted_at: str + supersedes_revision_sha256: str | None + human_intent_confirmed: bool = True + causation_proven: bool = False + policy_authority: bool = False + operational_authority: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = GHOSTWALK_ACCEPTED_INTENT_SCHEMA_VERSION + + def __post_init__(self) -> None: + if self.schema_version != GHOSTWALK_ACCEPTED_INTENT_SCHEMA_VERSION: + raise GhostWalkAcceptedIntentError( + "unsupported accepted-intent schema" + ) + _require_sha256( + self.target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + _require_sha256( + self.source_operator_note_revision_sha256, + "source_operator_note_revision_sha256", + ) + if ( + isinstance(self.revision, bool) + or not isinstance(self.revision, int) + or self.revision < 1 + ): + raise GhostWalkAcceptedIntentError( + "revision must be a positive integer" + ) + _require_intent_code(self.intent_family, self.intent_code) + _require_text(self.accepted_by, "accepted_by", maximum=512) + _require_timestamp(self.accepted_at, "accepted_at") + if self.revision == 1: + if self.supersedes_revision_sha256 is not None: + raise GhostWalkAcceptedIntentError( + "first accepted-intent revision cannot supersede history" + ) + else: + _require_sha256( + self.supersedes_revision_sha256, + "supersedes_revision_sha256", + ) + if not self.human_intent_confirmed: + raise GhostWalkAcceptedIntentError( + "accepted intent must confirm human intent" + ) + if self.causation_proven: + raise GhostWalkAcceptedIntentError( + "accepted intent cannot claim causation" + ) + if ( + self.policy_authority + or self.operational_authority + or self.action_authority + or self.execution_authority + ): + raise GhostWalkAcceptedIntentError( + "accepted intent cannot carry authority" + ) + + def body_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "target_inference_receipt_sha256": ( + self.target_inference_receipt_sha256 + ), + "source_operator_note_revision_sha256": ( + self.source_operator_note_revision_sha256 + ), + "revision": self.revision, + "intent_family": self.intent_family.value, + "intent_code": self.intent_code, + "status": self.status.value, + "accepted_by": self.accepted_by, + "accepted_at": self.accepted_at, + "supersedes_revision_sha256": ( + self.supersedes_revision_sha256 + ), + "human_intent_confirmed": self.human_intent_confirmed, + "causation_proven": self.causation_proven, + "policy_authority": self.policy_authority, + "operational_authority": self.operational_authority, + "action_authority": self.action_authority, + "execution_authority": self.execution_authority, + } + + @property + def revision_sha256(self) -> str: + return _canonical_sha256(self.body_dict()) + + def to_dict(self) -> dict[str, object]: + payload = self.body_dict() + payload["revision_sha256"] = self.revision_sha256 + return payload + + @classmethod + def from_dict( + cls, + payload: Mapping[str, object], + ) -> "GhostWalkAcceptedIntentRevision": + claimed = _require_sha256( + payload.get("revision_sha256"), + "revision_sha256", + ) + try: + family = GhostWalkIntentFamily( + _require_text( + payload.get("intent_family"), + "intent_family", + maximum=64, + ) + ) + status = GhostWalkAcceptedIntentStatus( + _require_text( + payload.get("status"), + "status", + maximum=64, + ) + ) + except ValueError as exc: + raise GhostWalkAcceptedIntentError( + "accepted-intent enum value is unsupported" + ) from exc + revision_raw = payload.get("revision") + if ( + isinstance(revision_raw, bool) + or not isinstance(revision_raw, int) + ): + raise GhostWalkAcceptedIntentError( + "revision must be an integer" + ) + item = cls( + target_inference_receipt_sha256=_require_sha256( + payload.get("target_inference_receipt_sha256"), + "target_inference_receipt_sha256", + ), + source_operator_note_revision_sha256=_require_sha256( + payload.get("source_operator_note_revision_sha256"), + "source_operator_note_revision_sha256", + ), + revision=revision_raw, + intent_family=family, + intent_code=_require_text( + payload.get("intent_code"), + "intent_code", + maximum=128, + ), + status=status, + accepted_by=_require_text( + payload.get("accepted_by"), + "accepted_by", + maximum=512, + ), + accepted_at=_require_timestamp( + payload.get("accepted_at"), + "accepted_at", + ), + supersedes_revision_sha256=_optional_sha256( + payload.get("supersedes_revision_sha256"), + "supersedes_revision_sha256", + ), + human_intent_confirmed=_require_bool( + payload.get("human_intent_confirmed"), + "human_intent_confirmed", + ), + causation_proven=_require_bool( + payload.get("causation_proven"), + "causation_proven", + ), + 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", + ), + ) + if item.revision_sha256 != claimed: + raise GhostWalkAcceptedIntentError( + "accepted-intent revision hash mismatch" + ) + return item + + +class GhostWalkAcceptedIntentRegistry: + """Append-only typed human intent acceptance, separate from policy.""" + + def __init__( + self, + *, + ledger: RealityLedger, + accepted_by: str, + ) -> None: + if not isinstance(ledger, RealityLedger): + raise GhostWalkAcceptedIntentError( + "ledger must be a RealityLedger" + ) + self._ledger = ledger + self.accepted_by = _require_text( + accepted_by, + "accepted_by", + maximum=512, + ) + self._lock = threading.RLock() + self._operator_editor = GhostWalkOperatorEditor( + ledger=ledger, + author_id=accepted_by, + ) + + def current( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAcceptedIntentRevision | None: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + with self._lock: + chain = self._load_chain(target) + return chain[-1] if chain else None + + def accept( + self, + *, + target_inference_receipt_sha256: str, + source_operator_note_revision_sha256: str, + intent_family: GhostWalkIntentFamily, + intent_code: str, + expected_current_revision_sha256: str | None, + accepted_at: str | None = None, + ) -> GhostWalkAcceptedIntentRevision: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + source_note = _require_sha256( + source_operator_note_revision_sha256, + "source_operator_note_revision_sha256", + ) + code = _require_intent_code(intent_family, intent_code) + timestamp = _require_timestamp( + _utc_now() if accepted_at is None else accepted_at, + "accepted_at", + ) + + with self._lock: + note = self._operator_editor.view( + target_inference_receipt_sha256=target + ) + if note.status is not OperatorNoteStatus.ACTIVE: + raise GhostWalkAcceptedIntentError( + "accepted intent requires an ACTIVE operator note" + ) + if note.revision_sha256 != source_note: + raise GhostWalkAcceptedIntentError( + "operator note revision changed before intent acceptance" + ) + + chain = self._load_chain(target) + current = chain[-1] if chain else None + if current is None: + if expected_current_revision_sha256 is not None: + raise GhostWalkAcceptedIntentError( + "first accepted intent cannot expect prior history" + ) + revision = 1 + previous = None + else: + expected = _require_sha256( + expected_current_revision_sha256, + "expected_current_revision_sha256", + ) + if current.revision_sha256 != expected: + raise GhostWalkAcceptedIntentError( + "accepted-intent revision changed before update" + ) + revision = current.revision + 1 + previous = current.revision_sha256 + + item = GhostWalkAcceptedIntentRevision( + target_inference_receipt_sha256=target, + source_operator_note_revision_sha256=source_note, + revision=revision, + intent_family=intent_family, + intent_code=code, + status=GhostWalkAcceptedIntentStatus.ACTIVE, + accepted_by=self.accepted_by, + accepted_at=timestamp, + supersedes_revision_sha256=previous, + ) + self._ledger.append_ghostwalk_accepted_intent_revision(item) + return item + + def revoke( + self, + *, + target_inference_receipt_sha256: str, + expected_current_revision_sha256: str, + accepted_at: str | None = None, + ) -> GhostWalkAcceptedIntentRevision: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + expected = _require_sha256( + expected_current_revision_sha256, + "expected_current_revision_sha256", + ) + timestamp = _require_timestamp( + _utc_now() if accepted_at is None else accepted_at, + "accepted_at", + ) + + with self._lock: + chain = self._load_chain(target) + if not chain: + raise GhostWalkAcceptedIntentError( + "accepted intent does not exist" + ) + current = chain[-1] + if current.revision_sha256 != expected: + raise GhostWalkAcceptedIntentError( + "accepted-intent revision changed before revoke" + ) + if current.status is GhostWalkAcceptedIntentStatus.REVOKED: + raise GhostWalkAcceptedIntentError( + "accepted intent is already revoked" + ) + item = GhostWalkAcceptedIntentRevision( + target_inference_receipt_sha256=target, + source_operator_note_revision_sha256=( + current.source_operator_note_revision_sha256 + ), + revision=current.revision + 1, + intent_family=current.intent_family, + intent_code=current.intent_code, + status=GhostWalkAcceptedIntentStatus.REVOKED, + accepted_by=self.accepted_by, + accepted_at=timestamp, + supersedes_revision_sha256=current.revision_sha256, + ) + self._ledger.append_ghostwalk_accepted_intent_revision(item) + return item + + def _load_chain( + self, + target_sha256: str, + ) -> list[GhostWalkAcceptedIntentRevision]: + rows = self._ledger.ghostwalk_accepted_intent_revisions( + target_inference_receipt_sha256=target_sha256 + ) + revisions = [ + GhostWalkAcceptedIntentRevision.from_dict(row) + for row in rows + ] + previous: GhostWalkAcceptedIntentRevision | None = None + for expected_revision, item in enumerate(revisions, start=1): + if item.target_inference_receipt_sha256 != target_sha256: + raise GhostWalkAcceptedIntentError( + "accepted-intent target changed across revisions" + ) + if item.revision != expected_revision: + raise GhostWalkAcceptedIntentError( + "accepted-intent revisions are not contiguous" + ) + self._validate_source_operator_note(item) + if previous is not None: + if ( + item.supersedes_revision_sha256 + != previous.revision_sha256 + ): + raise GhostWalkAcceptedIntentError( + "accepted-intent revision chain mismatch" + ) + previous = item + return revisions + + def _validate_source_operator_note( + self, + intent: GhostWalkAcceptedIntentRevision, + ) -> None: + all_rows = self._ledger.operator_log_revisions() + matches = [ + row + for row in all_rows + if row.get("revision_sha256") + == intent.source_operator_note_revision_sha256 + ] + if len(matches) != 1: + raise GhostWalkAcceptedIntentError( + "accepted intent source OperatorLog revision is missing or ambiguous" + ) + try: + revision = OperatorLogRevision.from_dict(matches[0]) + except OperatorLogContractError as exc: + raise GhostWalkAcceptedIntentError( + "accepted intent source OperatorLog revision is invalid" + ) from exc + if ( + revision.target_sha256 + != intent.target_inference_receipt_sha256 + ): + raise GhostWalkAcceptedIntentError( + "accepted intent source OperatorLog target mismatch" + ) + + prefix_rows: list[dict[str, object]] = [] + for row in all_rows: + raw_revision = row.get("revision") + if ( + row.get("note_id") == revision.note_id + and isinstance(raw_revision, int) + and not isinstance(raw_revision, bool) + and raw_revision <= revision.revision + ): + prefix_rows.append(row) + parsed: list[OperatorLogRevision] = [] + try: + parsed = [ + OperatorLogRevision.from_dict(row) + for row in prefix_rows + ] + except OperatorLogContractError as exc: + raise GhostWalkAcceptedIntentError( + "accepted intent source OperatorLog prefix is invalid" + ) from exc + + previous: OperatorLogRevision | None = None + for expected_revision, item in enumerate(parsed, start=1): + if item.revision != expected_revision: + raise GhostWalkAcceptedIntentError( + "accepted intent source OperatorLog revisions are not contiguous" + ) + if item.target_sha256 != revision.target_sha256: + raise GhostWalkAcceptedIntentError( + "accepted intent source OperatorLog target changed" + ) + if previous is not None and ( + item.supersedes_revision_sha256 + != previous.revision_sha256 + ): + raise GhostWalkAcceptedIntentError( + "accepted intent source OperatorLog chain mismatch" + ) + previous = item + + if not parsed or parsed[-1].revision_sha256 != revision.revision_sha256: + raise GhostWalkAcceptedIntentError( + "accepted intent source OperatorLog prefix is incomplete" + ) diff --git a/phios/macro_ghostwalk_control_server.py b/phios/macro_ghostwalk_control_server.py index 20fb767f..c6a77a35 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_accepted_intent import ( + GhostWalkAcceptedIntentError, + GhostWalkAcceptedIntentRegistry, + GhostWalkAcceptedIntentRevision, + GhostWalkIntentFamily, +) from phios.macro_ghostwalk_control_surface import ( GhostWalkControlAction, GhostWalkControlOutcome, @@ -44,6 +50,10 @@ "phios.ghostwalk-operator-log-transport.v0.28" ) OPERATOR_TRANSPORT_IDENTITY = "phios-ghostwalk-operator-editor" +ACCEPTED_INTENT_TRANSPORT_SCHEMA_VERSION = ( + "phios.ghostwalk-accepted-intent-transport.v0.29" +) +ACCEPTED_INTENT_TRANSPORT_IDENTITY = "phios-ghostwalk-accepted-intent" DEFAULT_HOST_ID = "ghostwalk-host:local" DEFAULT_BASELINE_SERVICE_ID = "ghostwalk-baseline:local" DEFAULT_COORDINATOR_ID = "ghostwalk-coordinator:local" @@ -85,6 +95,33 @@ def edit( ) -> GhostWalkOperatorEditOutcome: ... +class GhostWalkAcceptedIntentPort(Protocol): + def current( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAcceptedIntentRevision | None: ... + + def accept( + self, + *, + target_inference_receipt_sha256: str, + source_operator_note_revision_sha256: str, + intent_family: GhostWalkIntentFamily, + intent_code: str, + expected_current_revision_sha256: str | None, + accepted_at: str | None = None, + ) -> GhostWalkAcceptedIntentRevision: ... + + def revoke( + self, + *, + target_inference_receipt_sha256: str, + expected_current_revision_sha256: str, + accepted_at: str | None = None, + ) -> GhostWalkAcceptedIntentRevision: ... + + def _utc_now() -> str: return datetime.now(UTC).isoformat() @@ -229,6 +266,167 @@ def parse_operator_edit_payload( return target, expected, body, status +def _accepted_intent_transport_base( + *, + effect_performed: bool, +) -> dict[str, object]: + return { + "transportSchemaVersion": ( + ACCEPTED_INTENT_TRANSPORT_SCHEMA_VERSION + ), + "transport": "loopback-http", + "transportIdentity": ACCEPTED_INTENT_TRANSPORT_IDENTITY, + "localOnly": True, + "intentMutation": effect_performed, + "desktopEffectPerformed": False, + "policyAuthority": False, + "operationalAuthority": False, + "actionAuthority": False, + "executionAuthority": False, + "effectPerformed": effect_performed, + } + + +def accepted_intent_envelope( + registry: GhostWalkAcceptedIntentPort, + *, + target_inference_receipt_sha256: str, +) -> dict[str, object] | None: + current = registry.current( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + if current is None: + return None + payload = _accepted_intent_transport_base(effect_performed=False) + payload.update( + { + "servedAt": _utc_now(), + "intent": current.to_dict(), + } + ) + return payload + + +def accepted_intent_mutation_envelope( + revision: GhostWalkAcceptedIntentRevision, +) -> dict[str, object]: + payload = _accepted_intent_transport_base(effect_performed=True) + payload.update( + { + "servedAt": _utc_now(), + "intent": revision.to_dict(), + } + ) + return payload + + +def parse_accepted_intent_payload( + payload: object, +) -> tuple[ + str, + str, + str | None, + GhostWalkIntentFamily | None, + str | None, + str | None, +]: + if not isinstance(payload, Mapping): + raise GhostWalkControlBridgeError( + "accepted-intent body must be an object" + ) + operation = payload.get("operation") + if operation == "ACCEPT": + expected_keys = { + "operation", + "target_inference_receipt_sha256", + "source_operator_note_revision_sha256", + "intent_family", + "intent_code", + "expected_current_revision_sha256", + } + if set(payload) != expected_keys: + raise GhostWalkControlBridgeError( + "accepted-intent ACCEPT fields do not match contract" + ) + target = payload.get("target_inference_receipt_sha256") + source_note = payload.get( + "source_operator_note_revision_sha256" + ) + expected = payload.get("expected_current_revision_sha256") + raw_family = payload.get("intent_family") + intent_code = payload.get("intent_code") + if ( + not isinstance(target, str) + or re.fullmatch(r"[0-9a-f]{64}", target) is None + or not isinstance(source_note, str) + or re.fullmatch(r"[0-9a-f]{64}", source_note) is None + or ( + expected is not None + and ( + not isinstance(expected, str) + or re.fullmatch(r"[0-9a-f]{64}", expected) is None + ) + ) + or not isinstance(raw_family, str) + or not isinstance(intent_code, str) + ): + raise GhostWalkControlBridgeError( + "accepted-intent ACCEPT values are invalid" + ) + try: + family = GhostWalkIntentFamily(raw_family) + except ValueError as exc: + raise GhostWalkControlBridgeError( + "accepted-intent family is unsupported" + ) from exc + if ( + not intent_code + or len(intent_code) > 128 + or re.fullmatch(r"[A-Z][A-Z0-9_]{2,127}", intent_code) + is None + ): + raise GhostWalkControlBridgeError( + "accepted-intent code is invalid" + ) + return ( + operation, + target, + expected, + family, + intent_code, + source_note, + ) + + if operation == "REVOKE": + expected_keys = { + "operation", + "target_inference_receipt_sha256", + "expected_current_revision_sha256", + } + if set(payload) != expected_keys: + raise GhostWalkControlBridgeError( + "accepted-intent REVOKE fields do not match contract" + ) + target = payload.get("target_inference_receipt_sha256") + expected = payload.get("expected_current_revision_sha256") + if ( + not isinstance(target, str) + or re.fullmatch(r"[0-9a-f]{64}", target) is None + or not isinstance(expected, str) + or re.fullmatch(r"[0-9a-f]{64}", expected) is None + ): + raise GhostWalkControlBridgeError( + "accepted-intent REVOKE values are invalid" + ) + return operation, target, expected, None, None, None + + raise GhostWalkControlBridgeError( + "accepted-intent operation is unsupported" + ) + + def status_envelope(surface: GhostWalkSurface) -> dict[str, object]: payload = _transport_base() payload.update( @@ -366,6 +564,15 @@ def _operator_error( body.update({"error": code, "servedAt": _utc_now()}) self._json(status, body) + def _accepted_intent_error( + self, + status: HTTPStatus, + code: str, + ) -> None: + body = _accepted_intent_transport_base(effect_performed=False) + body.update({"error": code, "servedAt": _utc_now()}) + self._json(status, body) + def _read_json( self, *, @@ -401,6 +608,57 @@ def _read_json( def do_GET(self) -> None: parsed = urlsplit(self.path) + if parsed.path == "/api/v1/ghostwalk/accepted-intent": + if self.server.accepted_intents is None: + self._accepted_intent_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_accepted_intent_unavailable", + ) + return + try: + query = parse_qs( + parsed.query, + keep_blank_values=True, + strict_parsing=True, + ) + except ValueError: + self._accepted_intent_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_accepted_intent_request", + ) + 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._accepted_intent_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_accepted_intent_request", + ) + return + try: + envelope = accepted_intent_envelope( + self.server.accepted_intents, + target_inference_receipt_sha256=targets[0], + ) + except GhostWalkAcceptedIntentError: + self._accepted_intent_error( + HTTPStatus.CONFLICT, + "ghostwalk_accepted_intent_invalid_history", + ) + return + if envelope is None: + self._accepted_intent_error( + HTTPStatus.NOT_FOUND, + "ghostwalk_accepted_intent_not_found", + ) + return + self._json(HTTPStatus.OK, envelope) + return + if parsed.path == "/api/v1/ghostwalk/operator-log": if self.server.editor is None: self._operator_error( @@ -461,6 +719,83 @@ def do_GET(self) -> None: def do_POST(self) -> None: parsed = urlsplit(self.path) + if parsed.path == "/api/v1/ghostwalk/accepted-intent/revisions": + if parsed.query or parsed.fragment: + self._accepted_intent_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_accepted_intent_mutation", + ) + return + if self.server.accepted_intents is None: + self._accepted_intent_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_accepted_intent_unavailable", + ) + return + try: + ( + operation, + target, + expected, + family, + intent_code, + source_note, + ) = parse_accepted_intent_payload(self._read_json()) + except GhostWalkControlBridgeError: + self._accepted_intent_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_accepted_intent_mutation", + ) + return + + try: + if operation == "ACCEPT": + if ( + family is None + or intent_code is None + or source_note is None + ): + raise GhostWalkAcceptedIntentError( + "accepted-intent ACCEPT parse was incomplete" + ) + revision = self.server.accepted_intents.accept( + target_inference_receipt_sha256=target, + source_operator_note_revision_sha256=source_note, + intent_family=family, + intent_code=intent_code, + expected_current_revision_sha256=expected, + ) + else: + if expected is None: + raise GhostWalkAcceptedIntentError( + "accepted-intent REVOKE parse was incomplete" + ) + revision = self.server.accepted_intents.revoke( + target_inference_receipt_sha256=target, + expected_current_revision_sha256=expected, + ) + except GhostWalkAcceptedIntentError as exc: + text = str(exc) + conflict = ( + "changed before" in text + or "prior history" in text + ) + self._accepted_intent_error( + HTTPStatus.CONFLICT if conflict else HTTPStatus.BAD_REQUEST, + ( + "ghostwalk_accepted_intent_conflict" + if conflict + else "ghostwalk_accepted_intent_rejected" + ), + ) + return + + self._json( + HTTPStatus.OK, + accepted_intent_mutation_envelope(revision), + ) + return + if parsed.path == "/api/v1/ghostwalk/operator-log/revisions": if parsed.query or parsed.fragment: self._operator_error( @@ -552,6 +887,7 @@ def __init__( *, surface: GhostWalkSurface, editor: GhostWalkOperatorEditorPort | None = None, + accepted_intents: GhostWalkAcceptedIntentPort | None = None, stop_callback: Callable[[], object] | None = None, ) -> None: if address[0] != LOOPBACK_HOST: @@ -560,6 +896,7 @@ def __init__( ) self.surface = surface self.editor = editor + self.accepted_intents = accepted_intents self._stop_callback = stop_callback super().__init__(address, GhostWalkControlHandler) @@ -650,10 +987,19 @@ def main() -> None: ), author_id=DEFAULT_OPERATOR_AUTHOR_ID, ) + accepted_intents = GhostWalkAcceptedIntentRegistry( + ledger=RealityLedger( + args.state_root.expanduser() + / "ledger" + / "receipts.jsonl" + ), + accepted_by=DEFAULT_OPERATOR_AUTHOR_ID, + ) server = GhostWalkControlServer( (LOOPBACK_HOST, args.port), surface=surface, editor=editor, + accepted_intents=accepted_intents, stop_callback=host.stop, ) diff --git a/phios/spine/ledger.py b/phios/spine/ledger.py index ec6e8abe..5f6d6fb2 100644 --- a/phios/spine/ledger.py +++ b/phios/spine/ledger.py @@ -30,6 +30,7 @@ from phios.macro_interaction_guard import InteractionGuardReceipt from phios.macro_journal import MacroRunJournalEntry, MacroRunResumeReceipt from phios.macro_operator_log import OperatorLogRevision + from phios.macro_accepted_intent import GhostWalkAcceptedIntentRevision from phios.macro_post_action_verification import ( PostActionVerificationReceipt, ) @@ -479,6 +480,48 @@ def operator_log_revisions( return rows return [row for row in rows if row.get("note_id") == note_id] + def append_ghostwalk_accepted_intent_revision( + self, + revision: "GhostWalkAcceptedIntentRevision", + ) -> None: + """Append one immutable Ghost-Walk accepted-intent revision.""" + + path = ( + self.path.parent + / "ghostwalk-accepted-intent-revisions.jsonl" + ) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write( + json.dumps(revision.to_dict(), sort_keys=True) + "\n" + ) + + def ghostwalk_accepted_intent_revisions( + self, + *, + target_inference_receipt_sha256: str | None = None, + ) -> list[dict[str, object]]: + """Return append-order Ghost-Walk accepted-intent revisions.""" + + path = ( + self.path.parent + / "ghostwalk-accepted-intent-revisions.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", diff --git a/phishell/host/ghostWalkAcceptedIntentLocalTransport.test.mjs b/phishell/host/ghostWalkAcceptedIntentLocalTransport.test.mjs new file mode 100644 index 00000000..3c4330d2 --- /dev/null +++ b/phishell/host/ghostWalkAcceptedIntentLocalTransport.test.mjs @@ -0,0 +1,159 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { createLocalObservationServer } from "./localTransport.mjs"; + +const intent = { + schema_version: "phios.ghostwalk_accepted_intent_revision.v0.29", + target_inference_receipt_sha256: "a".repeat(64), + source_operator_note_revision_sha256: "b".repeat(64), + revision: 1, + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + status: "ACTIVE", + accepted_by: "operator:local", + accepted_at: "2026-09-27T06:55:00.000Z", + supersedes_revision_sha256: null, + human_intent_confirmed: true, + causation_proven: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + revision_sha256: "c".repeat(64), +}; + +const readEnvelope = { + transportSchemaVersion: "phios.ghostwalk-accepted-intent-transport.v0.29", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-accepted-intent", + localOnly: true, + intentMutation: false, + desktopEffectPerformed: false, + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T06:55:00.000Z", + intent, +}; + +const writeEnvelope = { + ...readEnvelope, + intentMutation: true, + effectPerformed: true, +}; + +test("local transport distinguishes no accepted intent", async () => { + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkAcceptedIntentFetcher: async () => ({ kind: "none" }), + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/accepted-intent?target=${"a".repeat(64)}`, + ); + assert.equal(response.status, 404); + } finally { + await transport.close(); + } +}); + +test("local transport proxies accepted intent read", async () => { + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkAcceptedIntentFetcher: async () => ({ + kind: "found", + envelope: readEnvelope, + }), + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/accepted-intent?target=${"a".repeat(64)}`, + ); + assert.equal(response.status, 200); + const payload = await response.json(); + assert.equal(payload.intent.intent_code, "OPEN_NETWORK_ADAPTER_PROPERTIES"); + assert.equal(payload.policyAuthority, false); + } finally { + await transport.close(); + } +}); + +test("local transport proxies intent acceptance without policy authority", async () => { + const seen = []; + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkAcceptedIntentMutator: async (payload) => { + seen.push(payload); + return { kind: "applied", envelope: writeEnvelope }; + }, + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/accepted-intent/revisions`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + operation: "ACCEPT", + target_inference_receipt_sha256: "a".repeat(64), + source_operator_note_revision_sha256: "b".repeat(64), + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256: null, + }), + }, + ); + assert.equal(response.status, 200); + const payload = await response.json(); + assert.equal(payload.effectPerformed, true); + assert.equal(payload.desktopEffectPerformed, false); + assert.equal(payload.policyAuthority, false); + assert.equal(seen.length, 1); + } finally { + await transport.close(); + } +}); + +test("local transport rejects browser policy authority injection", async () => { + let called = false; + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkAcceptedIntentMutator: async () => { + called = true; + return null; + }, + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/accepted-intent/revisions`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + operation: "ACCEPT", + target_inference_receipt_sha256: "a".repeat(64), + source_operator_note_revision_sha256: "b".repeat(64), + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256: null, + policyAuthority: true, + }), + }, + ); + assert.equal(response.status, 400); + assert.equal(called, false); + } finally { + await transport.close(); + } +}); diff --git a/phishell/host/ghostWalkAcceptedIntentProxy.mjs b/phishell/host/ghostWalkAcceptedIntentProxy.mjs new file mode 100644 index 00000000..dba9e003 --- /dev/null +++ b/phishell/host/ghostWalkAcceptedIntentProxy.mjs @@ -0,0 +1,233 @@ +import { ghostWalkSidecarPort, GHOSTWALK_HOST } from "./ghostWalkControlProxy.mjs"; + +const SHA256 = /^[0-9a-f]{64}$/; +const INTENT_CODE = /^[A-Z][A-Z0-9_]{2,127}$/; +const FAMILIES = new Set([ + "NAVIGATE", + "OPEN", + "CLOSE", + "SELECT", + "TOGGLE", + "ENTER_TEXT", + "SUBMIT", + "CONFIRM", + "CANCEL", + "OTHER", +]); +const STATUSES = new Set(["ACTIVE", "REVOKED"]); + +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 integer(value, minimum = 1) { + return Number.isInteger(value) && value >= minimum; +} + +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 validateGhostWalkAcceptedIntent(value) { + if (!zeroSnakeAuthority(value)) return false; + if ( + value.schema_version !== "phios.ghostwalk_accepted_intent_revision.v0.29" || + !sha(value.target_inference_receipt_sha256) || + !sha(value.source_operator_note_revision_sha256) || + !integer(value.revision) || + !FAMILIES.has(value.intent_family) || + !INTENT_CODE.test(String(value.intent_code)) || + !STATUSES.has(value.status) || + !boundedString(value.accepted_by) || + !timestamp(value.accepted_at) || + !nullableSha(value.supersedes_revision_sha256) || + value.human_intent_confirmed !== true || + value.causation_proven !== false || + !sha(value.revision_sha256) + ) { + return false; + } + + if (value.intent_family !== "OTHER") { + return String(value.intent_code).startsWith(`${value.intent_family}_`); + } + return true; +} + +function validEnvelope(value, mutated) { + return ( + zeroTransportAuthority(value) && + value.transportSchemaVersion === "phios.ghostwalk-accepted-intent-transport.v0.29" && + value.transport === "loopback-http" && + value.transportIdentity === "phios-ghostwalk-accepted-intent" && + value.localOnly === true && + value.intentMutation === mutated && + value.desktopEffectPerformed === false && + value.effectPerformed === mutated && + timestamp(value.servedAt) + ); +} + +export function validateGhostWalkAcceptedIntentEnvelope(value, { mutated }) { + return ( + validEnvelope(value, mutated) && + validateGhostWalkAcceptedIntent(value.intent) + ); +} + +export function validateGhostWalkAcceptedIntentMutationPayload(value) { + if (!record(value)) return false; + if (value.operation === "ACCEPT") { + const keys = Object.keys(value).sort(); + const expected = [ + "expected_current_revision_sha256", + "intent_code", + "intent_family", + "operation", + "source_operator_note_revision_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.source_operator_note_revision_sha256) && + (value.expected_current_revision_sha256 === null || + sha(value.expected_current_revision_sha256)) && + FAMILIES.has(value.intent_family) && + typeof value.intent_code === "string" && + INTENT_CODE.test(value.intent_code) && + ( + value.intent_family === "OTHER" || + value.intent_code.startsWith(`${value.intent_family}_`) + ) + ); + } + + if (value.operation === "REVOKE") { + const keys = Object.keys(value).sort(); + const expected = [ + "expected_current_revision_sha256", + "operation", + "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_current_revision_sha256) + ); + } + + return false; +} + +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 fetchGhostWalkAcceptedIntent(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/accepted-intent?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + headers: { accept: "application/json" }, + }, + fetcher, + timeoutMs, + ); + if (!response) return null; + if (response.status === 404) return { kind: "none" }; + if (!response.ok) return null; + + try { + const payload = await response.json(); + if (!validateGhostWalkAcceptedIntentEnvelope(payload, { mutated: false })) { + return null; + } + return { kind: "found", envelope: payload }; + } catch { + return null; + } +} + +export async function applyGhostWalkAcceptedIntentMutation(payload, { + fetcher = globalThis.fetch.bind(globalThis), + port = ghostWalkSidecarPort(), + timeoutMs = 2500, +} = {}) { + if (!validateGhostWalkAcceptedIntentMutationPayload(payload)) return null; + const response = await request( + `http://${GHOSTWALK_HOST}:${port}/api/v1/ghostwalk/accepted-intent/revisions`, + { + 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(); + if (!validateGhostWalkAcceptedIntentEnvelope(result, { mutated: true })) { + return null; + } + return { kind: "applied", envelope: result }; + } catch { + return null; + } +} diff --git a/phishell/host/ghostWalkAcceptedIntentProxy.test.mjs b/phishell/host/ghostWalkAcceptedIntentProxy.test.mjs new file mode 100644 index 00000000..8c8095c8 --- /dev/null +++ b/phishell/host/ghostWalkAcceptedIntentProxy.test.mjs @@ -0,0 +1,151 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + applyGhostWalkAcceptedIntentMutation, + fetchGhostWalkAcceptedIntent, + validateGhostWalkAcceptedIntentEnvelope, + validateGhostWalkAcceptedIntentMutationPayload, +} from "./ghostWalkAcceptedIntentProxy.mjs"; + +const intent = { + schema_version: "phios.ghostwalk_accepted_intent_revision.v0.29", + target_inference_receipt_sha256: "a".repeat(64), + source_operator_note_revision_sha256: "b".repeat(64), + revision: 1, + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + status: "ACTIVE", + accepted_by: "operator:local", + accepted_at: "2026-09-27T06:55:00.000Z", + supersedes_revision_sha256: null, + human_intent_confirmed: true, + causation_proven: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + revision_sha256: "c".repeat(64), +}; + +const readEnvelope = { + transportSchemaVersion: "phios.ghostwalk-accepted-intent-transport.v0.29", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-accepted-intent", + localOnly: true, + intentMutation: false, + desktopEffectPerformed: false, + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T06:55:00.000Z", + intent, +}; + +const writeEnvelope = { + ...readEnvelope, + intentMutation: true, + effectPerformed: true, +}; + +test("validates typed accepted intent without policy authority", () => { + assert.equal( + validateGhostWalkAcceptedIntentEnvelope(readEnvelope, { mutated: false }), + true, + ); + assert.equal( + validateGhostWalkAcceptedIntentEnvelope({ + ...readEnvelope, + policyAuthority: true, + }, { mutated: false }), + false, + ); +}); + +test("rejects mismatched family and intent code", () => { + assert.equal( + validateGhostWalkAcceptedIntentEnvelope({ + ...readEnvelope, + intent: { + ...intent, + intent_code: "TOGGLE_NETWORK_ADAPTER_PROPERTIES", + }, + }, { mutated: false }), + false, + ); +}); + +test("accept payload excludes authority and accepted-by fields", () => { + const payload = { + operation: "ACCEPT", + target_inference_receipt_sha256: "a".repeat(64), + source_operator_note_revision_sha256: "b".repeat(64), + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256: null, + }; + assert.equal(validateGhostWalkAcceptedIntentMutationPayload(payload), true); + assert.equal( + validateGhostWalkAcceptedIntentMutationPayload({ + ...payload, + accepted_by: "browser:fake", + }), + false, + ); +}); + +test("read distinguishes no accepted intent from unavailable sidecar", async () => { + const missingFetcher = async () => ({ + status: 404, + ok: false, + }); + assert.deepEqual( + await fetchGhostWalkAcceptedIntent("a".repeat(64), { + fetcher: missingFetcher, + port: 3973, + }), + { kind: "none" }, + ); + + const foundFetcher = async () => ({ + status: 200, + ok: true, + async json() { + return readEnvelope; + }, + }); + const found = await fetchGhostWalkAcceptedIntent("a".repeat(64), { + fetcher: foundFetcher, + port: 3973, + }); + assert.equal(found?.kind, "found"); +}); + +test("write validates persistent intent mutation envelope", async () => { + const fetcher = async (_url, init) => { + const body = JSON.parse(init.body); + assert.equal("policyAuthority" in body, false); + assert.equal("accepted_by" in body, false); + return { + status: 200, + ok: true, + async json() { + return writeEnvelope; + }, + }; + }; + const result = await applyGhostWalkAcceptedIntentMutation( + { + operation: "ACCEPT", + target_inference_receipt_sha256: "a".repeat(64), + source_operator_note_revision_sha256: "b".repeat(64), + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256: null, + }, + { fetcher, port: 3973 }, + ); + assert.equal(result?.kind, "applied"); +}); diff --git a/phishell/host/localTransport.mjs b/phishell/host/localTransport.mjs index c61ad37e..309f5e03 100644 --- a/phishell/host/localTransport.mjs +++ b/phishell/host/localTransport.mjs @@ -27,6 +27,11 @@ import { fetchGhostWalkOperatorNote, validateGhostWalkOperatorEditPayload, } from "./ghostWalkOperatorLogProxy.mjs"; +import { + applyGhostWalkAcceptedIntentMutation, + fetchGhostWalkAcceptedIntent, + validateGhostWalkAcceptedIntentMutationPayload, +} from "./ghostWalkAcceptedIntentProxy.mjs"; import { createPersistRequest, fetchBrokerHealth, @@ -125,6 +130,8 @@ export function createLocalObservationServer({ ghostWalkActionApplier = applyGhostWalkAction, ghostWalkOperatorNoteFetcher = fetchGhostWalkOperatorNote, ghostWalkOperatorEditApplier = applyGhostWalkOperatorEdit, + ghostWalkAcceptedIntentFetcher = fetchGhostWalkAcceptedIntent, + ghostWalkAcceptedIntentMutator = applyGhostWalkAcceptedIntentMutation, } = {}) { if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new Error("local observation port must be an integer between 0 and 65535"); @@ -134,6 +141,65 @@ export function createLocalObservationServer({ try { const url = new URL(request.url ?? "/", `http://${LOOPBACK_HOST}`); + if ( + request.method === "POST" && + url.pathname === "/api/v1/ghostwalk/accepted-intent/revisions" + ) { + let payload; + try { + payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); + } catch { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_accepted_intent_body", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + if (!validateGhostWalkAcceptedIntentMutationPayload(payload)) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_accepted_intent_request", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + const result = await ghostWalkAcceptedIntentMutator(payload); + if (result?.kind === "conflict") { + jsonResponse(response, 409, { + error: "ghostwalk_accepted_intent_conflict", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "applied") { + jsonResponse(response, 503, { + error: "ghostwalk_accepted_intent_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/operator-log/revisions" @@ -320,6 +386,54 @@ export function createLocalObservationServer({ return; } + if (url.pathname === "/api/v1/ghostwalk/accepted-intent") { + 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_accepted_intent_request", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + const result = await ghostWalkAcceptedIntentFetcher(target); + if (result?.kind === "none") { + jsonResponse(response, 404, { + error: "ghostwalk_accepted_intent_not_found", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "found") { + jsonResponse(response, 503, { + error: "ghostwalk_accepted_intent_unavailable", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + jsonResponse(response, 200, result.envelope); + return; + } + if (url.pathname === "/api/v1/ghostwalk/operator-log") { const keys = [...url.searchParams.keys()]; const target = url.searchParams.get("target"); diff --git a/phishell/src/components/GhostWalkAcceptedIntentEditor.tsx b/phishell/src/components/GhostWalkAcceptedIntentEditor.tsx new file mode 100644 index 00000000..a343d6c1 --- /dev/null +++ b/phishell/src/components/GhostWalkAcceptedIntentEditor.tsx @@ -0,0 +1,226 @@ +import { useCallback, useEffect, useState } from "react"; +import { + GHOSTWALK_INTENT_FAMILIES, + ghostWalkAcceptedIntentClient, + type GhostWalkAcceptedIntent, + type GhostWalkIntentFamily, +} from "../ghostwalk/acceptedIntent"; + +function shortHash(value: string) { + return `${value.slice(0, 10)}…`; +} + +export function GhostWalkAcceptedIntentEditor({ + targetSha256, + sourceOperatorNoteRevisionSha256, + operatorNoteActive, +}: { + targetSha256: string; + sourceOperatorNoteRevisionSha256: string; + operatorNoteActive: boolean; +}) { + const [current, setCurrent] = useState(null); + const [family, setFamily] = useState("OPEN"); + const [code, setCode] = useState("OPEN_"); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); + + const load = useCallback(async () => { + setLoading(true); + try { + const result = await ghostWalkAcceptedIntentClient.read(targetSha256); + if (result.kind === "found") { + setCurrent(result.intent); + setFamily(result.intent.intent_family); + setCode(result.intent.intent_code); + setMessage(null); + } else if (result.kind === "none") { + setCurrent(null); + setMessage(null); + } else { + setMessage("Accepted-intent registry is unavailable or returned invalid evidence."); + } + } finally { + setLoading(false); + } + }, [targetSha256]); + + useEffect(() => { + void load(); + }, [load]); + + const updateFamily = useCallback((next: GhostWalkIntentFamily) => { + setFamily(next); + if (next === "OTHER") { + setCode("CUSTOM_INTENT"); + } else { + setCode(`${next}_`); + } + }, []); + + const accept = useCallback(async () => { + if (!operatorNoteActive || !code.trim()) return; + setBusy(true); + setMessage(null); + try { + const result = await ghostWalkAcceptedIntentClient.accept({ + targetSha256, + sourceOperatorNoteRevisionSha256, + family, + code: code.trim().toUpperCase(), + expectedCurrentRevisionSha256: current?.revision_sha256 ?? null, + }); + if (result.kind === "conflict") { + setMessage( + "Intent conflict: the accepted-intent record changed after you loaded it. Reload before saving.", + ); + return; + } + if (result.kind === "unavailable") { + setMessage( + "Intent acceptance was rejected or could not be validated. The current OperatorLog revision may have changed.", + ); + return; + } + setCurrent(result.intent); + setFamily(result.intent.intent_family); + setCode(result.intent.intent_code); + setMessage( + `Accepted intent revision ${result.intent.revision}: ${result.intent.intent_code}. No execution policy was granted.`, + ); + } finally { + setBusy(false); + } + }, [ + code, + current, + family, + operatorNoteActive, + sourceOperatorNoteRevisionSha256, + targetSha256, + ]); + + const revoke = useCallback(async () => { + if (!current || current.status !== "ACTIVE") return; + setBusy(true); + setMessage(null); + try { + const result = await ghostWalkAcceptedIntentClient.revoke({ + targetSha256, + expectedCurrentRevisionSha256: current.revision_sha256, + }); + if (result.kind === "conflict") { + setMessage("Intent conflict: reload the latest accepted-intent revision."); + return; + } + if (result.kind === "unavailable") { + setMessage("Intent revocation was rejected or could not be validated."); + return; + } + setCurrent(result.intent); + setMessage( + `Accepted intent revoked in revision ${result.intent.revision}. Prior history remains intact.`, + ); + } finally { + setBusy(false); + } + }, [current, targetSha256]); + + return ( +
+
+
+ ACCEPTED INTENT + {current ? `r${current.revision} · ${current.status}` : "UNCLASSIFIED"} +
+ POLICY AUTH 0 +
+ + {loading ? ( +
Reading accepted-intent history…
+ ) : ( + <> + {current && ( +
+ {current.intent_code} + + {current.intent_family} · {shortHash(current.revision_sha256)} + + + bound to OperatorLog {shortHash(current.source_operator_note_revision_sha256)} + +
+ )} + + {current && + current.source_operator_note_revision_sha256 !== + sourceOperatorNoteRevisionSha256 && ( +
+ STALE BINDING: this accepted intent was based on an older OperatorLog revision. + Append a new accepted-intent revision to bind the current human interpretation. +
+ )} + +
+ + + setCode( + event.currentTarget.value + .toUpperCase() + .replace(/[^A-Z0-9_]/g, "_"), + ) + } + aria-label="Accepted intent code" + placeholder="OPEN_NETWORK_ADAPTER_PROPERTIES" + /> +
+ + {!operatorNoteActive && ( +
+ The current OperatorLog revision is retracted. Accepted intent cannot be created from retracted interpretation. +
+ )} + +
+ + {current?.status === "ACTIVE" && ( + + )} + +
+ + {message &&
{message}
} + +
+ MACHINE CANDIDATE != HUMAN ANNOTATION != ACCEPTED INTENT != EXECUTION POLICY +
+ + )} +
+ ); +} diff --git a/phishell/src/components/GhostWalkOperatorEditor.tsx b/phishell/src/components/GhostWalkOperatorEditor.tsx index 1752c26c..7ca806e7 100644 --- a/phishell/src/components/GhostWalkOperatorEditor.tsx +++ b/phishell/src/components/GhostWalkOperatorEditor.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useState } from "react"; +import { GhostWalkAcceptedIntentEditor } from "./GhostWalkAcceptedIntentEditor"; import { ghostWalkOperatorLogClient, type GhostWalkOperatorNote, @@ -132,6 +133,12 @@ export function GhostWalkOperatorEditor({
HUMAN INTERPRETATION != MACHINE INFERENCE · SAVE APPENDS · SOURCE RECEIPT IMMUTABLE · EXECUTION AUTHORITY FALSE
+ + ) : ( <> diff --git a/phishell/src/ghostwalk/acceptedIntent.test.ts b/phishell/src/ghostwalk/acceptedIntent.test.ts new file mode 100644 index 00000000..8072bf24 --- /dev/null +++ b/phishell/src/ghostwalk/acceptedIntent.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it, vi } from "vitest"; +import { + createGhostWalkAcceptedIntentClient, + isGhostWalkAcceptedIntentEnvelope, +} from "./acceptedIntent"; + +const intent = { + schema_version: "phios.ghostwalk_accepted_intent_revision.v0.29", + target_inference_receipt_sha256: "a".repeat(64), + source_operator_note_revision_sha256: "b".repeat(64), + revision: 1, + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + status: "ACTIVE", + accepted_by: "operator:local", + accepted_at: "2026-09-27T06:55:00.000Z", + supersedes_revision_sha256: null, + human_intent_confirmed: true, + causation_proven: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + revision_sha256: "c".repeat(64), +} as const; + +const envelope = { + transportSchemaVersion: "phios.ghostwalk-accepted-intent-transport.v0.29", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-accepted-intent", + localOnly: true, + intentMutation: false, + desktopEffectPerformed: false, + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T06:55:00.000Z", + intent, +} as const; + +describe("Ghost-Walk accepted intent browser client", () => { + it("validates typed intent while rejecting policy authority", () => { + expect(isGhostWalkAcceptedIntentEnvelope(envelope, false)).toBe(true); + expect( + isGhostWalkAcceptedIntentEnvelope({ + ...envelope, + policyAuthority: true, + }, false), + ).toBe(false); + }); + + it("distinguishes no intent from unavailable", async () => { + const fetcher = vi.fn(async () => new Response("", { status: 404 })); + const client = createGhostWalkAcceptedIntentClient({ + fetcher: fetcher as typeof fetch, + }); + await expect(client.read("a".repeat(64))).resolves.toEqual({ kind: "none" }); + }); + + it("does not send policy or accepted-by fields", async () => { + const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { + const body = JSON.parse(String(init?.body)); + expect(body.intent_family).toBe("OPEN"); + expect(body.intent_code).toBe("OPEN_NETWORK_ADAPTER_PROPERTIES"); + expect("policyAuthority" in body).toBe(false); + expect("accepted_by" in body).toBe(false); + return new Response( + JSON.stringify({ + ...envelope, + intentMutation: true, + effectPerformed: true, + }), + { + status: 200, + headers: { "content-type": "application/json" }, + }, + ); + }); + const client = createGhostWalkAcceptedIntentClient({ + fetcher: fetcher as typeof fetch, + }); + await expect( + client.accept({ + targetSha256: "a".repeat(64), + sourceOperatorNoteRevisionSha256: "b".repeat(64), + family: "OPEN", + code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + expectedCurrentRevisionSha256: null, + }), + ).resolves.toMatchObject({ kind: "applied" }); + }); + + it("rejects code whose prefix disagrees with family", async () => { + const fetcher = vi.fn(); + const client = createGhostWalkAcceptedIntentClient({ + fetcher: fetcher as typeof fetch, + }); + await expect( + client.accept({ + targetSha256: "a".repeat(64), + sourceOperatorNoteRevisionSha256: "b".repeat(64), + family: "OPEN", + code: "TOGGLE_NETWORK_ADAPTER_PROPERTIES", + expectedCurrentRevisionSha256: null, + }), + ).resolves.toEqual({ kind: "unavailable" }); + expect(fetcher).not.toHaveBeenCalled(); + }); +}); diff --git a/phishell/src/ghostwalk/acceptedIntent.ts b/phishell/src/ghostwalk/acceptedIntent.ts new file mode 100644 index 00000000..70425d4c --- /dev/null +++ b/phishell/src/ghostwalk/acceptedIntent.ts @@ -0,0 +1,273 @@ +export type GhostWalkIntentFamily = + | "NAVIGATE" + | "OPEN" + | "CLOSE" + | "SELECT" + | "TOGGLE" + | "ENTER_TEXT" + | "SUBMIT" + | "CONFIRM" + | "CANCEL" + | "OTHER"; + +export type GhostWalkAcceptedIntentStatus = "ACTIVE" | "REVOKED"; + +export interface GhostWalkAcceptedIntent { + schema_version: "phios.ghostwalk_accepted_intent_revision.v0.29"; + target_inference_receipt_sha256: string; + source_operator_note_revision_sha256: string; + revision: number; + intent_family: GhostWalkIntentFamily; + intent_code: string; + status: GhostWalkAcceptedIntentStatus; + accepted_by: string; + accepted_at: string; + supersedes_revision_sha256: string | null; + human_intent_confirmed: true; + causation_proven: false; + policy_authority: false; + operational_authority: false; + action_authority: false; + execution_authority: false; + revision_sha256: string; +} + +export interface GhostWalkAcceptedIntentEnvelope { + transportSchemaVersion: "phios.ghostwalk-accepted-intent-transport.v0.29"; + transport: "loopback-http"; + transportIdentity: "phios-ghostwalk-accepted-intent"; + localOnly: true; + intentMutation: boolean; + desktopEffectPerformed: false; + policyAuthority: false; + operationalAuthority: false; + actionAuthority: false; + executionAuthority: false; + effectPerformed: boolean; + servedAt: string; + intent: GhostWalkAcceptedIntent; +} + +export type GhostWalkAcceptedIntentReadResult = + | { kind: "found"; intent: GhostWalkAcceptedIntent } + | { kind: "none" } + | { kind: "unavailable" }; + +export type GhostWalkAcceptedIntentMutationResult = + | { kind: "applied"; intent: GhostWalkAcceptedIntent } + | { kind: "conflict" } + | { kind: "unavailable" }; + +export const GHOSTWALK_INTENT_FAMILIES: GhostWalkIntentFamily[] = [ + "NAVIGATE", + "OPEN", + "CLOSE", + "SELECT", + "TOGGLE", + "ENTER_TEXT", + "SUBMIT", + "CONFIRM", + "CANCEL", + "OTHER", +]; + +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 boundedString(value: unknown, maximum = 512): value is string { + return typeof value === "string" && value.length > 0 && value.length <= maximum; +} + +function validCode(family: GhostWalkIntentFamily, code: unknown): code is string { + if (typeof code !== "string" || !/^[A-Z][A-Z0-9_]{2,127}$/.test(code)) { + return false; + } + return family === "OTHER" || code.startsWith(`${family}_`); +} + +export function isGhostWalkAcceptedIntent( + value: unknown, +): value is GhostWalkAcceptedIntent { + if (!record(value)) return false; + const family = value.intent_family as GhostWalkIntentFamily; + return ( + value.schema_version === "phios.ghostwalk_accepted_intent_revision.v0.29" && + sha(value.target_inference_receipt_sha256) && + sha(value.source_operator_note_revision_sha256) && + typeof value.revision === "number" && + Number.isInteger(value.revision) && + value.revision >= 1 && + GHOSTWALK_INTENT_FAMILIES.includes(family) && + validCode(family, value.intent_code) && + (value.status === "ACTIVE" || value.status === "REVOKED") && + boundedString(value.accepted_by) && + timestamp(value.accepted_at) && + (value.supersedes_revision_sha256 === null || sha(value.supersedes_revision_sha256)) && + value.human_intent_confirmed === true && + value.causation_proven === false && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false && + sha(value.revision_sha256) + ); +} + +export function isGhostWalkAcceptedIntentEnvelope( + value: unknown, + mutated: boolean, +): value is GhostWalkAcceptedIntentEnvelope { + if (!record(value)) return false; + return ( + value.transportSchemaVersion === "phios.ghostwalk-accepted-intent-transport.v0.29" && + value.transport === "loopback-http" && + value.transportIdentity === "phios-ghostwalk-accepted-intent" && + value.localOnly === true && + value.intentMutation === mutated && + value.desktopEffectPerformed === false && + value.policyAuthority === false && + value.operationalAuthority === false && + value.actionAuthority === false && + value.executionAuthority === false && + value.effectPerformed === mutated && + timestamp(value.servedAt) && + isGhostWalkAcceptedIntent(value.intent) + ); +} + +export function createGhostWalkAcceptedIntentClient({ + 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/accepted-intent?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + credentials: "same-origin", + headers: { accept: "application/json" }, + signal: controller.signal, + }, + ); + if (response.status === 404) return { kind: "none" }; + if (!response.ok) return { kind: "unavailable" }; + const payload: unknown = await response.json(); + if (!isGhostWalkAcceptedIntentEnvelope(payload, false)) { + return { kind: "unavailable" }; + } + return { kind: "found", intent: payload.intent }; + } catch { + return { kind: "unavailable" }; + } finally { + globalThis.clearTimeout(timeout); + } + }, + + async accept({ + targetSha256, + sourceOperatorNoteRevisionSha256, + family, + code, + expectedCurrentRevisionSha256, + }: { + targetSha256: string; + sourceOperatorNoteRevisionSha256: string; + family: GhostWalkIntentFamily; + code: string; + expectedCurrentRevisionSha256: string | null; + }): Promise { + if ( + !sha(targetSha256) || + !sha(sourceOperatorNoteRevisionSha256) || + !GHOSTWALK_INTENT_FAMILIES.includes(family) || + !validCode(family, code) || + ( + expectedCurrentRevisionSha256 !== null && + !sha(expectedCurrentRevisionSha256) + ) + ) { + return { kind: "unavailable" }; + } + + return mutate({ + operation: "ACCEPT", + target_inference_receipt_sha256: targetSha256, + source_operator_note_revision_sha256: sourceOperatorNoteRevisionSha256, + intent_family: family, + intent_code: code, + expected_current_revision_sha256: expectedCurrentRevisionSha256, + }); + }, + + async revoke({ + targetSha256, + expectedCurrentRevisionSha256, + }: { + targetSha256: string; + expectedCurrentRevisionSha256: string; + }): Promise { + if (!sha(targetSha256) || !sha(expectedCurrentRevisionSha256)) { + return { kind: "unavailable" }; + } + return mutate({ + operation: "REVOKE", + target_inference_receipt_sha256: targetSha256, + expected_current_revision_sha256: expectedCurrentRevisionSha256, + }); + }, + }; + + async function mutate(body: Record): Promise { + const controller = new AbortController(); + const timeout = globalThis.setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + "/api/v1/ghostwalk/accepted-intent/revisions", + { + method: "POST", + cache: "no-store", + credentials: "same-origin", + headers: { + accept: "application/json", + "content-type": "application/json", + }, + body: JSON.stringify(body), + signal: controller.signal, + }, + ); + if (response.status === 409) return { kind: "conflict" }; + if (!response.ok) return { kind: "unavailable" }; + + const payload: unknown = await response.json(); + if (!isGhostWalkAcceptedIntentEnvelope(payload, true)) { + return { kind: "unavailable" }; + } + return { kind: "applied", intent: payload.intent }; + } catch { + return { kind: "unavailable" }; + } finally { + globalThis.clearTimeout(timeout); + } + } +} + +export const ghostWalkAcceptedIntentClient = + createGhostWalkAcceptedIntentClient(); diff --git a/phishell/src/styles.css b/phishell/src/styles.css index 116fc8d8..160b0f3c 100644 --- a/phishell/src/styles.css +++ b/phishell/src/styles.css @@ -317,3 +317,14 @@ linear-gradient(135deg,rgba(13,32,42,.92),rgba(5,13,17,.96));box-shadow:inset 0 .ghostwalk-editor-actions{display:flex;flex-wrap:wrap;gap:6px}.ghostwalk-editor-actions button,.ghostwalk-editor-reload{height:30px;padding:0 9px;border:1px solid #2c6170;border-radius:6px;background:rgba(39,223,255,.035);color:var(--cyan);font-size:6px;letter-spacing:.05em;cursor:pointer}.ghostwalk-editor-actions button.retract{border-color:rgba(243,182,75,.35);color:var(--amber);background:rgba(243,182,75,.025)}.ghostwalk-editor-actions button:disabled{opacity:.4;cursor:not-allowed} .ghostwalk-editor-message{padding:7px 8px;border:1px solid rgba(243,182,75,.23);border-radius:6px;background:rgba(243,182,75,.025);color:#d7c18f;font-size:7px;line-height:1.45} .ghostwalk-editor-boundary{padding:7px 8px;border:1px solid rgba(32,229,192,.2);border-radius:6px;background:rgba(32,229,192,.02);color:var(--teal);font:6px ui-monospace,monospace;letter-spacing:.04em;line-height:1.45} + + +/* Macro Runtime v0.29 typed accepted-intent layer */ +.ghostwalk-intent-editor{display:grid;gap:8px;margin-top:4px;padding:10px;border:1px solid rgba(32,229,192,.24);border-radius:8px;background:linear-gradient(155deg,rgba(6,29,28,.52),rgba(5,15,20,.9))} +.ghostwalk-intent-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.ghostwalk-intent-head small{display:block;color:var(--teal);font-size:7px;letter-spacing:.13em}.ghostwalk-intent-head b{display:block;margin-top:4px;color:var(--secondary);font:7px ui-monospace,monospace}.ghostwalk-intent-head>span{padding:4px 6px;border:1px solid rgba(32,229,192,.2);border-radius:4px;color:var(--teal);font:6px ui-monospace,monospace;letter-spacing:.05em} +.ghostwalk-intent-current{display:grid;gap:3px;padding:8px;border:1px solid rgba(32,229,192,.16);border-radius:6px;background:rgba(32,229,192,.02)}.ghostwalk-intent-current b{color:var(--teal);font:8px ui-monospace,monospace;overflow-wrap:anywhere}.ghostwalk-intent-current span,.ghostwalk-intent-current small{color:var(--muted);font:6px ui-monospace,monospace} +.ghostwalk-intent-form{display:grid;grid-template-columns:120px 1fr;gap:6px}.ghostwalk-intent-form select,.ghostwalk-intent-form input{height:31px;border:1px solid var(--border);border-radius:6px;background:#061015;color:var(--text);padding:0 8px;font-size:7px;outline:none}.ghostwalk-intent-form input{font-family:ui-monospace,monospace}.ghostwalk-intent-form select:focus,.ghostwalk-intent-form input:focus{border-color:var(--teal)}.ghostwalk-intent-form select:disabled,.ghostwalk-intent-form input:disabled{opacity:.45} +.ghostwalk-intent-actions{display:flex;flex-wrap:wrap;gap:6px}.ghostwalk-intent-actions button{height:30px;padding:0 9px;border:1px solid rgba(32,229,192,.3);border-radius:6px;background:rgba(32,229,192,.03);color:var(--teal);font-size:6px;letter-spacing:.05em;cursor:pointer}.ghostwalk-intent-actions button.revoke{border-color:rgba(243,182,75,.35);color:var(--amber);background:rgba(243,182,75,.025)}.ghostwalk-intent-actions button:disabled{opacity:.4;cursor:not-allowed} +.ghostwalk-intent-message,.ghostwalk-intent-warning{padding:7px 8px;border-radius:6px;font-size:7px;line-height:1.45}.ghostwalk-intent-message{border:1px solid rgba(32,229,192,.18);background:rgba(32,229,192,.02);color:var(--teal)}.ghostwalk-intent-warning{border:1px solid rgba(243,182,75,.28);background:rgba(243,182,75,.03);color:#d7c18f} +.ghostwalk-intent-boundary{padding:7px 8px;border:1px solid rgba(39,223,255,.18);border-radius:6px;background:rgba(39,223,255,.02);color:var(--cyan);font:6px ui-monospace,monospace;letter-spacing:.04em;line-height:1.45} +@media(max-width:780px){.ghostwalk-intent-form{grid-template-columns:1fr}} diff --git a/tests/test_macro_accepted_intent.py b/tests/test_macro_accepted_intent.py new file mode 100644 index 00000000..ca52d7a7 --- /dev/null +++ b/tests/test_macro_accepted_intent.py @@ -0,0 +1,335 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import pytest + +from phios.macro_accepted_intent import ( + GhostWalkAcceptedIntentError, + GhostWalkAcceptedIntentRegistry, + GhostWalkAcceptedIntentStatus, + GhostWalkIntentFamily, +) +from phios.macro_operator_log import OperatorLog +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) -> 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="Correction: opened network adapter properties.", + created_at="2026-09-27T06:50:00+00:00", + tags=( + "ghostwalk", + "operator-interpretation", + "transition-inference", + ), + ) + return note.revision_sha256 + + +def test_accepts_typed_intent_bound_to_current_operator_note( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha = _seed(ledger) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + + item = registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + accepted_at="2026-09-27T06:51:00+00:00", + ) + + assert item.revision == 1 + assert item.status is GhostWalkAcceptedIntentStatus.ACTIVE + assert item.human_intent_confirmed is True + assert item.causation_proven is False + assert item.policy_authority is False + assert item.execution_authority is False + + +def test_intent_code_must_match_typed_family( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha = _seed(ledger) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + + with pytest.raises( + GhostWalkAcceptedIntentError, + match="must start with OPEN_", + ): + registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="TOGGLE_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + ) + + +def test_acceptance_requires_exact_current_operator_note( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha = _seed(ledger) + current = OperatorLog(ledger).current( + note_id=f"ghostwalk-transition:{ACTION}" + ) + OperatorLog(ledger).edit( + note_id=current.note_id, + expected_current_revision_sha256=note_sha, + author_id="operator:local", + body="Newer correction.", + created_at="2026-09-27T06:51:00+00:00", + tags=current.tags, + ) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + + with pytest.raises( + GhostWalkAcceptedIntentError, + match="operator note revision changed", + ): + registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + ) + + +def test_retracted_operator_note_cannot_seed_acceptance( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha = _seed(ledger) + current = OperatorLog(ledger).current( + note_id=f"ghostwalk-transition:{ACTION}" + ) + from phios.macro_operator_log import OperatorNoteStatus + + retracted = OperatorLog(ledger).edit( + note_id=current.note_id, + expected_current_revision_sha256=note_sha, + author_id="operator:local", + body="Retracted.", + created_at="2026-09-27T06:51:00+00:00", + tags=current.tags, + status=OperatorNoteStatus.RETRACTED, + ) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + + with pytest.raises( + GhostWalkAcceptedIntentError, + match="ACTIVE operator note", + ): + registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=( + retracted.revision_sha256 + ), + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + ) + + +def test_reclassification_is_append_only_and_concurrency_guarded( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha = _seed(ledger) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + first = registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + accepted_at="2026-09-27T06:51:00+00:00", + ) + second = registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.NAVIGATE, + intent_code="NAVIGATE_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=first.revision_sha256, + accepted_at="2026-09-27T06:52:00+00:00", + ) + + assert second.revision == 2 + assert second.supersedes_revision_sha256 == first.revision_sha256 + rows = ledger.ghostwalk_accepted_intent_revisions( + target_inference_receipt_sha256=TARGET + ) + assert len(rows) == 2 + + with pytest.raises( + GhostWalkAcceptedIntentError, + match="revision changed before update", + ): + registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_SETTINGS", + expected_current_revision_sha256=first.revision_sha256, + ) + + +def test_revoke_appends_without_erasing_accepted_intent( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha = _seed(ledger) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + first = registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + ) + + revoked = registry.revoke( + target_inference_receipt_sha256=TARGET, + expected_current_revision_sha256=first.revision_sha256, + ) + + assert revoked.status is GhostWalkAcceptedIntentStatus.REVOKED + assert revoked.revision == 2 + assert len( + ledger.ghostwalk_accepted_intent_revisions( + target_inference_receipt_sha256=TARGET + ) + ) == 2 + + +def test_tampered_accepted_intent_chain_fails_closed( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha = _seed(ledger) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + ) + + path = ledger.path.parent / "ghostwalk-accepted-intent-revisions.jsonl" + row = json.loads(path.read_text(encoding="utf-8")) + row["intent_code"] = "OPEN_TAMPERED" + path.write_text( + json.dumps(row, sort_keys=True) + "\n", + encoding="utf-8", + ) + + with pytest.raises( + GhostWalkAcceptedIntentError, + match="revision hash mismatch", + ): + registry.current( + target_inference_receipt_sha256=TARGET + ) + + +def test_tampered_source_operator_note_invalidates_accepted_intent( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha = _seed(ledger) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note_sha, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + ) + + path = ledger.path.parent / "operator-log-revisions.jsonl" + row = json.loads(path.read_text(encoding="utf-8")) + row["body"] = "Tampered human interpretation." + path.write_text( + json.dumps(row, sort_keys=True) + "\n", + encoding="utf-8", + ) + + with pytest.raises( + GhostWalkAcceptedIntentError, + match="source OperatorLog revision is invalid", + ): + registry.current( + target_inference_receipt_sha256=TARGET + ) diff --git a/tests/test_macro_accepted_intent_server.py b/tests/test_macro_accepted_intent_server.py new file mode 100644 index 00000000..c82c9718 --- /dev/null +++ b/tests/test_macro_accepted_intent_server.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import json +import threading +from dataclasses import dataclass +from http.client import HTTPConnection + +from phios.macro_accepted_intent import ( + GhostWalkAcceptedIntentRevision, + GhostWalkAcceptedIntentStatus, + GhostWalkIntentFamily, +) +from phios.macro_ghostwalk_control_server import ( + LOOPBACK_HOST, + GhostWalkControlServer, +) + + +class FakeSurface: + def snapshot(self) -> object: + raise AssertionError("status endpoint not used") + + +class FakeIntentRegistry: + def __init__(self) -> None: + self.current_item: GhostWalkAcceptedIntentRevision | None = None + self.calls: list[dict[str, object]] = [] + + def current( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAcceptedIntentRevision | None: + self.calls.append( + {"operation": "CURRENT", "target": target_inference_receipt_sha256} + ) + return self.current_item + + def accept( + self, + *, + target_inference_receipt_sha256: str, + source_operator_note_revision_sha256: str, + intent_family: GhostWalkIntentFamily, + intent_code: str, + expected_current_revision_sha256: str | None, + accepted_at: str | None = None, + ) -> GhostWalkAcceptedIntentRevision: + self.calls.append( + { + "operation": "ACCEPT", + "target": target_inference_receipt_sha256, + "source": source_operator_note_revision_sha256, + "family": intent_family.value, + "code": intent_code, + "expected": expected_current_revision_sha256, + } + ) + item = GhostWalkAcceptedIntentRevision( + target_inference_receipt_sha256=target_inference_receipt_sha256, + source_operator_note_revision_sha256=( + source_operator_note_revision_sha256 + ), + revision=1 if expected_current_revision_sha256 is None else 2, + intent_family=intent_family, + intent_code=intent_code, + status=GhostWalkAcceptedIntentStatus.ACTIVE, + accepted_by="operator:local", + accepted_at="2026-09-27T06:55:00+00:00", + supersedes_revision_sha256=( + expected_current_revision_sha256 + ), + ) + self.current_item = item + return item + + def revoke( + self, + *, + target_inference_receipt_sha256: str, + expected_current_revision_sha256: str, + accepted_at: str | None = None, + ) -> GhostWalkAcceptedIntentRevision: + self.calls.append( + { + "operation": "REVOKE", + "target": target_inference_receipt_sha256, + "expected": expected_current_revision_sha256, + } + ) + assert self.current_item is not None + item = GhostWalkAcceptedIntentRevision( + target_inference_receipt_sha256=target_inference_receipt_sha256, + source_operator_note_revision_sha256=( + self.current_item.source_operator_note_revision_sha256 + ), + revision=self.current_item.revision + 1, + intent_family=self.current_item.intent_family, + intent_code=self.current_item.intent_code, + status=GhostWalkAcceptedIntentStatus.REVOKED, + accepted_by="operator:local", + accepted_at="2026-09-27T06:56:00+00:00", + supersedes_revision_sha256=expected_current_revision_sha256, + ) + self.current_item = item + return item + + +def _server( + registry: FakeIntentRegistry, +) -> tuple[GhostWalkControlServer, threading.Thread]: + server = GhostWalkControlServer( + (LOOPBACK_HOST, 0), + surface=FakeSurface(), # type: ignore[arg-type] + accepted_intents=registry, # 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_get_missing_accepted_intent_returns_404_zero_authority() -> None: + registry = FakeIntentRegistry() + server, thread = _server(registry) + try: + status, payload = _request( + server, + "GET", + "/api/v1/ghostwalk/accepted-intent?target=" + "a" * 64, + ) + assert status == 404 + assert payload["effectPerformed"] is False + assert payload["policyAuthority"] is False + assert payload["executionAuthority"] is False + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_accept_intent_is_persistent_non_policy_mutation() -> None: + registry = FakeIntentRegistry() + server, thread = _server(registry) + try: + status, payload = _request( + server, + "POST", + "/api/v1/ghostwalk/accepted-intent/revisions", + { + "operation": "ACCEPT", + "target_inference_receipt_sha256": "a" * 64, + "source_operator_note_revision_sha256": "b" * 64, + "intent_family": "OPEN", + "intent_code": "OPEN_NETWORK_ADAPTER_PROPERTIES", + "expected_current_revision_sha256": None, + }, + ) + assert status == 200 + assert payload["intentMutation"] is True + assert payload["effectPerformed"] is True + assert payload["desktopEffectPerformed"] is False + assert payload["policyAuthority"] is False + assert payload["executionAuthority"] is False + assert payload["intent"]["human_intent_confirmed"] is True + assert payload["intent"]["intent_code"] == ( + "OPEN_NETWORK_ADAPTER_PROPERTIES" + ) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_revoke_intent_appends_revision() -> None: + registry = FakeIntentRegistry() + first = registry.accept( + target_inference_receipt_sha256="a" * 64, + source_operator_note_revision_sha256="b" * 64, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + expected_current_revision_sha256=None, + ) + server, thread = _server(registry) + try: + status, payload = _request( + server, + "POST", + "/api/v1/ghostwalk/accepted-intent/revisions", + { + "operation": "REVOKE", + "target_inference_receipt_sha256": "a" * 64, + "expected_current_revision_sha256": ( + first.revision_sha256 + ), + }, + ) + assert status == 200 + assert payload["intent"]["status"] == "REVOKED" + assert payload["intent"]["revision"] == 2 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_browser_cannot_supply_accepted_by_or_policy_authority() -> None: + registry = FakeIntentRegistry() + server, thread = _server(registry) + try: + status, _ = _request( + server, + "POST", + "/api/v1/ghostwalk/accepted-intent/revisions", + { + "operation": "ACCEPT", + "target_inference_receipt_sha256": "a" * 64, + "source_operator_note_revision_sha256": "b" * 64, + "intent_family": "OPEN", + "intent_code": "OPEN_NETWORK_ADAPTER_PROPERTIES", + "expected_current_revision_sha256": None, + "accepted_by": "browser:fake", + "policyAuthority": True, + }, + ) + assert status == 400 + assert not any( + call.get("operation") == "ACCEPT" + for call in registry.calls + ) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2)