diff --git a/docs/MACRO_RUNTIME_V0.28.md b/docs/MACRO_RUNTIME_V0.28.md new file mode 100644 index 00000000..47aed14f --- /dev/null +++ b/docs/MACRO_RUNTIME_V0.28.md @@ -0,0 +1,279 @@ +# Macro Runtime v0.28 — Governed Ghost-Walk OperatorLog Editor + +v0.28 gives the human operator a real editing surface for Ghost-Walk's +machine-generated interpretation notes while preserving the underlying +transition inference as immutable evidence. + +The central rule is: + +```text +HUMAN INTERPRETATION +!= +MACHINE INFERENCE +``` + +Saving a correction appends a new OperatorLog revision. It never rewrites the +transition-inference receipt and never grants desktop execution authority. + +## Existing foundation + +Ghost-Walk already publishes one editable OperatorLog note after a successful +transition inference: + +```text +immutable transition inference receipt + | + v +OperatorLog revision 1 +machine-generated human-editable summary +``` + +The original OperatorLog contract already provides: + +- append-only revisions +- revision SHA-256 +- supersedes-revision linkage +- optimistic concurrency through expected-current revision hash +- ACTIVE / RETRACTED status +- zero operational/action/execution authority +- tamper detection for the revision chain + +v0.28 exposes those semantics safely to PhiShell. + +## Architecture + +```text +Ghost-Walk transition inference + | + | immutable receipt SHA + v +OperatorLog revision chain + | + v +GhostWalkOperatorEditor + | + | serialized edit transaction + v +Ghost-Walk loopback sidecar :3973 + | + | validated proxy + v +PhiShell local transport :3969 + | + v +typed browser client + | + v +System Inspector interpretation editor +``` + +## Exact target binding + +Edits are bound to: + +```text +target_inference_receipt_sha256 +``` + +not UI row numbers, candidate labels, text descriptions, or current window +coordinates. + +Before an edit is accepted, the editor: + +1. looks up the exact transition inference receipt +2. recomputes its canonical SHA-256 +3. rejects tampered inference evidence +4. locates exactly one OperatorLog chain targeting that receipt +5. validates the OperatorLog chain +6. checks the browser-supplied expected-current revision SHA +7. appends one new revision + +The source inference is never modified. + +## Concurrency + +The sidecar uses a lock around: + +```text +read current revision + + +verify expected-current SHA + + +append next revision +``` + +So two simultaneous edits based on the same revision cannot both become the +next revision. + +Expected behavior: + +```text +editor A: expected r1 -> APPLIED as r2 +editor B: expected r1 -> 409 CONFLICT +``` + +The browser preserves the operator's unsaved draft on conflict and asks for an +explicit reload of the latest revision. + +## Operator identity + +The browser does not supply `author_id`. + +The sidecar owns the configured local operator identity: + +```text +operator:local +``` + +Browser attempts to add an `author_id` field fail request validation. + +This prevents UI code from relabeling an annotation as another operator. + +## Sidecar endpoints + +Read current annotation: + +```http +GET /api/v1/ghostwalk/operator-log?target= +``` + +Append a revision: + +```http +POST /api/v1/ghostwalk/operator-log/revisions +``` + +Request body: + +```json +{ + "target_inference_receipt_sha256": "...", + "expected_current_revision_sha256": "...", + "body": "Correction: I opened network adapter properties.", + "status": "ACTIVE" +} +``` + +Allowed status values: + +```text +ACTIVE +RETRACTED +``` + +Retraction is another append-only revision. It does not erase prior text. + +## Effect semantics + +Reading a note: + +```text +annotationMutation = false +effectPerformed = false +desktopEffectPerformed = false +``` + +Saving a revision: + +```text +annotationMutation = true +effectPerformed = true +desktopEffectPerformed = false +``` + +The persistent OperatorLog append is a real filesystem effect, so v0.28 does +not pretend otherwise. + +However, both read and write envelopes retain: + +```text +operationalAuthority = false +actionAuthority = false +executionAuthority = false +``` + +An annotation write is not desktop automation authority. + +## PhiShell UI + +Each recent learned transition now exposes: + +```text +EDIT NOTE rN +``` + +Selecting it opens a bounded editor showing: + +- exact target inference digest +- current revision number +- current revision digest +- note author +- ACTIVE / RETRACTED state +- full current interpretation text + +The operator may: + +- append a new ACTIVE revision +- append a RETRACTED revision +- reload the current revision +- close without changing anything + +The editor states explicitly: + +```text +HUMAN INTERPRETATION != MACHINE INFERENCE +SAVE APPENDS +SOURCE RECEIPT IMMUTABLE +EXECUTION AUTHORITY FALSE +``` + +## Fail-closed behavior + +v0.28 rejects: + +- unknown inference receipt +- tampered inference receipt +- malformed OperatorLog identity +- ambiguous note chains +- tampered revision chain +- stale expected-current revision +- extra browser fields +- browser-controlled author identity +- malformed SHA-256 values +- oversized or invalid note bodies +- non-zero authority evidence returned through proxies + +## Tests + +Coverage includes: + +- exact inference-to-note binding +- canonical inference hash verification +- append-only correction +- retraction as revision +- stale-edit rejection +- simultaneous-edit serialization +- unknown target rejection +- tampered inference rejection +- loopback GET projection +- loopback POST append +- browser author-injection rejection +- Node proxy validation +- 409 conflict preservation +- browser client envelope validation +- browser client omission of author identity + +## Next rung + +v0.29 should let the human classify a corrected interpretation into a small, +typed accepted-intent vocabulary without collapsing the distinction between: + +```text +machine candidate +human annotation +accepted intent +execution policy +``` + +Those should remain separate governed layers rather than one increasingly +confident blob of text. diff --git a/phios/macro_ghostwalk_control_server.py b/phios/macro_ghostwalk_control_server.py index 9c12528b..20fb767f 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,7 +357,20 @@ def _error( body.update({"error": code, "servedAt": _utc_now()}) self._json(status, body) - def _read_json(self) -> object: + 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, + *, + max_bytes: int = MAX_REQUEST_BYTES, + ) -> object: raw_length = self.headers.get("content-length") if raw_length is None: raise GhostWalkControlBridgeError( @@ -212,7 +382,7 @@ def _read_json(self) -> object: raise GhostWalkControlBridgeError( "content-length must be an integer" ) from exc - if length < 1 or length > MAX_REQUEST_BYTES: + if length < 1 or length > max_bytes: raise GhostWalkControlBridgeError( "request body length is outside the allowed bound" ) @@ -230,6 +400,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 +460,51 @@ 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(max_bytes=32768) + ) + ) + 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 +551,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 +559,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 +642,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, ) diff --git a/phios/macro_ghostwalk_operator_editor.py b/phios/macro_ghostwalk_operator_editor.py new file mode 100644 index 00000000..da1852cf --- /dev/null +++ b/phios/macro_ghostwalk_operator_editor.py @@ -0,0 +1,414 @@ +"""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 hashlib +import json +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 _canonical_sha256(value: object) -> str: + try: + encoded = json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode("utf-8") + except (TypeError, ValueError) as exc: + raise GhostWalkOperatorEditorError( + "transition inference payload must be canonical JSON" + ) from exc + return hashlib.sha256(encoded).hexdigest() + + +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" + ) + claimed = _require_sha256( + row.get("receipt_sha256"), + "inference_receipt_sha256", + ) + body = dict(row) + del body["receipt_sha256"] + if _canonical_sha256(body) != claimed: + raise GhostWalkOperatorEditorError( + "transition inference receipt hash mismatch" + ) + 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: set[str] = set() + for row in rows: + raw_note_id = row.get("note_id") + if not isinstance(raw_note_id, str) or not raw_note_id: + raise GhostWalkOperatorEditorError( + "transition inference has malformed operator-note identity" + ) + note_ids.add(raw_note_id) + 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, + ) 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", 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(); + } +}); diff --git a/phishell/host/ghostWalkOperatorLogProxy.mjs b/phishell/host/ghostWalkOperatorLogProxy.mjs new file mode 100644 index 00000000..a13c0aba --- /dev/null +++ b/phishell/host/ghostWalkOperatorLogProxy.mjs @@ -0,0 +1,185 @@ +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 + ); +} + +function zeroSnakeAuthority(value) { + return ( + record(value) && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false + ); +} + +export function validateGhostWalkOperatorNote(value) { + return ( + zeroSnakeAuthority(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); + } +} 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" }, + ); +}); 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, { diff --git a/phishell/src/components/GhostWalkControlPanel.tsx b/phishell/src/components/GhostWalkControlPanel.tsx index 93241835..bb53da2f 100644 --- a/phishell/src/components/GhostWalkControlPanel.tsx +++ b/phishell/src/components/GhostWalkControlPanel.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useState } from "react"; +import { GhostWalkOperatorEditor } from "./GhostWalkOperatorEditor"; import { ghostWalkControlClient, type GhostWalkAction, @@ -19,6 +20,7 @@ export function GhostWalkControlPanel() { const [busy, setBusy] = useState(false); const [unavailable, setUnavailable] = useState(false); const [lastResult, setLastResult] = useState(null); + const [selectedInference, setSelectedInference] = useState(null); const refresh = useCallback(async () => { const next = await ghostWalkControlClient.status(); @@ -199,16 +201,27 @@ export function GhostWalkControlPanel() { {transition.status} {new Date(transition.inferred_at).toLocaleTimeString()} - + )) )} + {selectedInference && ( + setSelectedInference(null)} + onSaved={() => void refresh()} + /> + )} +
RECENT HOLDS / FAILURES
{snapshot.recent_issues.length === 0 ? ( 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)} +
+ +