From e925727ae661da1c9c07fb09d03cc88190d56f02 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:31:34 -0700 Subject: [PATCH 01/21] feat: add governed Ghost-Walk OperatorLog editor --- phios/macro_ghostwalk_operator_editor.py | 383 +++++++++++++++++++++++ 1 file changed, 383 insertions(+) create mode 100644 phios/macro_ghostwalk_operator_editor.py diff --git a/phios/macro_ghostwalk_operator_editor.py b/phios/macro_ghostwalk_operator_editor.py new file mode 100644 index 00000000..27e8ed09 --- /dev/null +++ b/phios/macro_ghostwalk_operator_editor.py @@ -0,0 +1,383 @@ +"""Human-governed OperatorLog editing for Ghost-Walk v0.28. + +This service edits only the append-only OperatorLog annotation chain attached to +an immutable transition-inference receipt. It never mutates inference evidence, +desktop state, or execution authority. +""" + +from __future__ import annotations + +import re +import threading +from dataclasses import dataclass +from datetime import UTC, datetime +from enum import StrEnum + +from phios.macro_operator_log import ( + OperatorLog, + OperatorLogContractError, + OperatorLogRevision, + OperatorNoteStatus, +) +from phios.spine.ledger import RealityLedger + +GHOSTWALK_OPERATOR_NOTE_SCHEMA_VERSION = ( + "phios.ghostwalk_operator_note.v0.28" +) +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_REQUIRED_TAGS = ( + "ghostwalk", + "operator-interpretation", + "transition-inference", +) + + +class GhostWalkOperatorEditorError(ValueError): + """Raised when a Ghost-Walk annotation edit cannot be trusted.""" + + +class GhostWalkOperatorEditResult(StrEnum): + APPLIED = "APPLIED" + + +def _require_text( + value: object, + field: str, + *, + maximum: int = 16384, +) -> str: + if not isinstance(value, str) or not value: + raise GhostWalkOperatorEditorError( + f"{field} must be a non-empty string" + ) + if len(value) > maximum: + raise GhostWalkOperatorEditorError( + f"{field} exceeds {maximum} characters" + ) + if any(ord(char) < 32 and char not in "\n\r\t" for char in value): + raise GhostWalkOperatorEditorError( + f"{field} contains unsupported 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 GhostWalkOperatorEditorError( + f"{field} must be a lowercase SHA-256 digest" + ) + return text + + +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 GhostWalkOperatorEditorError( + f"{field} must be an ISO-8601 timestamp" + ) from exc + if parsed.tzinfo is None: + raise GhostWalkOperatorEditorError( + f"{field} must include a timezone" + ) + return text + + +def _utc_now() -> str: + return datetime.now(UTC).isoformat() + + +@dataclass(frozen=True, slots=True) +class GhostWalkOperatorNoteView: + target_inference_receipt_sha256: str + note_id: str + revision: int + revision_sha256: str + author_id: str + body: str + tags: tuple[str, ...] + status: OperatorNoteStatus + created_at: str + supersedes_revision_sha256: str | None + inference_status: str + session_id: str + action_observation_sha256: str + operational_authority: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = GHOSTWALK_OPERATOR_NOTE_SCHEMA_VERSION + + def __post_init__(self) -> None: + if self.schema_version != GHOSTWALK_OPERATOR_NOTE_SCHEMA_VERSION: + raise GhostWalkOperatorEditorError( + "unsupported Ghost-Walk operator-note schema" + ) + _require_sha256( + self.target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + _require_text(self.note_id, "note_id", maximum=512) + if ( + isinstance(self.revision, bool) + or not isinstance(self.revision, int) + or self.revision < 1 + ): + raise GhostWalkOperatorEditorError( + "revision must be a positive integer" + ) + _require_sha256(self.revision_sha256, "revision_sha256") + _require_text(self.author_id, "author_id", maximum=512) + _require_text(self.body, "body") + for tag in self.tags: + _require_text(tag, "tag", maximum=128) + if tuple(sorted(set(self.tags))) != self.tags: + raise GhostWalkOperatorEditorError( + "tags must be sorted and unique" + ) + _require_timestamp(self.created_at, "created_at") + if self.supersedes_revision_sha256 is not None: + _require_sha256( + self.supersedes_revision_sha256, + "supersedes_revision_sha256", + ) + _require_text(self.inference_status, "inference_status", maximum=64) + _require_text(self.session_id, "session_id", maximum=512) + _require_sha256( + self.action_observation_sha256, + "action_observation_sha256", + ) + if ( + self.operational_authority + or self.action_authority + or self.execution_authority + ): + raise GhostWalkOperatorEditorError( + "GhostWalkOperatorNoteView cannot carry authority" + ) + + def to_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "target_inference_receipt_sha256": ( + self.target_inference_receipt_sha256 + ), + "note_id": self.note_id, + "revision": self.revision, + "revision_sha256": self.revision_sha256, + "author_id": self.author_id, + "body": self.body, + "tags": list(self.tags), + "status": self.status.value, + "created_at": self.created_at, + "supersedes_revision_sha256": ( + self.supersedes_revision_sha256 + ), + "inference_status": self.inference_status, + "session_id": self.session_id, + "action_observation_sha256": ( + self.action_observation_sha256 + ), + "operational_authority": self.operational_authority, + "action_authority": self.action_authority, + "execution_authority": self.execution_authority, + } + + +@dataclass(frozen=True, slots=True) +class GhostWalkOperatorEditOutcome: + result: GhostWalkOperatorEditResult + note: GhostWalkOperatorNoteView + + def to_dict(self) -> dict[str, object]: + return { + "result": self.result.value, + "note": self.note.to_dict(), + "annotation_mutation": True, + "desktop_effect_performed": False, + "operational_authority": False, + "action_authority": False, + "execution_authority": False, + } + + +class GhostWalkOperatorEditor: + """Serialize append-only human interpretation revisions by inference.""" + + def __init__( + self, + *, + ledger: RealityLedger, + author_id: str, + ) -> None: + if not isinstance(ledger, RealityLedger): + raise GhostWalkOperatorEditorError( + "ledger must be a RealityLedger" + ) + self._ledger = ledger + self.author_id = _require_text( + author_id, + "author_id", + maximum=512, + ) + self._lock = threading.RLock() + + def view( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkOperatorNoteView: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + with self._lock: + inference = self._inference(target) + revision = self._current_revision(target) + return self._view( + inference=inference, + revision=revision, + ) + + def edit( + self, + *, + target_inference_receipt_sha256: str, + expected_current_revision_sha256: str, + body: str, + status: OperatorNoteStatus = OperatorNoteStatus.ACTIVE, + created_at: str | None = None, + ) -> GhostWalkOperatorEditOutcome: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + expected = _require_sha256( + expected_current_revision_sha256, + "expected_current_revision_sha256", + ) + body = _require_text(body, "body") + timestamp = _require_timestamp( + _utc_now() if created_at is None else created_at, + "created_at", + ) + + with self._lock: + inference = self._inference(target) + current = self._current_revision(target) + if current.revision_sha256 != expected: + raise GhostWalkOperatorEditorError( + "operator note revision changed before edit" + ) + tags = tuple( + sorted(set(current.tags).union(_REQUIRED_TAGS)) + ) + try: + revision = OperatorLog(self._ledger).edit( + note_id=current.note_id, + expected_current_revision_sha256=expected, + author_id=self.author_id, + body=body, + created_at=timestamp, + tags=tags, + status=status, + ) + except OperatorLogContractError as exc: + raise GhostWalkOperatorEditorError(str(exc)) from exc + + return GhostWalkOperatorEditOutcome( + result=GhostWalkOperatorEditResult.APPLIED, + note=self._view( + inference=inference, + revision=revision, + ), + ) + + def _inference( + self, + target_sha256: str, + ) -> dict[str, object]: + row = self._ledger.transition_inference_receipt( + receipt_sha256=target_sha256 + ) + if row is None: + raise GhostWalkOperatorEditorError( + "transition inference receipt does not exist" + ) + return row + + def _current_revision( + self, + target_sha256: str, + ) -> OperatorLogRevision: + rows = [ + row + for row in self._ledger.operator_log_revisions() + if row.get("target_sha256") == target_sha256 + ] + if not rows: + raise GhostWalkOperatorEditorError( + "operator note does not exist for transition inference" + ) + + note_ids = { + row.get("note_id") + for row in rows + if isinstance(row.get("note_id"), str) + } + if len(note_ids) != 1: + raise GhostWalkOperatorEditorError( + "transition inference has ambiguous operator-note chains" + ) + note_id = next(iter(note_ids)) + try: + return OperatorLog(self._ledger).current(note_id=note_id) + except OperatorLogContractError as exc: + raise GhostWalkOperatorEditorError(str(exc)) from exc + + @staticmethod + def _view( + *, + inference: dict[str, object], + revision: OperatorLogRevision, + ) -> GhostWalkOperatorNoteView: + status = _require_text( + inference.get("status"), + "inference_status", + maximum=64, + ) + session_id = _require_text( + inference.get("session_id"), + "session_id", + maximum=512, + ) + action_observation_sha256 = _require_sha256( + inference.get("action_observation_sha256"), + "action_observation_sha256", + ) + target = _require_sha256( + inference.get("receipt_sha256"), + "inference_receipt_sha256", + ) + if revision.target_sha256 != target: + raise GhostWalkOperatorEditorError( + "operator note target does not match inference" + ) + return GhostWalkOperatorNoteView( + target_inference_receipt_sha256=target, + note_id=revision.note_id, + revision=revision.revision, + revision_sha256=revision.revision_sha256, + author_id=revision.author_id, + body=revision.body, + tags=revision.tags, + status=revision.status, + created_at=revision.created_at, + supersedes_revision_sha256=( + revision.supersedes_revision_sha256 + ), + inference_status=status, + session_id=session_id, + action_observation_sha256=action_observation_sha256, + ) From a59a80be4cfc07c23391367fcc268eb8dc86fa37 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:31:36 -0700 Subject: [PATCH 02/21] test: cover Ghost-Walk OperatorLog editor --- tests/test_macro_ghostwalk_operator_editor.py | 203 ++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 tests/test_macro_ghostwalk_operator_editor.py diff --git a/tests/test_macro_ghostwalk_operator_editor.py b/tests/test_macro_ghostwalk_operator_editor.py new file mode 100644 index 00000000..761df1dd --- /dev/null +++ b/tests/test_macro_ghostwalk_operator_editor.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +import json +import threading +from pathlib import Path + +import pytest + +from phios.macro_ghostwalk_operator_editor import ( + GhostWalkOperatorEditor, + GhostWalkOperatorEditorError, +) +from phios.macro_operator_log import OperatorLog, OperatorNoteStatus +from phios.spine.ledger import RealityLedger + +TARGET = "a" * 64 +ACTION = "b" * 64 + + +def _ledger(tmp_path: Path) -> RealityLedger: + return RealityLedger(tmp_path / "ledger" / "receipts.jsonl") + + +def _seed(ledger: RealityLedger) -> str: + path = ledger.path.parent / "transition-inference-receipts.jsonl" + path.write_text( + json.dumps( + { + "receipt_sha256": TARGET, + "status": "CANDIDATES", + "session_id": "demo", + "action_observation_sha256": ACTION, + }, + 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="Machine-generated candidate summary.", + created_at="2026-09-27T06:30:00+00:00", + tags=("ghostwalk", "transition-inference"), + ) + return note.revision_sha256 + + +def test_editor_reads_current_note_bound_to_inference( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + first_sha = _seed(ledger) + editor = GhostWalkOperatorEditor( + ledger=ledger, + author_id="operator:local", + ) + + view = editor.view( + target_inference_receipt_sha256=TARGET + ) + + assert view.revision == 1 + assert view.revision_sha256 == first_sha + assert view.target_inference_receipt_sha256 == TARGET + assert view.inference_status == "CANDIDATES" + assert view.action_observation_sha256 == ACTION + assert view.execution_authority is False + + +def test_editor_appends_human_correction_without_rewriting_inference( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + first_sha = _seed(ledger) + editor = GhostWalkOperatorEditor( + ledger=ledger, + author_id="operator:mikey", + ) + + outcome = editor.edit( + target_inference_receipt_sha256=TARGET, + expected_current_revision_sha256=first_sha, + body="Correction: I opened network adapter properties.", + created_at="2026-09-27T06:31:00+00:00", + ) + + assert outcome.note.revision == 2 + assert outcome.note.author_id == "operator:mikey" + assert "operator-interpretation" in outcome.note.tags + rows = ledger.operator_log_revisions() + assert rows[0]["body"] == "Machine-generated candidate summary." + assert rows[1]["body"].startswith("Correction:") + inference = ledger.transition_inference_receipt( + receipt_sha256=TARGET + ) + assert inference is not None + assert inference["status"] == "CANDIDATES" + + +def test_editor_rejects_stale_revision( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + first_sha = _seed(ledger) + editor = GhostWalkOperatorEditor( + ledger=ledger, + author_id="operator:local", + ) + editor.edit( + target_inference_receipt_sha256=TARGET, + expected_current_revision_sha256=first_sha, + body="First human edit.", + created_at="2026-09-27T06:31:00+00:00", + ) + + with pytest.raises( + GhostWalkOperatorEditorError, + match="revision changed before edit", + ): + editor.edit( + target_inference_receipt_sha256=TARGET, + expected_current_revision_sha256=first_sha, + body="Stale competing edit.", + created_at="2026-09-27T06:32:00+00:00", + ) + + +def test_editor_retraction_is_append_only( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + first_sha = _seed(ledger) + editor = GhostWalkOperatorEditor( + ledger=ledger, + author_id="operator:local", + ) + + outcome = editor.edit( + target_inference_receipt_sha256=TARGET, + expected_current_revision_sha256=first_sha, + body="Retracted: this interpretation was inaccurate.", + status=OperatorNoteStatus.RETRACTED, + created_at="2026-09-27T06:31:00+00:00", + ) + + assert outcome.note.status is OperatorNoteStatus.RETRACTED + assert len(ledger.operator_log_revisions()) == 2 + + +def test_editor_serializes_competing_expected_revision_edits( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + first_sha = _seed(ledger) + editor = GhostWalkOperatorEditor( + ledger=ledger, + author_id="operator:local", + ) + barrier = threading.Barrier(2) + outcomes: list[str] = [] + + def worker(body: str) -> None: + barrier.wait() + try: + result = editor.edit( + target_inference_receipt_sha256=TARGET, + expected_current_revision_sha256=first_sha, + body=body, + created_at="2026-09-27T06:31:00+00:00", + ) + outcomes.append(result.result.value) + except GhostWalkOperatorEditorError: + outcomes.append("REJECTED") + + first = threading.Thread(target=worker, args=("Edit A",)) + second = threading.Thread(target=worker, args=("Edit B",)) + first.start() + second.start() + first.join() + second.join() + + assert sorted(outcomes) == ["APPLIED", "REJECTED"] + assert len(ledger.operator_log_revisions()) == 2 + + +def test_editor_rejects_unknown_inference_target( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + editor = GhostWalkOperatorEditor( + ledger=ledger, + author_id="operator:local", + ) + + with pytest.raises( + GhostWalkOperatorEditorError, + match="inference receipt does not exist", + ): + editor.view( + target_inference_receipt_sha256="f" * 64 + ) From a5f444f5a91683e7f65b3af3517a252e454349fa Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:31:44 -0700 Subject: [PATCH 03/21] feat: look up transition inference by receipt hash --- phios/spine/ledger.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/phios/spine/ledger.py b/phios/spine/ledger.py index a8aa2fcf..ec6e8abe 100644 --- a/phios/spine/ledger.py +++ b/phios/spine/ledger.py @@ -915,6 +915,22 @@ def recent_transition_inference_receipts( lines = path.read_text(encoding="utf-8").splitlines() return [json.loads(line) for line in lines[-limit:]] + def transition_inference_receipt( + self, + *, + receipt_sha256: str, + ) -> dict[str, object] | None: + """Return one transition inference receipt by its claimed hash.""" + + path = self.path.parent / "transition-inference-receipts.jsonl" + if not path.exists(): + return None + for line in reversed(path.read_text(encoding="utf-8").splitlines()): + row = json.loads(line) + if row.get("receipt_sha256") == receipt_sha256: + return row + return None + def append_uia_state_observation_receipt( self, receipt: "UiaStateObservationReceipt", From 8c5019b86437e1f3bcd9e5b90cc2a02f6adddf18 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:32:42 -0700 Subject: [PATCH 04/21] feat: expose governed OperatorLog editor on Ghost-Walk sidecar --- phios/macro_ghostwalk_control_server.py | 268 +++++++++++++++++++++++- 1 file changed, 267 insertions(+), 1 deletion(-) diff --git a/phios/macro_ghostwalk_control_server.py b/phios/macro_ghostwalk_control_server.py index 9c12528b..c214404f 100644 --- a/phios/macro_ghostwalk_control_server.py +++ b/phios/macro_ghostwalk_control_server.py @@ -10,13 +10,14 @@ import argparse import json import os +import re import sys from datetime import UTC, datetime from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Callable, Mapping, Protocol -from urllib.parse import urlsplit +from urllib.parse import parse_qs, urlsplit from phios.macro_ghostwalk_control_surface import ( GhostWalkControlAction, @@ -25,6 +26,13 @@ GhostWalkControlSurface, ) from phios.macro_ghostwalk_host_service import GhostWalkHostService +from phios.macro_ghostwalk_operator_editor import ( + GhostWalkOperatorEditOutcome, + GhostWalkOperatorEditor, + GhostWalkOperatorEditorError, + GhostWalkOperatorNoteView, +) +from phios.macro_operator_log import OperatorNoteStatus from phios.spine.ledger import RealityLedger LOOPBACK_HOST = "127.0.0.1" @@ -32,6 +40,10 @@ MAX_REQUEST_BYTES = 8192 TRANSPORT_SCHEMA_VERSION = "phios.ghostwalk-control-transport.v0.26" TRANSPORT_IDENTITY = "phios-ghostwalk-control" +OPERATOR_TRANSPORT_SCHEMA_VERSION = ( + "phios.ghostwalk-operator-log-transport.v0.28" +) +OPERATOR_TRANSPORT_IDENTITY = "phios-ghostwalk-operator-editor" DEFAULT_HOST_ID = "ghostwalk-host:local" DEFAULT_BASELINE_SERVICE_ID = "ghostwalk-baseline:local" DEFAULT_COORDINATOR_ID = "ghostwalk-coordinator:local" @@ -55,6 +67,24 @@ def apply( ) -> GhostWalkControlOutcome: ... +class GhostWalkOperatorEditorPort(Protocol): + def view( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkOperatorNoteView: ... + + def edit( + self, + *, + target_inference_receipt_sha256: str, + expected_current_revision_sha256: str, + body: str, + status: OperatorNoteStatus = OperatorNoteStatus.ACTIVE, + created_at: str | None = None, + ) -> GhostWalkOperatorEditOutcome: ... + + def _utc_now() -> str: return datetime.now(UTC).isoformat() @@ -72,6 +102,133 @@ def _transport_base() -> dict[str, object]: } +def _operator_transport_base( + *, + effect_performed: bool, +) -> dict[str, object]: + return { + "transportSchemaVersion": OPERATOR_TRANSPORT_SCHEMA_VERSION, + "transport": "loopback-http", + "transportIdentity": OPERATOR_TRANSPORT_IDENTITY, + "localOnly": True, + "annotationMutation": effect_performed, + "desktopEffectPerformed": False, + "operationalAuthority": False, + "actionAuthority": False, + "executionAuthority": False, + "effectPerformed": effect_performed, + } + + +def operator_note_envelope( + editor: GhostWalkOperatorEditorPort, + *, + target_inference_receipt_sha256: str, +) -> dict[str, object]: + payload = _operator_transport_base(effect_performed=False) + payload.update( + { + "servedAt": _utc_now(), + "note": editor.view( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ).to_dict(), + } + ) + return payload + + +def operator_edit_envelope( + editor: GhostWalkOperatorEditorPort, + *, + target_inference_receipt_sha256: str, + expected_current_revision_sha256: str, + body: str, + status: OperatorNoteStatus, +) -> dict[str, object]: + outcome = editor.edit( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_current_revision_sha256=( + expected_current_revision_sha256 + ), + body=body, + status=status, + ) + payload = _operator_transport_base(effect_performed=True) + payload.update( + { + "servedAt": _utc_now(), + "outcome": outcome.to_dict(), + } + ) + return payload + + +def parse_operator_edit_payload( + payload: object, +) -> tuple[str, str, str, OperatorNoteStatus]: + if not isinstance(payload, Mapping): + raise GhostWalkControlBridgeError( + "OperatorLog edit body must be an object" + ) + expected_keys = { + "target_inference_receipt_sha256", + "expected_current_revision_sha256", + "body", + "status", + } + if set(payload) != expected_keys: + raise GhostWalkControlBridgeError( + "OperatorLog edit fields do not match contract" + ) + + target = payload.get("target_inference_receipt_sha256") + expected = payload.get("expected_current_revision_sha256") + body = payload.get("body") + raw_status = payload.get("status") + + if ( + not isinstance(target, str) + or not re.fullmatch(r"[0-9a-f]{64}", target) + ): + raise GhostWalkControlBridgeError( + "target inference receipt must be a SHA-256 digest" + ) + if ( + not isinstance(expected, str) + or not re.fullmatch(r"[0-9a-f]{64}", expected) + ): + raise GhostWalkControlBridgeError( + "expected revision must be a SHA-256 digest" + ) + if ( + not isinstance(body, str) + or not body + or len(body) > 16384 + or any( + ord(char) < 32 and char not in "\n\r\t" + for char in body + ) + ): + raise GhostWalkControlBridgeError( + "operator note body is invalid" + ) + if not isinstance(raw_status, str): + raise GhostWalkControlBridgeError( + "operator note status must be a string" + ) + try: + status = OperatorNoteStatus(raw_status) + except ValueError as exc: + raise GhostWalkControlBridgeError( + "operator note status is unsupported" + ) from exc + return target, expected, body, status + + def status_envelope(surface: GhostWalkSurface) -> dict[str, object]: payload = _transport_base() payload.update( @@ -200,6 +357,15 @@ def _error( body.update({"error": code, "servedAt": _utc_now()}) self._json(status, body) + def _operator_error( + self, + status: HTTPStatus, + code: str, + ) -> None: + body = _operator_transport_base(effect_performed=False) + body.update({"error": code, "servedAt": _utc_now()}) + self._json(status, body) + def _read_json(self) -> object: raw_length = self.headers.get("content-length") if raw_length is None: @@ -230,6 +396,52 @@ def _read_json(self) -> object: def do_GET(self) -> None: parsed = urlsplit(self.path) + + if parsed.path == "/api/v1/ghostwalk/operator-log": + if self.server.editor is None: + self._operator_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_operator_editor_unavailable", + ) + return + try: + query = parse_qs( + parsed.query, + keep_blank_values=True, + strict_parsing=True, + ) + except ValueError: + self._operator_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_operator_note_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._operator_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_operator_note_request", + ) + return + try: + envelope = operator_note_envelope( + self.server.editor, + target_inference_receipt_sha256=targets[0], + ) + except GhostWalkOperatorEditorError: + self._operator_error( + HTTPStatus.NOT_FOUND, + "ghostwalk_operator_note_not_found", + ) + return + self._json(HTTPStatus.OK, envelope) + return + if ( parsed.path != "/api/v1/ghostwalk" or parsed.query @@ -244,6 +456,49 @@ def do_GET(self) -> None: def do_POST(self) -> None: parsed = urlsplit(self.path) + + if parsed.path == "/api/v1/ghostwalk/operator-log/revisions": + if parsed.query or parsed.fragment: + self._operator_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_operator_edit_request", + ) + return + if self.server.editor is None: + self._operator_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_operator_editor_unavailable", + ) + return + try: + target, expected, body, status = ( + parse_operator_edit_payload(self._read_json()) + ) + except GhostWalkControlBridgeError: + self._operator_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_operator_edit_request", + ) + return + try: + envelope = operator_edit_envelope( + self.server.editor, + target_inference_receipt_sha256=target, + expected_current_revision_sha256=expected, + body=body, + status=status, + ) + except GhostWalkOperatorEditorError as exc: + code = ( + "ghostwalk_operator_edit_conflict" + if "revision changed before edit" in str(exc) + else "ghostwalk_operator_edit_rejected" + ) + self._operator_error(HTTPStatus.CONFLICT, code) + return + self._json(HTTPStatus.OK, envelope) + return + if ( parsed.path != "/api/v1/ghostwalk/actions" or parsed.query @@ -290,6 +545,7 @@ def __init__( address: tuple[str, int], *, surface: GhostWalkSurface, + editor: GhostWalkOperatorEditorPort | None = None, stop_callback: Callable[[], object] | None = None, ) -> None: if address[0] != LOOPBACK_HOST: @@ -297,6 +553,7 @@ def __init__( "Ghost-Walk control server must bind IPv4 loopback" ) self.surface = surface + self.editor = editor self._stop_callback = stop_callback super().__init__(address, GhostWalkControlHandler) @@ -379,9 +636,18 @@ def main() -> None: host, surface = build_local_runtime( state_root=args.state_root, ) + editor = GhostWalkOperatorEditor( + ledger=RealityLedger( + args.state_root.expanduser() + / "ledger" + / "receipts.jsonl" + ), + author_id=DEFAULT_OPERATOR_AUTHOR_ID, + ) server = GhostWalkControlServer( (LOOPBACK_HOST, args.port), surface=surface, + editor=editor, stop_callback=host.stop, ) From 8091f5babefd2838b8f8432a840dea3a1b525255 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:33:09 -0700 Subject: [PATCH 05/21] test: cover Ghost-Walk OperatorLog sidecar endpoints --- ..._macro_ghostwalk_operator_editor_server.py | 236 ++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 tests/test_macro_ghostwalk_operator_editor_server.py diff --git a/tests/test_macro_ghostwalk_operator_editor_server.py b/tests/test_macro_ghostwalk_operator_editor_server.py new file mode 100644 index 00000000..ed6c0a42 --- /dev/null +++ b/tests/test_macro_ghostwalk_operator_editor_server.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +import json +import threading +from dataclasses import dataclass +from http.client import HTTPConnection +from typing import Any + +from phios.macro_ghostwalk_control_server import ( + LOOPBACK_HOST, + GhostWalkControlServer, +) +from phios.macro_operator_log import OperatorNoteStatus + + +@dataclass +class FakeSnapshot: + def to_dict(self) -> dict[str, object]: + return {} + + +class FakeSurface: + def snapshot(self) -> FakeSnapshot: + return FakeSnapshot() + + +@dataclass +class FakeNote: + revision: int + revision_sha256: str + body: str + status: str = "ACTIVE" + + def to_dict(self) -> dict[str, object]: + return { + "schema_version": "phios.ghostwalk_operator_note.v0.28", + "target_inference_receipt_sha256": "a" * 64, + "note_id": "ghostwalk-transition:" + "b" * 64, + "revision": self.revision, + "revision_sha256": self.revision_sha256, + "author_id": "operator:local", + "body": self.body, + "tags": [ + "ghostwalk", + "operator-interpretation", + "transition-inference", + ], + "status": self.status, + "created_at": "2026-09-27T06:30:00+00:00", + "supersedes_revision_sha256": ( + None if self.revision == 1 else "c" * 64 + ), + "inference_status": "CANDIDATES", + "session_id": "demo", + "action_observation_sha256": "b" * 64, + "operational_authority": False, + "action_authority": False, + "execution_authority": False, + } + + +@dataclass +class FakeOutcome: + note: FakeNote + + def to_dict(self) -> dict[str, object]: + return { + "result": "APPLIED", + "note": self.note.to_dict(), + "annotation_mutation": True, + "desktop_effect_performed": False, + "operational_authority": False, + "action_authority": False, + "execution_authority": False, + } + + +class FakeEditor: + def __init__(self) -> None: + self.note = FakeNote( + revision=1, + revision_sha256="c" * 64, + body="Machine summary.", + ) + self.calls: list[dict[str, Any]] = [] + + def view( + self, + *, + target_inference_receipt_sha256: str, + ) -> FakeNote: + assert target_inference_receipt_sha256 == "a" * 64 + return self.note + + def edit( + self, + *, + target_inference_receipt_sha256: str, + expected_current_revision_sha256: str, + body: str, + status: OperatorNoteStatus = OperatorNoteStatus.ACTIVE, + created_at: str | None = None, + ) -> FakeOutcome: + self.calls.append( + { + "target": target_inference_receipt_sha256, + "expected": expected_current_revision_sha256, + "body": body, + "status": status.value, + "created_at": created_at, + } + ) + self.note = FakeNote( + revision=2, + revision_sha256="d" * 64, + body=body, + status=status.value, + ) + return FakeOutcome(self.note) + + +def _server( + editor: FakeEditor, +) -> tuple[GhostWalkControlServer, threading.Thread]: + server = GhostWalkControlServer( + (LOOPBACK_HOST, 0), + surface=FakeSurface(), # type: ignore[arg-type] + editor=editor, # 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_operator_note_get_is_read_only_projection() -> None: + editor = FakeEditor() + server, thread = _server(editor) + try: + status, payload = _request( + server, + "GET", + "/api/v1/ghostwalk/operator-log?target=" + "a" * 64, + ) + assert status == 200 + assert ( + payload["transportSchemaVersion"] + == "phios.ghostwalk-operator-log-transport.v0.28" + ) + assert payload["annotationMutation"] is False + assert payload["effectPerformed"] is False + assert payload["executionAuthority"] is False + assert payload["note"]["revision"] == 1 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_operator_note_post_appends_annotation_revision() -> None: + editor = FakeEditor() + server, thread = _server(editor) + try: + status, payload = _request( + server, + "POST", + "/api/v1/ghostwalk/operator-log/revisions", + { + "target_inference_receipt_sha256": "a" * 64, + "expected_current_revision_sha256": "c" * 64, + "body": "Correction: opened network adapter properties.", + "status": "ACTIVE", + }, + ) + assert status == 200 + assert payload["annotationMutation"] is True + assert payload["effectPerformed"] is True + assert payload["desktopEffectPerformed"] is False + assert payload["executionAuthority"] is False + assert payload["outcome"]["note"]["revision"] == 2 + assert editor.calls[0]["status"] == "ACTIVE" + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_operator_note_post_rejects_extra_fields() -> None: + editor = FakeEditor() + server, thread = _server(editor) + try: + status, payload = _request( + server, + "POST", + "/api/v1/ghostwalk/operator-log/revisions", + { + "target_inference_receipt_sha256": "a" * 64, + "expected_current_revision_sha256": "c" * 64, + "body": "Correction.", + "status": "ACTIVE", + "author_id": "browser:should-not-control-this", + }, + ) + assert status == 400 + assert payload["effectPerformed"] is False + assert editor.calls == [] + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) From 75f477ae9a9bacef35b327b9e4dc197353315add Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:34:03 -0700 Subject: [PATCH 06/21] feat: add Ghost-Walk OperatorLog sidecar proxy --- phishell/host/ghostWalkOperatorLogProxy.mjs | 176 ++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 phishell/host/ghostWalkOperatorLogProxy.mjs diff --git a/phishell/host/ghostWalkOperatorLogProxy.mjs b/phishell/host/ghostWalkOperatorLogProxy.mjs new file mode 100644 index 00000000..b68a1ca9 --- /dev/null +++ b/phishell/host/ghostWalkOperatorLogProxy.mjs @@ -0,0 +1,176 @@ +import { ghostWalkSidecarPort, GHOSTWALK_HOST } from "./ghostWalkControlProxy.mjs"; + +const SHA256 = /^[0-9a-f]{64}$/; +const STATUSES = new Set(["ACTIVE", "RETRACTED"]); + +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 = 16384) { + 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 zeroAuthority(value) { + return ( + record(value) && + value.operationalAuthority === false && + value.actionAuthority === false && + value.executionAuthority === false + ); +} + +export function validateGhostWalkOperatorNote(value) { + return ( + zeroAuthority(value) && + value.schema_version === "phios.ghostwalk_operator_note.v0.28" && + sha(value.target_inference_receipt_sha256) && + boundedString(value.note_id, 512) && + integer(value.revision) && + sha(value.revision_sha256) && + boundedString(value.author_id, 512) && + boundedString(value.body, 16384) && + Array.isArray(value.tags) && + value.tags.length <= 64 && + value.tags.every((item) => boundedString(item, 128)) && + STATUSES.has(value.status) && + timestamp(value.created_at) && + nullableSha(value.supersedes_revision_sha256) && + boundedString(value.inference_status, 64) && + boundedString(value.session_id, 512) && + sha(value.action_observation_sha256) + ); +} + +function validTransportBase(value, { mutated }) { + return ( + zeroAuthority(value) && + value.transportSchemaVersion === "phios.ghostwalk-operator-log-transport.v0.28" && + value.transport === "loopback-http" && + value.transportIdentity === "phios-ghostwalk-operator-editor" && + value.localOnly === true && + value.annotationMutation === mutated && + value.desktopEffectPerformed === false && + value.effectPerformed === mutated && + timestamp(value.servedAt) + ); +} + +export function validateGhostWalkOperatorNoteEnvelope(value) { + return ( + validTransportBase(value, { mutated: false }) && + validateGhostWalkOperatorNote(value.note) + ); +} + +export function validateGhostWalkOperatorEditEnvelope(value) { + if (!validTransportBase(value, { mutated: true }) || !record(value.outcome)) { + return false; + } + return ( + value.outcome.result === "APPLIED" && + value.outcome.annotation_mutation === true && + value.outcome.desktop_effect_performed === false && + value.outcome.operational_authority === false && + value.outcome.action_authority === false && + value.outcome.execution_authority === false && + validateGhostWalkOperatorNote(value.outcome.note) + ); +} + +export function validateGhostWalkOperatorEditPayload(value) { + if (!record(value)) return false; + const keys = Object.keys(value).sort(); + const expected = [ + "body", + "expected_current_revision_sha256", + "status", + "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) && + boundedString(value.body, 16384) && + STATUSES.has(value.status) + ); +} + +export async function fetchGhostWalkOperatorNote(targetSha256, { + fetcher = globalThis.fetch.bind(globalThis), + port = ghostWalkSidecarPort(), + timeoutMs = 1500, +} = {}) { + if (!sha(targetSha256)) return null; + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + `http://${GHOSTWALK_HOST}:${port}/api/v1/ghostwalk/operator-log?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + headers: { accept: "application/json" }, + signal: controller.signal, + }, + ); + if (!response.ok) return null; + const payload = await response.json(); + return validateGhostWalkOperatorNoteEnvelope(payload) ? payload : null; + } catch { + return null; + } finally { + clearTimeout(timeout); + } +} + +export async function applyGhostWalkOperatorEdit(payload, { + fetcher = globalThis.fetch.bind(globalThis), + port = ghostWalkSidecarPort(), + timeoutMs = 2500, +} = {}) { + if (!validateGhostWalkOperatorEditPayload(payload)) return null; + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + `http://${GHOSTWALK_HOST}:${port}/api/v1/ghostwalk/operator-log/revisions`, + { + method: "POST", + cache: "no-store", + headers: { + accept: "application/json", + "content-type": "application/json", + }, + body: JSON.stringify(payload), + signal: controller.signal, + }, + ); + if (response.status === 409) return { kind: "conflict" }; + if (!response.ok) return null; + const result = await response.json(); + if (!validateGhostWalkOperatorEditEnvelope(result)) return null; + return { kind: "applied", envelope: result }; + } catch { + return null; + } finally { + clearTimeout(timeout); + } +} From b294ff2882e443425a5606f56d6c14a454b84fa9 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:34:05 -0700 Subject: [PATCH 07/21] test: validate Ghost-Walk OperatorLog proxy --- .../host/ghostWalkOperatorLogProxy.test.mjs | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 phishell/host/ghostWalkOperatorLogProxy.test.mjs diff --git a/phishell/host/ghostWalkOperatorLogProxy.test.mjs b/phishell/host/ghostWalkOperatorLogProxy.test.mjs new file mode 100644 index 00000000..a7e4fdf4 --- /dev/null +++ b/phishell/host/ghostWalkOperatorLogProxy.test.mjs @@ -0,0 +1,137 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + applyGhostWalkOperatorEdit, + fetchGhostWalkOperatorNote, + validateGhostWalkOperatorEditEnvelope, + validateGhostWalkOperatorEditPayload, + validateGhostWalkOperatorNoteEnvelope, +} from "./ghostWalkOperatorLogProxy.mjs"; + +const note = { + schema_version: "phios.ghostwalk_operator_note.v0.28", + target_inference_receipt_sha256: "a".repeat(64), + note_id: "ghostwalk-transition:" + "b".repeat(64), + revision: 2, + revision_sha256: "c".repeat(64), + author_id: "operator:local", + body: "Correction: opened network adapter properties.", + tags: ["ghostwalk", "operator-interpretation", "transition-inference"], + status: "ACTIVE", + created_at: "2026-09-27T06:31:00.000Z", + supersedes_revision_sha256: "d".repeat(64), + inference_status: "CANDIDATES", + session_id: "demo", + action_observation_sha256: "b".repeat(64), + operational_authority: false, + action_authority: false, + execution_authority: false, +}; + +const readEnvelope = { + transportSchemaVersion: "phios.ghostwalk-operator-log-transport.v0.28", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-operator-editor", + localOnly: true, + annotationMutation: false, + desktopEffectPerformed: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T06:31:00.000Z", + note, +}; + +const writeEnvelope = { + ...readEnvelope, + annotationMutation: true, + effectPerformed: true, + outcome: { + result: "APPLIED", + note, + annotation_mutation: true, + desktop_effect_performed: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + }, +}; +delete writeEnvelope.note; + +test("validates read-only OperatorLog projection", () => { + assert.equal(validateGhostWalkOperatorNoteEnvelope(readEnvelope), true); + assert.equal( + validateGhostWalkOperatorNoteEnvelope({ + ...readEnvelope, + actionAuthority: true, + }), + false, + ); +}); + +test("validates annotation write as a real persistent effect", () => { + assert.equal(validateGhostWalkOperatorEditEnvelope(writeEnvelope), true); + assert.equal( + validateGhostWalkOperatorEditEnvelope({ + ...writeEnvelope, + effectPerformed: false, + }), + false, + ); +}); + +test("edit payload excludes browser-controlled author identity", () => { + const payload = { + target_inference_receipt_sha256: "a".repeat(64), + expected_current_revision_sha256: "c".repeat(64), + body: "Human correction.", + status: "ACTIVE", + }; + assert.equal(validateGhostWalkOperatorEditPayload(payload), true); + assert.equal( + validateGhostWalkOperatorEditPayload({ + ...payload, + author_id: "browser:fake", + }), + false, + ); +}); + +test("fetches current operator note only after validation", async () => { + const fetcher = async () => ({ + ok: true, + async json() { + return readEnvelope; + }, + }); + assert.ok( + await fetchGhostWalkOperatorNote("a".repeat(64), { + fetcher, + port: 3973, + }), + ); +}); + +test("preserves stale-edit conflict signal", async () => { + const fetcher = async () => ({ + status: 409, + ok: false, + async json() { + return {}; + }, + }); + assert.deepEqual( + await applyGhostWalkOperatorEdit( + { + target_inference_receipt_sha256: "a".repeat(64), + expected_current_revision_sha256: "c".repeat(64), + body: "Human correction.", + status: "ACTIVE", + }, + { fetcher, port: 3973 }, + ), + { kind: "conflict" }, + ); +}); From 7d168c24613b90c3447428f20d52b36d9de64311 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:34:23 -0700 Subject: [PATCH 08/21] feat: proxy Ghost-Walk OperatorLog edits through PhiShell --- phishell/host/localTransport.mjs | 96 ++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/phishell/host/localTransport.mjs b/phishell/host/localTransport.mjs index 90226da6..c61ad37e 100644 --- a/phishell/host/localTransport.mjs +++ b/phishell/host/localTransport.mjs @@ -22,6 +22,11 @@ import { fetchGhostWalkStatus, validateGhostWalkActionPayload, } from "./ghostWalkControlProxy.mjs"; +import { + applyGhostWalkOperatorEdit, + fetchGhostWalkOperatorNote, + validateGhostWalkOperatorEditPayload, +} from "./ghostWalkOperatorLogProxy.mjs"; import { createPersistRequest, fetchBrokerHealth, @@ -118,6 +123,8 @@ export function createLocalObservationServer({ curiosityPersistRequestFetcher = fetchPersistRequest, ghostWalkStatusFetcher = fetchGhostWalkStatus, ghostWalkActionApplier = applyGhostWalkAction, + ghostWalkOperatorNoteFetcher = fetchGhostWalkOperatorNote, + ghostWalkOperatorEditApplier = applyGhostWalkOperatorEdit, } = {}) { if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new Error("local observation port must be an integer between 0 and 65535"); @@ -127,6 +134,61 @@ export function createLocalObservationServer({ try { const url = new URL(request.url ?? "/", `http://${LOOPBACK_HOST}`); + if ( + request.method === "POST" && + url.pathname === "/api/v1/ghostwalk/operator-log/revisions" + ) { + let payload; + try { + payload = await readBoundedJsonObject(request, { maxBytes: 32768 }); + } catch { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_operator_edit_body", + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + if (!validateGhostWalkOperatorEditPayload(payload)) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_operator_edit_request", + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + const result = await ghostWalkOperatorEditApplier(payload); + if (result?.kind === "conflict") { + jsonResponse(response, 409, { + error: "ghostwalk_operator_edit_conflict", + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "applied") { + jsonResponse(response, 503, { + error: "ghostwalk_operator_editor_unavailable", + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + jsonResponse(response, 200, result.envelope); + return; + } + if ( request.method === "POST" && url.pathname === "/api/v1/ghostwalk/actions" @@ -258,6 +320,40 @@ export function createLocalObservationServer({ return; } + if (url.pathname === "/api/v1/ghostwalk/operator-log") { + 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_operator_note_request", + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + const note = await ghostWalkOperatorNoteFetcher(target); + if (!note) { + jsonResponse(response, 503, { + error: "ghostwalk_operator_note_unavailable", + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + jsonResponse(response, 200, note); + return; + } + if (url.pathname === "/api/v1/ghostwalk") { if ([...url.searchParams.keys()].length !== 0) { jsonResponse(response, 400, { From 0297c1f0777bd7d67e04492f4d83c30a8d5aa960 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:34:49 -0700 Subject: [PATCH 09/21] test: cover PhiShell OperatorLog proxy routes --- ...hostWalkOperatorLogLocalTransport.test.mjs | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 phishell/host/ghostWalkOperatorLogLocalTransport.test.mjs diff --git a/phishell/host/ghostWalkOperatorLogLocalTransport.test.mjs b/phishell/host/ghostWalkOperatorLogLocalTransport.test.mjs new file mode 100644 index 00000000..1facb379 --- /dev/null +++ b/phishell/host/ghostWalkOperatorLogLocalTransport.test.mjs @@ -0,0 +1,181 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { createLocalObservationServer } from "./localTransport.mjs"; + +const noteEnvelope = { + transportSchemaVersion: "phios.ghostwalk-operator-log-transport.v0.28", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-operator-editor", + localOnly: true, + annotationMutation: false, + desktopEffectPerformed: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T06:31:00.000Z", + note: { + schema_version: "phios.ghostwalk_operator_note.v0.28", + target_inference_receipt_sha256: "a".repeat(64), + note_id: "ghostwalk-transition:" + "b".repeat(64), + revision: 1, + revision_sha256: "c".repeat(64), + author_id: "operator:local", + body: "Machine summary.", + tags: ["ghostwalk", "transition-inference"], + status: "ACTIVE", + created_at: "2026-09-27T06:30:00.000Z", + supersedes_revision_sha256: null, + inference_status: "CANDIDATES", + session_id: "demo", + action_observation_sha256: "b".repeat(64), + operational_authority: false, + action_authority: false, + execution_authority: false, + }, +}; + +const editEnvelope = { + ...noteEnvelope, + annotationMutation: true, + effectPerformed: true, + outcome: { + result: "APPLIED", + note: { + ...noteEnvelope.note, + revision: 2, + revision_sha256: "d".repeat(64), + body: "Correction: opened network adapter properties.", + tags: ["ghostwalk", "operator-interpretation", "transition-inference"], + supersedes_revision_sha256: "c".repeat(64), + }, + annotation_mutation: true, + desktop_effect_performed: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + }, +}; +delete editEnvelope.note; + +test("local transport proxies current OperatorLog revision", async () => { + let seenTarget = null; + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkOperatorNoteFetcher: async (target) => { + seenTarget = target; + return noteEnvelope; + }, + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/operator-log?target=${"a".repeat(64)}`, + ); + assert.equal(response.status, 200); + const payload = await response.json(); + assert.equal(payload.note.revision, 1); + assert.equal(payload.effectPerformed, false); + assert.equal(seenTarget, "a".repeat(64)); + } finally { + await transport.close(); + } +}); + +test("local transport proxies append-only OperatorLog edit", async () => { + const seen = []; + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkOperatorEditApplier: async (payload) => { + seen.push(payload); + return { kind: "applied", envelope: editEnvelope }; + }, + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/operator-log/revisions`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target_inference_receipt_sha256: "a".repeat(64), + expected_current_revision_sha256: "c".repeat(64), + body: "Correction: opened network adapter properties.", + status: "ACTIVE", + }), + }, + ); + assert.equal(response.status, 200); + const payload = await response.json(); + assert.equal(payload.effectPerformed, true); + assert.equal(payload.desktopEffectPerformed, false); + assert.equal(payload.outcome.note.revision, 2); + assert.equal(seen.length, 1); + } finally { + await transport.close(); + } +}); + +test("local transport preserves OperatorLog revision conflicts", async () => { + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkOperatorEditApplier: async () => ({ kind: "conflict" }), + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/operator-log/revisions`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target_inference_receipt_sha256: "a".repeat(64), + expected_current_revision_sha256: "c".repeat(64), + body: "Stale correction.", + status: "ACTIVE", + }), + }, + ); + assert.equal(response.status, 409); + } finally { + await transport.close(); + } +}); + +test("local transport rejects browser author injection", async () => { + let called = false; + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkOperatorEditApplier: async () => { + called = true; + return null; + }, + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/operator-log/revisions`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target_inference_receipt_sha256: "a".repeat(64), + expected_current_revision_sha256: "c".repeat(64), + body: "Correction.", + status: "ACTIVE", + author_id: "browser:fake", + }), + }, + ); + assert.equal(response.status, 400); + assert.equal(called, false); + } finally { + await transport.close(); + } +}); From f868690f40310be62cf7fe9c803da26d93e82106 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:35:58 -0700 Subject: [PATCH 10/21] feat: add typed Ghost-Walk OperatorLog client --- phishell/src/ghostwalk/operatorLog.ts | 247 ++++++++++++++++++++++++++ 1 file changed, 247 insertions(+) create mode 100644 phishell/src/ghostwalk/operatorLog.ts diff --git a/phishell/src/ghostwalk/operatorLog.ts b/phishell/src/ghostwalk/operatorLog.ts new file mode 100644 index 00000000..d0000c74 --- /dev/null +++ b/phishell/src/ghostwalk/operatorLog.ts @@ -0,0 +1,247 @@ +export type GhostWalkOperatorNoteStatus = "ACTIVE" | "RETRACTED"; + +export interface GhostWalkOperatorNote { + schema_version: "phios.ghostwalk_operator_note.v0.28"; + target_inference_receipt_sha256: string; + note_id: string; + revision: number; + revision_sha256: string; + author_id: string; + body: string; + tags: string[]; + status: GhostWalkOperatorNoteStatus; + created_at: string; + supersedes_revision_sha256: string | null; + inference_status: string; + session_id: string; + action_observation_sha256: string; + operational_authority: false; + action_authority: false; + execution_authority: false; +} + +export interface GhostWalkOperatorNoteEnvelope { + transportSchemaVersion: "phios.ghostwalk-operator-log-transport.v0.28"; + transport: "loopback-http"; + transportIdentity: "phios-ghostwalk-operator-editor"; + localOnly: true; + annotationMutation: false; + desktopEffectPerformed: false; + operationalAuthority: false; + actionAuthority: false; + executionAuthority: false; + effectPerformed: false; + servedAt: string; + note: GhostWalkOperatorNote; +} + +export interface GhostWalkOperatorEditEnvelope { + transportSchemaVersion: "phios.ghostwalk-operator-log-transport.v0.28"; + transport: "loopback-http"; + transportIdentity: "phios-ghostwalk-operator-editor"; + localOnly: true; + annotationMutation: true; + desktopEffectPerformed: false; + operationalAuthority: false; + actionAuthority: false; + executionAuthority: false; + effectPerformed: true; + servedAt: string; + outcome: { + result: "APPLIED"; + note: GhostWalkOperatorNote; + annotation_mutation: true; + desktop_effect_performed: false; + operational_authority: false; + action_authority: false; + execution_authority: false; + }; +} + +export type GhostWalkOperatorEditResult = + | { kind: "applied"; envelope: GhostWalkOperatorEditEnvelope } + | { kind: "conflict" } + | { kind: "unavailable" }; + +function record(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function sha(value: unknown): value is string { + return typeof value === "string" && /^[0-9a-f]{64}$/.test(value); +} + +function timestamp(value: unknown): value is string { + return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value)); +} + +function boundedString(value: unknown, maximum = 16384): value is string { + return typeof value === "string" && value.length > 0 && value.length <= maximum; +} + +function nullableSha(value: unknown): value is string | null { + return value === null || sha(value); +} + +export function isGhostWalkOperatorNote(value: unknown): value is GhostWalkOperatorNote { + if (!record(value)) return false; + return ( + value.schema_version === "phios.ghostwalk_operator_note.v0.28" && + sha(value.target_inference_receipt_sha256) && + boundedString(value.note_id, 512) && + typeof value.revision === "number" && + Number.isInteger(value.revision) && + value.revision >= 1 && + sha(value.revision_sha256) && + boundedString(value.author_id, 512) && + boundedString(value.body, 16384) && + Array.isArray(value.tags) && + value.tags.length <= 64 && + value.tags.every((tag) => boundedString(tag, 128)) && + (value.status === "ACTIVE" || value.status === "RETRACTED") && + timestamp(value.created_at) && + nullableSha(value.supersedes_revision_sha256) && + boundedString(value.inference_status, 64) && + boundedString(value.session_id, 512) && + sha(value.action_observation_sha256) && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false + ); +} + +function validBase( + value: unknown, + mutation: boolean, +): value is Record { + if (!record(value)) return false; + return ( + value.transportSchemaVersion === "phios.ghostwalk-operator-log-transport.v0.28" && + value.transport === "loopback-http" && + value.transportIdentity === "phios-ghostwalk-operator-editor" && + value.localOnly === true && + value.annotationMutation === mutation && + value.desktopEffectPerformed === false && + value.operationalAuthority === false && + value.actionAuthority === false && + value.executionAuthority === false && + value.effectPerformed === mutation && + timestamp(value.servedAt) + ); +} + +export function isGhostWalkOperatorNoteEnvelope( + value: unknown, +): value is GhostWalkOperatorNoteEnvelope { + return validBase(value, false) && isGhostWalkOperatorNote(value.note); +} + +export function isGhostWalkOperatorEditEnvelope( + value: unknown, +): value is GhostWalkOperatorEditEnvelope { + if (!validBase(value, true) || !record(value.outcome)) return false; + return ( + value.outcome.result === "APPLIED" && + value.outcome.annotation_mutation === true && + value.outcome.desktop_effect_performed === false && + value.outcome.operational_authority === false && + value.outcome.action_authority === false && + value.outcome.execution_authority === false && + isGhostWalkOperatorNote(value.outcome.note) + ); +} + +export function createGhostWalkOperatorLogClient({ + fetcher = globalThis.fetch.bind(globalThis), + timeoutMs = 2_500, +}: { + fetcher?: typeof fetch; + timeoutMs?: number; +} = {}) { + return { + async read(targetSha256: string): Promise { + if (!sha(targetSha256)) return null; + const controller = new AbortController(); + const timeout = globalThis.setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + `/api/v1/ghostwalk/operator-log?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + credentials: "same-origin", + headers: { accept: "application/json" }, + signal: controller.signal, + }, + ); + if (!response.ok) return null; + const payload: unknown = await response.json(); + return isGhostWalkOperatorNoteEnvelope(payload) ? payload.note : null; + } catch { + return null; + } finally { + globalThis.clearTimeout(timeout); + } + }, + + async edit({ + targetSha256, + expectedRevisionSha256, + body, + status, + }: { + targetSha256: string; + expectedRevisionSha256: string; + body: string; + status: GhostWalkOperatorNoteStatus; + }): Promise { + if ( + !sha(targetSha256) || + !sha(expectedRevisionSha256) || + !boundedString(body, 16384) || + !["ACTIVE", "RETRACTED"].includes(status) + ) { + return { kind: "unavailable" }; + } + + const controller = new AbortController(); + const timeout = globalThis.setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + "/api/v1/ghostwalk/operator-log/revisions", + { + method: "POST", + cache: "no-store", + credentials: "same-origin", + headers: { + accept: "application/json", + "content-type": "application/json", + }, + body: JSON.stringify({ + target_inference_receipt_sha256: targetSha256, + expected_current_revision_sha256: expectedRevisionSha256, + body, + status, + }), + signal: controller.signal, + }, + ); + if (response.status === 409) return { kind: "conflict" }; + if (!response.ok) return { kind: "unavailable" }; + + const payload: unknown = await response.json(); + if (!isGhostWalkOperatorEditEnvelope(payload)) { + return { kind: "unavailable" }; + } + return { kind: "applied", envelope: payload }; + } catch { + return { kind: "unavailable" }; + } finally { + globalThis.clearTimeout(timeout); + } + }, + }; +} + +export const ghostWalkOperatorLogClient = + createGhostWalkOperatorLogClient(); From 16d2ced97b325592e3438ce046259ea74f23525e Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:36:00 -0700 Subject: [PATCH 11/21] test: cover Ghost-Walk OperatorLog browser client --- phishell/src/ghostwalk/operatorLog.test.ts | 134 +++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 phishell/src/ghostwalk/operatorLog.test.ts diff --git a/phishell/src/ghostwalk/operatorLog.test.ts b/phishell/src/ghostwalk/operatorLog.test.ts new file mode 100644 index 00000000..9bab5522 --- /dev/null +++ b/phishell/src/ghostwalk/operatorLog.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it, vi } from "vitest"; +import { + createGhostWalkOperatorLogClient, + isGhostWalkOperatorEditEnvelope, + isGhostWalkOperatorNoteEnvelope, +} from "./operatorLog"; + +const note = { + schema_version: "phios.ghostwalk_operator_note.v0.28", + target_inference_receipt_sha256: "a".repeat(64), + note_id: "ghostwalk-transition:" + "b".repeat(64), + revision: 2, + revision_sha256: "c".repeat(64), + author_id: "operator:local", + body: "Correction: opened network adapter properties.", + tags: ["ghostwalk", "operator-interpretation", "transition-inference"], + status: "ACTIVE", + created_at: "2026-09-27T06:31:00.000Z", + supersedes_revision_sha256: "d".repeat(64), + inference_status: "CANDIDATES", + session_id: "demo", + action_observation_sha256: "b".repeat(64), + operational_authority: false, + action_authority: false, + execution_authority: false, +} as const; + +const readEnvelope = { + transportSchemaVersion: "phios.ghostwalk-operator-log-transport.v0.28", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-operator-editor", + localOnly: true, + annotationMutation: false, + desktopEffectPerformed: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T06:31:00.000Z", + note, +} as const; + +const writeEnvelope = { + transportSchemaVersion: "phios.ghostwalk-operator-log-transport.v0.28", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-operator-editor", + localOnly: true, + annotationMutation: true, + desktopEffectPerformed: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: true, + servedAt: "2026-09-27T06:31:00.000Z", + outcome: { + result: "APPLIED", + note, + annotation_mutation: true, + desktop_effect_performed: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + }, +} as const; + +describe("Ghost-Walk OperatorLog browser client", () => { + it("validates read and write envelopes separately", () => { + expect(isGhostWalkOperatorNoteEnvelope(readEnvelope)).toBe(true); + expect(isGhostWalkOperatorEditEnvelope(writeEnvelope)).toBe(true); + expect( + isGhostWalkOperatorEditEnvelope({ + ...writeEnvelope, + effectPerformed: false, + }), + ).toBe(false); + }); + + it("reads the note by exact inference receipt", async () => { + const fetcher = vi.fn(async () => + new Response(JSON.stringify(readEnvelope), { + status: 200, + headers: { "content-type": "application/json" }, + }), + ); + const client = createGhostWalkOperatorLogClient({ + fetcher: fetcher as typeof fetch, + }); + const current = await client.read("a".repeat(64)); + expect(current?.revision).toBe(2); + }); + + it("posts no browser-controlled author identity", async () => { + const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { + const body = JSON.parse(String(init?.body)); + expect(body).toEqual({ + target_inference_receipt_sha256: "a".repeat(64), + expected_current_revision_sha256: "c".repeat(64), + body: "Human correction.", + status: "ACTIVE", + }); + expect("author_id" in body).toBe(false); + return new Response(JSON.stringify(writeEnvelope), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }); + const client = createGhostWalkOperatorLogClient({ + fetcher: fetcher as typeof fetch, + }); + await expect( + client.edit({ + targetSha256: "a".repeat(64), + expectedRevisionSha256: "c".repeat(64), + body: "Human correction.", + status: "ACTIVE", + }), + ).resolves.toMatchObject({ kind: "applied" }); + }); + + it("preserves 409 as revision conflict", async () => { + const fetcher = vi.fn(async () => new Response("", { status: 409 })); + const client = createGhostWalkOperatorLogClient({ + fetcher: fetcher as typeof fetch, + }); + await expect( + client.edit({ + targetSha256: "a".repeat(64), + expectedRevisionSha256: "c".repeat(64), + body: "Human correction.", + status: "ACTIVE", + }), + ).resolves.toEqual({ kind: "conflict" }); + }); +}); From 424d527850fca586d6724b81825090f65e036d1f Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Sat, 26 Sep 2026 23:36:03 -0700 Subject: [PATCH 12/21] feat: add Ghost-Walk interpretation editor --- .../components/GhostWalkOperatorEditor.tsx | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 phishell/src/components/GhostWalkOperatorEditor.tsx diff --git a/phishell/src/components/GhostWalkOperatorEditor.tsx b/phishell/src/components/GhostWalkOperatorEditor.tsx new file mode 100644 index 00000000..1752c26c --- /dev/null +++ b/phishell/src/components/GhostWalkOperatorEditor.tsx @@ -0,0 +1,146 @@ +import { useCallback, useEffect, useState } from "react"; +import { + ghostWalkOperatorLogClient, + type GhostWalkOperatorNote, + type GhostWalkOperatorNoteStatus, +} from "../ghostwalk/operatorLog"; + +function shortHash(value: string) { + return `${value.slice(0, 10)}…`; +} + +export function GhostWalkOperatorEditor({ + targetSha256, + onClose, + onSaved, +}: { + targetSha256: string; + onClose: () => void; + onSaved: () => void; +}) { + const [note, setNote] = useState(null); + const [body, setBody] = useState(""); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); + + const load = useCallback(async () => { + setLoading(true); + try { + const current = await ghostWalkOperatorLogClient.read(targetSha256); + setNote(current); + if (current) { + setBody(current.body); + setMessage(null); + } else { + setMessage("Current OperatorLog revision is unavailable or failed validation."); + } + } finally { + setLoading(false); + } + }, [targetSha256]); + + useEffect(() => { + void load(); + }, [load]); + + const save = useCallback( + async (status: GhostWalkOperatorNoteStatus) => { + if (!note || !body.trim()) return; + setBusy(true); + setMessage(null); + try { + const result = await ghostWalkOperatorLogClient.edit({ + targetSha256, + expectedRevisionSha256: note.revision_sha256, + body: body.trim(), + status, + }); + if (result.kind === "conflict") { + setMessage( + "Revision conflict: this interpretation changed after you loaded it. Your draft is preserved; reload the current revision before saving.", + ); + return; + } + if (result.kind === "unavailable") { + setMessage("The governed OperatorLog editor rejected or could not validate the edit."); + return; + } + const next = result.envelope.outcome.note; + setNote(next); + setBody(next.body); + setMessage( + `Saved revision ${next.revision} as ${next.status}. Original inference evidence was not modified.`, + ); + onSaved(); + } finally { + setBusy(false); + } + }, + [body, note, onSaved, targetSha256], + ); + + return ( +
+
+
+ OPERATOR INTERPRETATION + {shortHash(targetSha256)} +
+ +
+ + {loading ? ( +
Loading current append-only revision…
+ ) : note ? ( + <> +
+ revision {note.revision} + {note.status} + {note.author_id} + {shortHash(note.revision_sha256)} +
+ +