diff --git a/loopx/capabilities/content_ops/media.py b/loopx/capabilities/content_ops/media.py index c643751e38..a86b63f83d 100644 --- a/loopx/capabilities/content_ops/media.py +++ b/loopx/capabilities/content_ops/media.py @@ -226,14 +226,14 @@ def _execute(self, composition_id: str, attempt: str) -> None: if binding.binding is None: raise ValueError("Provider unavailable") checked = _owner("plan", {"plan": record["plan"]}) - result = execute_extension_runtime_binding(binding.binding, request={"protocol": PROTOCOL, + raw_result = execute_extension_runtime_binding(binding.binding, request={"protocol": PROTOCOL, "plan": record["plan"], "layout_style": checked["layout_style"], "plan_digest": record["plan_digest"], "frame_count": record["frame_count"], "sources": record["sources"], "attempt_directory": str(_safe_path(bundle, attempt)), "cancel_file": str(cancel)}) spatial = [{"id": shot["id"], "frames": round(shot["seconds"] * record["plan"]["fps"])} for shot in record["plan"]["shots"] if shot["kind"] == "blender"] full_frame = [shot["id"] for shot in record["plan"]["shots"] if shot.get("framing") == "full_frame"] - result = _owner("result", {"result": result, "plan_digest": record["plan_digest"], + result = _owner("result", {"result": raw_result, "plan_digest": record["plan_digest"], "frame_count": record["frame_count"], "narration_mode": record["plan"]["narration"]["mode"], **({"blender_shots": spatial} if spatial else {}), **({"full_frame_shots": full_frame} if full_frame else {}), diff --git a/loopx/extensions/capability_admission.py b/loopx/extensions/capability_admission.py index ffd93859a4..9dc060657b 100644 --- a/loopx/extensions/capability_admission.py +++ b/loopx/extensions/capability_admission.py @@ -125,7 +125,7 @@ def resolve_external_capability_binding( f"multiple enabled, doctor-ready external providers expose " f"`{capability_id}`: {providers}" ) - extension_id, capability, profile = matches[0] + extension_id, matched_capability, profile = matches[0] operation_profile = _operation_from_profile(profile, operation) permission = _token( operation_profile.get("required_permission"), @@ -143,7 +143,7 @@ def resolve_external_capability_binding( "capability_id": capability_id, "operation": deepcopy(operation_profile), "integration_profile_digest": _token( - capability.get("integration_profile_digest"), + matched_capability.get("integration_profile_digest"), "external capability integration_profile_digest", ), } diff --git a/loopx/extensions/lark/goal_channel_operation.py b/loopx/extensions/lark/goal_channel_operation.py index 21c104e45b..e052ebbf60 100644 --- a/loopx/extensions/lark/goal_channel_operation.py +++ b/loopx/extensions/lark/goal_channel_operation.py @@ -722,12 +722,14 @@ def _resolve_operation_executor_binding( ) if not isinstance(executor, Mapping): raise ValueError("operation executor binding is unavailable") - return resolve_extension_binding( - str(executor["extension_id"]), - state_file=default_extension_state_file(runtime_root), - capability_id=OPERATION_EXECUTOR_CAPABILITY_ID, - protocol=str(executor["protocol"]), - permission=str(executor["permission"]), + return dict( + resolve_extension_binding( + str(executor["extension_id"]), + state_file=default_extension_state_file(runtime_root), + capability_id=OPERATION_EXECUTOR_CAPABILITY_ID, + protocol=str(executor["protocol"]), + permission=str(executor["permission"]), + ) ) diff --git a/loopx/extensions/runtime.py b/loopx/extensions/runtime.py index d44a4a1b1a..e5636d0e45 100644 --- a/loopx/extensions/runtime.py +++ b/loopx/extensions/runtime.py @@ -1,1189 +1,75 @@ +"""Lifecycle-gated extension execution and stable runtime facade.""" + from __future__ import annotations -import hashlib +from collections.abc import Mapping import json import math -import os -from collections.abc import Iterable, Mapping, Sequence -from contextlib import nullcontext -from copy import deepcopy -from dataclasses import dataclass from pathlib import Path -from typing import Any -from ..file_lock import exclusive_file_lock -from ..paths import select_default_runtime_root -from .manifest import load_extension_manifest, loopx_api_incompatibility -from .process_runtime import run_capped_process -from .runtime_location import located_runtime, probe_runtime_location, record_runtime_location -from .readiness import ( - EXTENSION_DOCTOR_SCHEMA_VERSION, - ResolvedRuntimeEntrypoint, - declared_view_validators, - extension_runtime, - resolve_runtime_entrypoint, - runtime_process_environment, +from .process_runtime import run_capped_process as run_capped_process +from .readiness import runtime_process_environment +from .runtime_bindings import ( + _capability_binding_from_entry as _capability_binding_from_entry, + _matching_capability_implementations as _matching_capability_implementations, + _optional_binding_for_entry as _optional_binding_for_entry, + _optional_binding_resolution as _optional_binding_resolution, + resolve_capability_binding as resolve_capability_binding, + resolve_capability_extension_id as resolve_capability_extension_id, + resolve_extension_activation as resolve_extension_activation, + resolve_extension_binding as resolve_extension_binding, + resolve_extension_runtime_binding as resolve_extension_runtime_binding, + resolve_optional_capability_binding as resolve_optional_capability_binding, +) +from .runtime_lifecycle import ( + disable_extension as disable_extension, + doctor_enabled_extensions as doctor_enabled_extensions, + doctor_installed_extension as doctor_installed_extension, + enable_extension as enable_extension, + extension_catalog_entries as extension_catalog_entries, + extension_status as extension_status, + install_extension as install_extension, + rollback_extension as rollback_extension, +) +from .runtime_state import ( + EXTENSION_ACTIVATION_SCHEMA_VERSION as EXTENSION_ACTIVATION_SCHEMA_VERSION, + EXTENSION_BINDING_SCHEMA_VERSION as EXTENSION_BINDING_SCHEMA_VERSION, + EXTENSION_DISABLED_STATUS as EXTENSION_DISABLED_STATUS, + EXTENSION_DOCTOR_BATCH_SCHEMA_VERSION as EXTENSION_DOCTOR_BATCH_SCHEMA_VERSION, + EXTENSION_DOCTOR_NOT_READY_STATUS as EXTENSION_DOCTOR_NOT_READY_STATUS, + EXTENSION_OPERATION_SCHEMA_VERSION as EXTENSION_OPERATION_SCHEMA_VERSION, + EXTENSION_PROVIDER_READINESS_SCHEMA_VERSION as EXTENSION_PROVIDER_READINESS_SCHEMA_VERSION, + EXTENSION_RUN_SCHEMA_VERSION as EXTENSION_RUN_SCHEMA_VERSION, + EXTENSION_STATE_SCHEMA_VERSION as EXTENSION_STATE_SCHEMA_VERSION, + MAX_EXTENSION_REQUEST_BYTES as MAX_EXTENSION_REQUEST_BYTES, + MAX_EXTENSION_RESPONSE_BYTES as MAX_EXTENSION_RESPONSE_BYTES, + MAX_REVISIONS as MAX_REVISIONS, + MAX_VERIFIED_ENTRYPOINTS as MAX_VERIFIED_ENTRYPOINTS, + ExtensionCapabilityResolution as ExtensionCapabilityResolution, + ExtensionCatalogEntry as ExtensionCatalogEntry, + ExtensionHookAdapterEntry as ExtensionHookAdapterEntry, + ExtensionRuntimeBinding as ExtensionRuntimeBinding, + _active_manifest as _active_manifest, + _active_manifest_incompatibility as _active_manifest_incompatibility, + _coerce_object_dict, + _empty_state as _empty_state, + _entry_for_revision as _entry_for_revision, + _manifest_snapshot as _manifest_snapshot, + _read_state as _read_state, + _record_doctor as _record_doctor, + _resolved_active_extension as _resolved_active_extension, + _retain_revisions as _retain_revisions, + _revision as _revision, + _runtime as _runtime, + _verified_entrypoint as _verified_entrypoint, + _verified_identities as _verified_identities, + _write_state as _write_state, + default_extension_state_file as default_extension_state_file, ) - -EXTENSION_STATE_SCHEMA_VERSION = "loopx_extension_state_v0" -EXTENSION_OPERATION_SCHEMA_VERSION = "loopx_extension_operation_v0" -EXTENSION_BINDING_SCHEMA_VERSION = "loopx_extension_runtime_binding_v0" -EXTENSION_PROVIDER_READINESS_SCHEMA_VERSION = "loopx_extension_provider_readiness_v0" -EXTENSION_ACTIVATION_SCHEMA_VERSION = "loopx_extension_activation_v0" -EXTENSION_RUN_SCHEMA_VERSION = "loopx_extension_run_receipt_v0" -EXTENSION_DOCTOR_BATCH_SCHEMA_VERSION = "loopx_extension_doctor_batch_v0" -# Content-free lifecycle non-admission codes. Optional capability resolution -# reports them as `ExtensionCapabilityResolution.status`; hook-adapter discovery -# reuses them for declared adapters whose extension it does not activate. -EXTENSION_DISABLED_STATUS = "extension_disabled" -EXTENSION_DOCTOR_NOT_READY_STATUS = "extension_doctor_not_ready" -MAX_REVISIONS = 5 -# Requalification is required on eviction; unprobed artifacts never activate. -MAX_VERIFIED_ENTRYPOINTS = 32 -MAX_EXTENSION_REQUEST_BYTES = 1_000_000 -MAX_EXTENSION_RESPONSE_BYTES = 1_000_000 - - -@dataclass(frozen=True) -class ExtensionCapabilityResolution: - """One atomic lifecycle/readiness snapshot for an optional provider.""" - - status: str - extension_id: str | None - installed: bool | None - enabled: bool | None - doctor_verified: bool | None - next_action: str | None - binding: Mapping[str, Any] | None = None - - def __post_init__(self) -> None: - if (self.status == "ready") != (self.binding is not None): - raise ValueError( - "a ready extension capability resolution requires exactly one binding" - ) - - def public_readiness(self) -> dict[str, Any]: - return { - "schema_version": EXTENSION_PROVIDER_READINESS_SCHEMA_VERSION, - "status": self.status, - "extension_id": self.extension_id, - "installed": self.installed, - "enabled": self.enabled, - "doctor_verified": self.doctor_verified, - "next_action": self.next_action, - } - - -def default_extension_state_file(runtime_root: str | Path | None = None) -> Path: - root = ( - Path(runtime_root).expanduser() - if runtime_root is not None - else select_default_runtime_root() - ) - return root / "extensions" / "state.json" - - -def _empty_state() -> dict[str, Any]: - return { - "schema_version": EXTENSION_STATE_SCHEMA_VERSION, - "extensions": {}, - } - - -def _read_state(path: Path) -> dict[str, Any]: - if not path.exists(): - return _empty_state() - try: - payload = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: - raise ValueError("extension runtime state is unreadable") from exc - if ( - not isinstance(payload, dict) - or payload.get("schema_version") != EXTENSION_STATE_SCHEMA_VERSION - or not isinstance(payload.get("extensions"), dict) - ): - raise ValueError( - f"extension runtime state must use {EXTENSION_STATE_SCHEMA_VERSION}" - ) - return payload - - -def _write_state(path: Path, payload: Mapping[str, Any]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}") - temporary.write_text( - json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n", - encoding="utf-8", - ) - temporary.chmod(0o600) - os.replace(temporary, path) - - -def _revision(manifest: Mapping[str, Any]) -> str: - serialized = json.dumps( - manifest, - ensure_ascii=False, - sort_keys=True, - separators=(",", ":"), - ) - return hashlib.sha256(serialized.encode("utf-8")).hexdigest()[:16] - - -def _runtime(manifest: Mapping[str, Any]) -> Mapping[str, Any]: - return extension_runtime(manifest) - - -def _manifest_snapshot(manifest: Mapping[str, Any]) -> dict[str, Any]: - return deepcopy(dict(manifest)) - - -def _entry_for_revision(entry: Mapping[str, Any], revision: str) -> dict[str, Any]: - revisions = entry.get("revisions") - if not isinstance(revisions, list): - raise ValueError("extension revision history is invalid") - for item in revisions: - if isinstance(item, dict) and item.get("revision") == revision: - return item - raise ValueError("extension active revision is missing") - - -def _retain_revisions( - revisions: list[dict[str, Any]], - new_revision: dict[str, Any], - *, - required_revision: str | None, -) -> list[dict[str, Any]]: - deduplicated = [ - item - for item in revisions - if item.get("revision") != new_revision.get("revision") - ] - required = next( - ( - item - for item in deduplicated - if required_revision and item.get("revision") == required_revision - ), - None, - ) - retained = [*deduplicated, new_revision][-MAX_REVISIONS:] - if required is not None and required not in retained: - retained = [required, *retained[-(MAX_REVISIONS - 1) :]] - return retained - - -def _verified_identities(entry: Mapping[str, Any], revision: str) -> list[str]: - if entry.get("doctor_verified_revision") != revision: - return [] - identities = entry.get("doctor_verified_entrypoint_identities") - if identities is None: - # Read legacy state without rewriting it during status/activation. - identities = [entry.get("doctor_verified_entrypoint_identity")] - if not isinstance(identities, list): - return [] - return list(dict.fromkeys( - identity for identity in identities if isinstance(identity, str) and identity - ))[-MAX_VERIFIED_ENTRYPOINTS:] - - -def _record_doctor(entry: dict[str, Any], revision: str, doctor: Mapping[str, Any]) -> None: - identities = _verified_identities(entry, revision) - identity = doctor.get("probed_entrypoint_identity") - if doctor.get("verified") is True: - identity = doctor.get("entrypoint_identity") - if isinstance(identity, str) and identity: - identities = [value for value in identities if value != identity] - if doctor.get("verified") is True: - identities.append(identity) - entry.pop("doctor_verified_entrypoint_identity", None) - if identities: - entry["doctor_verified_revision"] = revision - entry["doctor_verified_entrypoint_identities"] = identities[-MAX_VERIFIED_ENTRYPOINTS:] - else: - entry.pop("doctor_verified_revision", None) - entry.pop("doctor_verified_entrypoint_identities", None) - - -def install_extension( - manifest_path: str | Path, - *, - state_file: str | Path, - operation: str = "install", - execute: bool = False, -) -> dict[str, Any]: - if operation not in {"install", "upgrade"}: - raise ValueError("extension operation must be install or upgrade") - manifest = load_extension_manifest(manifest_path) - _runtime(manifest) - provider = manifest["provider"] - extension_id = str(provider["id"]) - revision = _revision(manifest) - doctor, location = probe_runtime_location(manifest, execute=execute) - if execute and not doctor["verified"]: - raise ValueError( - f"extension `{extension_id}` doctor is not ready: {doctor['status']}" - ) - path = Path(state_file).expanduser() - changed = False - lock = exclusive_file_lock(path) if execute else nullcontext() - with lock: - state = _read_state(path) - extensions = state["extensions"] - existing = extensions.get(extension_id) - if operation == "install" and existing is not None: - raise ValueError(f"extension `{extension_id}` is already installed") - if operation == "upgrade" and not isinstance(existing, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - if isinstance(existing, dict) and existing.get("active_revision") == revision: - raise ValueError(f"extension `{extension_id}` revision is already active") - previous_revision = ( - str(existing.get("active_revision")) if isinstance(existing, dict) else None - ) - # A fresh install activates the provider. An upgrade changes only the - # active revision; the operator's enable/disable decision is separate - # state and survives the revision change. - enabled = bool(existing.get("enabled")) if isinstance(existing, dict) else True - if execute: - revisions = ( - list(existing.get("revisions") or []) - if isinstance(existing, dict) - else [] - ) - revisions = _retain_revisions( - revisions, - { - "revision": revision, - "version": provider["version"], - "manifest": _manifest_snapshot(manifest), - **({"entrypoint_path": location} if location is not None else {}), - }, - required_revision=previous_revision, - ) - extensions[extension_id] = { - "id": extension_id, - "enabled": enabled, - "active_revision": revision, - "rollback_revision": previous_revision, - "revisions": revisions, - } - _record_doctor(extensions[extension_id], revision, doctor) - _write_state(path, state) - changed = True - return { - "ok": True, - "schema_version": EXTENSION_OPERATION_SCHEMA_VERSION, - "operation": operation, - "dry_run": not execute, - "changed": changed, - "extension_id": extension_id, - "version": provider["version"], - "revision": revision, - "previous_revision": previous_revision, - "enabled": enabled if execute else None, - "doctor": doctor, - "rollback_available": previous_revision is not None, - } - - -def enable_extension( - extension_id: str, - *, - state_file: str | Path, - execute: bool = False, -) -> dict[str, Any]: - path = Path(state_file).expanduser() - state = _read_state(path) - entry = state["extensions"].get(extension_id) - if not isinstance(entry, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - active_revision = str(entry.get("active_revision") or "") - snapshot = _entry_for_revision(entry, active_revision) - manifest = snapshot.get("manifest") - if not isinstance(manifest, Mapping): - raise ValueError("extension active manifest is invalid") - already_enabled = bool(entry.get("enabled")) - incompatibility = _active_manifest_incompatibility(entry) - if incompatibility is not None: - raise ValueError( - f"{incompatibility}; upgrade to a compatible manifest or roll back" - ) - doctor, location = probe_runtime_location( - manifest, location=snapshot.get("entrypoint_path"), execute=execute, - ) - if execute and not doctor["verified"]: - with exclusive_file_lock(path): - current_state = _read_state(path) - current_entry = current_state["extensions"].get(extension_id) - if ( - not isinstance(current_entry, dict) - or current_entry.get("active_revision") != active_revision - or bool(current_entry.get("enabled")) != already_enabled - ): - raise ValueError("extension state changed during enable; retry") - _record_doctor(current_entry, active_revision, doctor) - _write_state(path, current_state) - raise ValueError( - f"extension `{extension_id}` enable doctor is not ready: {doctor['status']}" - ) - changed = False - if execute: - with exclusive_file_lock(path): - current_state = _read_state(path) - current_entry = current_state["extensions"].get(extension_id) - if ( - not isinstance(current_entry, dict) - or current_entry.get("active_revision") != active_revision - or bool(current_entry.get("enabled")) != already_enabled - ): - raise ValueError("extension state changed during enable; retry") - record_runtime_location( - _entry_for_revision(current_entry, active_revision), - location=location, expected=snapshot.get("entrypoint_path"), - ) - current_entry["enabled"] = True - _record_doctor(current_entry, active_revision, doctor) - _write_state(path, current_state) - changed = not already_enabled - return { - "ok": True, - "schema_version": EXTENSION_OPERATION_SCHEMA_VERSION, - "operation": "enable", - "dry_run": not execute, - "changed": changed, - "would_change": not already_enabled, - "extension_id": extension_id, - "enabled": True if execute else already_enabled, - "active_revision": active_revision, - "doctor": doctor, - } - - -def disable_extension( - extension_id: str, - *, - state_file: str | Path, - execute: bool = False, -) -> dict[str, Any]: - path = Path(state_file).expanduser() - lock = exclusive_file_lock(path) if execute else nullcontext() - with lock: - state = _read_state(path) - entry = state["extensions"].get(extension_id) - if not isinstance(entry, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - changed = bool(entry.get("enabled")) - if execute and changed: - entry["enabled"] = False - _write_state(path, state) - return { - "ok": True, - "schema_version": EXTENSION_OPERATION_SCHEMA_VERSION, - "operation": "disable", - "dry_run": not execute, - "changed": changed if execute else False, - "would_change": changed, - "extension_id": extension_id, - "enabled": False if execute else bool(entry.get("enabled")), - "active_revision": entry.get("active_revision"), - } - - -def rollback_extension( - extension_id: str, - *, - state_file: str | Path, - execute: bool = False, -) -> dict[str, Any]: - path = Path(state_file).expanduser() - state = _read_state(path) - entry = state["extensions"].get(extension_id) - if not isinstance(entry, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - target_revision = str(entry.get("rollback_revision") or "") - if not target_revision: - raise ValueError(f"extension `{extension_id}` has no rollback revision") - target = _entry_for_revision(entry, target_revision) - manifest = target.get("manifest") - if not isinstance(manifest, dict): - raise ValueError("extension rollback manifest is invalid") - target_provider = manifest.get("provider") - incompatibility = loopx_api_incompatibility( - target_provider.get("requires_loopx_api") if isinstance(target_provider, Mapping) else None, - context=f"extension `{extension_id}` rollback revision `{target_revision}`", - ) - if incompatibility is not None: - # Probing the entrypoint cannot admit a snapshot this runtime rejects; - # refuse before switching rather than leaving an active revision that - # every reader then fails closed on. - raise ValueError(f"{incompatibility}; roll forward with a compatible manifest instead") - doctor, location = probe_runtime_location( - manifest, location=target.get("entrypoint_path"), execute=execute, - ) - if execute and not doctor["verified"]: - raise ValueError( - f"extension `{extension_id}` rollback doctor is not ready: {doctor['status']}" - ) - previous_revision = str(entry.get("active_revision") or "") - # Dry-run previews the enablement read before the probe; the execute path - # replaces it with the value committed under the lock below. - enabled = bool(entry.get("enabled")) - if execute: - with exclusive_file_lock(path): - current_state = _read_state(path) - current_entry = current_state["extensions"].get(extension_id) - if not isinstance(current_entry, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - if ( - current_entry.get("active_revision") != previous_revision - or current_entry.get("rollback_revision") != target_revision - ): - raise ValueError("extension state changed during rollback; retry") - record_runtime_location( - _entry_for_revision(current_entry, target_revision), - location=location, expected=target.get("entrypoint_path"), - ) - current_entry["active_revision"] = target_revision - current_entry["rollback_revision"] = previous_revision - _record_doctor(current_entry, target_revision, doctor) - # Rollback switches the active revision only; it does not undo an - # operator's enable/disable decision, including one that completed - # while the probe ran. The result must report what was committed - # here, not the pre-probe snapshot. - enabled = bool(current_entry.get("enabled")) - _write_state(path, current_state) - return { - "ok": True, - "schema_version": EXTENSION_OPERATION_SCHEMA_VERSION, - "operation": "rollback", - "dry_run": not execute, - "changed": execute, - "extension_id": extension_id, - "version": target.get("version"), - "revision": target_revision, - "previous_revision": previous_revision, - "enabled": enabled, - "doctor": doctor, - } - - -def extension_status( - *, - state_file: str | Path, - extension_id: str | None = None, -) -> dict[str, Any]: - state = _read_state(Path(state_file).expanduser()) - entries = state["extensions"] - if extension_id is not None: - entry = entries.get(extension_id) - if not isinstance(entry, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - visible = [entry] - else: - visible = [entry for entry in entries.values() if isinstance(entry, dict)] - return { - "ok": True, - "schema_version": EXTENSION_STATE_SCHEMA_VERSION, - "extensions": [ - { - "id": entry.get("id"), - "enabled": bool(entry.get("enabled")), - "active_revision": entry.get("active_revision"), - "rollback_available": bool(entry.get("rollback_revision")), - # Missing legacy metadata is readable but unverified. Resolve - # its proof before parsing the active manifest; a valid proof - # must still match this runtime's extension API. - "doctor_verified": bool(entry.get("enabled")) - and _verified_entrypoint(entry) is not None - and _active_manifest_incompatibility(entry) is None, - "revision_count": len(entry.get("revisions") or []), - } - for entry in visible - ], - } - - -def doctor_installed_extension( - extension_id: str, - *, - state_file: str | Path, - execute: bool = False, -) -> dict[str, Any]: - path = Path(state_file).expanduser() - state = _read_state(path) - entry = state["extensions"].get(extension_id) - if not isinstance(entry, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - if not entry.get("enabled"): - return { - "ok": True, - "schema_version": EXTENSION_DOCTOR_SCHEMA_VERSION, - "extension_id": extension_id, - "status": "disabled", - "available": False, - "verified": False, - "entrypoint_identity": None, - "failure_kind": None, - "external_writes_performed": False, - } - active_revision = str(entry.get("active_revision") or "") - snapshot = _entry_for_revision(entry, active_revision) - manifest = snapshot.get("manifest") - if not isinstance(manifest, Mapping): - raise ValueError("extension active manifest is invalid") - incompatibility = _active_manifest_incompatibility(entry) - if incompatibility is not None: - # The snapshot was valid for the runtime that installed it; this - # runtime's extension API moved. No probe can repair that, so the - # doctor fails closed and, when executed, revokes the stale proof. - doctor = { - "ok": True, - "schema_version": EXTENSION_DOCTOR_SCHEMA_VERSION, - "extension_id": extension_id, - "version": manifest.get("provider", {}).get("version"), - "status": "api_incompatible", - "available": False, - "verified": False, - "entrypoint_identity": None, - "probed_entrypoint_identity": None, - "failure_kind": "api_incompatible", - "reason": incompatibility, - "external_writes_performed": False, - } - location = None - else: - doctor, location = probe_runtime_location( - manifest, location=snapshot.get("entrypoint_path"), execute=execute, - ) - if execute: - with exclusive_file_lock(path): - current_state = _read_state(path) - current_entry = current_state["extensions"].get(extension_id) - if ( - not isinstance(current_entry, dict) - or current_entry.get("active_revision") != active_revision - or not current_entry.get("enabled") - ): - raise ValueError("extension state changed during doctor; retry") - if incompatibility is not None: - current_entry.pop("doctor_verified_revision", None) - current_entry.pop("doctor_verified_entrypoint_identities", None) - current_entry.pop("doctor_verified_entrypoint_identity", None) - if doctor["verified"]: - record_runtime_location( - _entry_for_revision(current_entry, active_revision), - location=location, expected=snapshot.get("entrypoint_path"), - ) - _record_doctor(current_entry, active_revision, doctor) - _write_state(path, current_state) - return doctor - - -def doctor_enabled_extensions( - *, - state_file: str | Path, - execute: bool = False, -) -> dict[str, Any]: - """Revalidate every enabled extension after a runtime release transition. - - Extension doctors are declared read-only provider probes. Running them as - one bounded batch lets installers and rollback paths refresh the runtime - identity without weakening the fail-closed activation fence. - """ - - path = Path(state_file).expanduser() - state = _read_state(path) - extension_ids = sorted( - str(extension_id) - for extension_id, entry in state["extensions"].items() - if isinstance(entry, Mapping) and entry.get("enabled") - ) - doctors = [ - doctor_installed_extension( - extension_id, - state_file=path, - execute=execute, - ) - for extension_id in extension_ids - ] - verified_count = sum(bool(doctor.get("verified")) for doctor in doctors) - blocked_count = len(doctors) - verified_count if execute else 0 - return { - "ok": blocked_count == 0, - "schema_version": EXTENSION_DOCTOR_BATCH_SCHEMA_VERSION, - "status": ( - "ready" - if execute and blocked_count == 0 - else "blocked" - if execute - else "probe_required" - if doctors - else "ready" - ), - "execute": execute, - "enabled_count": len(doctors), - "verified_count": verified_count, - "blocked_count": blocked_count, - "extensions": doctors, - "local_state_write_performed": execute and bool(doctors), - "external_writes_performed": False, - } - - -def _verified_entrypoint( - entry: Mapping[str, Any], -) -> ResolvedRuntimeEntrypoint | None: - active_revision = str(entry.get("active_revision") or "") - if entry.get("doctor_verified_revision") != active_revision: - return None - try: - snapshot = _entry_for_revision(entry, active_revision) - except ValueError: - return None - manifest = snapshot.get("manifest") - if not isinstance(manifest, Mapping): - return None - runtime = located_runtime(manifest, snapshot.get("entrypoint_path")) - identity = resolve_runtime_entrypoint( - runtime, - view_validators=declared_view_validators(manifest), - ) - if identity is None or identity.identity not in _verified_identities( - entry, active_revision - ): - return None - return identity - - -def _active_manifest(entry: Mapping[str, Any]) -> Mapping[str, Any]: - active_revision = str(entry.get("active_revision") or "") - snapshot = _entry_for_revision(entry, active_revision) - manifest = snapshot.get("manifest") - if not isinstance(manifest, Mapping): - raise ValueError("extension active manifest is invalid") - return manifest - - -def _active_manifest_incompatibility(entry: Mapping[str, Any]) -> str | None: - """Re-check the installed snapshot against the runtime reading it. - - `install`/`upgrade` validate `requires_loopx_api` when they load the - manifest, but the saved copy outlives that runtime. A later LoopX whose - extension API moved must treat the snapshot as incompatible, not ready. - """ - manifest = _active_manifest(entry) - provider = manifest.get("provider") - if not isinstance(provider, Mapping): - return "extension active manifest is incomplete" - extension_id = str(provider.get("id") or entry.get("id") or "") - return loopx_api_incompatibility( - provider.get("requires_loopx_api"), - context=f"extension `{extension_id}` active manifest", - ) - - -def extension_catalog_entries( - extension_manifest_paths: Iterable[str | Path] = (), - *, - state_file: str | Path | None = None, -) -> list[dict[str, Any]]: - """Compose declared manifests with installed runtime lifecycle state.""" - - manifests: dict[str, Mapping[str, Any]] = {} - lifecycle: dict[str, dict[str, Any]] = {} - manifest: Mapping[str, Any] - for manifest_path in extension_manifest_paths: - manifest = load_extension_manifest(manifest_path) - extension_id = str(manifest["provider"]["id"]) - if extension_id in manifests: - raise ValueError(f"duplicate capability provider `{extension_id}`") - manifests[extension_id] = manifest - lifecycle[extension_id] = { - "declared": True, - "installed": False, - "enabled": False, - "ready": False, - } - - if state_file is not None: - state = _read_state(Path(state_file).expanduser()) - for extension_id, entry in state["extensions"].items(): - if not isinstance(entry, Mapping): - raise ValueError(f"extension `{extension_id}` runtime entry is invalid") - manifest = _active_manifest(entry) - provider = manifest.get("provider") - if not isinstance(provider, Mapping) or provider.get("id") != extension_id: - raise ValueError( - f"extension `{extension_id}` active manifest is invalid" - ) - active_revision = str(entry.get("active_revision") or "") - declared = manifests.get(extension_id) - if declared is not None and _revision(declared) != active_revision: - # Two different manifests for one id: the installed state is - # the lifecycle source, so a declaration may only repeat it. - raise ValueError( - f"duplicate capability provider `{extension_id}`: declared " - f"manifest revision `{_revision(declared)}` differs from the " - f"installed active revision `{active_revision}`" - ) - manifests[extension_id] = manifest - enabled = bool(entry.get("enabled")) - compatible = _active_manifest_incompatibility(entry) is None - lifecycle[extension_id] = { - "declared": True, - "installed": True, - "enabled": enabled, - "ready": enabled and compatible and _verified_entrypoint(entry) is not None, - "active_revision": active_revision, - } - - entries: list[dict[str, Any]] = [] - for extension_id, manifest in manifests.items(): - normalized = deepcopy(dict(manifest)) - normalized["provider"] = ( - deepcopy(dict(manifest["provider"])) | lifecycle[extension_id] - ) - entries.append(normalized) - return entries - - -def resolve_capability_extension_id( - *, - state_file: str | Path, - capability_id: str, - protocol: str, -) -> str: - """Resolve one ready extension implementation without caller aliases.""" - - matching: list[str] = [] - for entry in extension_catalog_entries(state_file=state_file): - provider = entry.get("provider") - if not isinstance(provider, Mapping) or not provider.get("ready"): - continue - if _matching_capability_implementations( - entry, capability_id=capability_id, protocol=protocol - ): - matching.append(str(entry["provider"]["id"])) - if not matching: - raise ValueError( - f"no enabled, doctor-ready extension implements `{capability_id}` " - f"with protocol `{protocol}`" - ) - if len(matching) != 1: - raise ValueError( - f"multiple enabled, doctor-ready extensions implement `{capability_id}` " - f"with protocol `{protocol}`: {matching}" - ) - return matching[0] - - -def _resolved_active_extension( - extension_id: str, - *, - state_file: str | Path, -) -> tuple[str, ResolvedRuntimeEntrypoint, Mapping[str, Any]]: - state = _read_state(Path(state_file).expanduser()) - entry = state["extensions"].get(extension_id) - if not isinstance(entry, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - if not entry.get("enabled"): - raise ValueError(f"extension `{extension_id}` is disabled") - incompatibility = _active_manifest_incompatibility(entry) - if incompatibility is not None: - raise ValueError( - f"{incompatibility}; upgrade to a compatible manifest or roll back" - ) - active_revision = str(entry.get("active_revision") or "") - verified_entrypoint = _verified_entrypoint(entry) - if verified_entrypoint is None: - raise ValueError( - f"extension `{extension_id}` doctor readiness is stale; run " - f"`loopx extension doctor {extension_id} --execute`" - ) - manifest = _active_manifest(entry) - return active_revision, verified_entrypoint, manifest - - -def resolve_extension_activation( - extension_id: str, - *, - state_file: str | Path, - required_permissions: Sequence[str] = (), -) -> dict[str, Any]: - """Resolve one enabled, revision-bound extension compatibility delegate.""" - - active_revision, _, manifest = _resolved_active_extension( - extension_id, - state_file=state_file, - ) - provider = manifest.get("provider") - if not isinstance(provider, Mapping): - raise ValueError("extension active manifest is incomplete") - declared_permissions = { - str(permission) - for permission in provider.get("permissions") or [] - if str(permission).strip() - } - required = { - str(permission).strip() - for permission in required_permissions - if str(permission).strip() - } - missing = sorted(required - declared_permissions) - if missing: - raise ValueError( - f"extension `{extension_id}` does not declare permissions {missing}" - ) - return { - "schema_version": EXTENSION_ACTIVATION_SCHEMA_VERSION, - "extension_id": extension_id, - "provider_version": provider.get("version"), - "revision": active_revision, - "enabled": True, - "doctor_verified": True, - "required_permissions": sorted(required), - } - - -def resolve_extension_binding( - extension_id: str, - *, - state_file: str | Path, - capability_id: str, - protocol: str, - permission: str, -) -> dict[str, Any]: - state = _read_state(Path(state_file).expanduser()) - entry = state["extensions"].get(extension_id) - if not isinstance(entry, dict): - raise ValueError(f"extension `{extension_id}` is not installed") - return _capability_binding_from_entry( - extension_id, - entry=entry, - capability_id=capability_id, - protocol=protocol, - permission=permission, - ) - - -def _capability_binding_from_entry( - extension_id: str, - *, - entry: Mapping[str, Any], - capability_id: str, - protocol: str, - permission: str, - verified_entrypoint: ResolvedRuntimeEntrypoint | None = None, -) -> dict[str, Any]: - if not entry.get("enabled"): - raise ValueError(f"extension `{extension_id}` is disabled") - incompatibility = _active_manifest_incompatibility(entry) - if incompatibility is not None: - raise ValueError( - f"{incompatibility}; upgrade to a compatible manifest or roll back" - ) - active_revision = str(entry.get("active_revision") or "") - verified_entrypoint = verified_entrypoint or _verified_entrypoint(entry) - if verified_entrypoint is None: - raise ValueError( - f"extension `{extension_id}` doctor readiness is stale; run " - f"`loopx extension doctor {extension_id} --execute`" - ) - manifest = _active_manifest(entry) - provider = manifest.get("provider") - runtime = _runtime(manifest) - implementations = manifest.get("implementations") - if not isinstance(provider, Mapping) or not isinstance(implementations, list): - raise ValueError("extension active manifest is incomplete") - if permission not in (provider.get("permissions") or []): - raise ValueError( - f"extension `{extension_id}` does not declare permission `{permission}`" - ) - if permission not in (runtime.get("required_permissions") or []): - raise ValueError( - f"extension `{extension_id}` runtime does not require permission " - f"`{permission}`" - ) - matching = _matching_capability_implementations( - manifest, capability_id=capability_id, protocol=protocol - ) - if len(matching) != 1 or runtime.get("protocol") != protocol: - raise ValueError( - f"extension `{extension_id}` does not implement `{capability_id}` " - f"with protocol `{protocol}`" - ) - return { - "schema_version": EXTENSION_BINDING_SCHEMA_VERSION, - "extension_id": extension_id, - "provider_version": provider.get("version"), - "revision": active_revision, - "protocol": protocol, - "argv": [*verified_entrypoint.argv_prefix, *(runtime.get("args") or [])], - "environment_path_prefix": verified_entrypoint.path_prefix, - "doctor_argv": [ - *verified_entrypoint.argv_prefix, - *(runtime.get("args") or []), - *(runtime.get("doctor_args") or []), - ], - "timeout_seconds": runtime["timeout_seconds"], - } - - -def _optional_binding_resolution( - *, - status: str, - extension_id: str | None, - installed: bool | None, - enabled: bool | None, - doctor_verified: bool | None, - next_action: str | None, - binding: Mapping[str, Any] | None = None, -) -> ExtensionCapabilityResolution: - return ExtensionCapabilityResolution( - status=status, - extension_id=extension_id, - installed=installed, - enabled=enabled, - doctor_verified=doctor_verified, - next_action=next_action, - binding=dict(binding) if binding is not None else None, - ) - - -def _matching_capability_implementations( - manifest: Mapping[str, Any], - *, - capability_id: str, - protocol: str, -) -> list[Mapping[str, Any]]: - implementations = manifest.get("implementations") - if not isinstance(implementations, list): - return [] - return [ - item - for item in implementations - if isinstance(item, Mapping) - and item.get("capability_id") == capability_id - and item.get("protocol") == protocol - ] - - -def _optional_binding_for_entry( - extension_id: str, - *, - entry: Mapping[str, Any], - capability_id: str, - protocol: str, - permission: str, -) -> ExtensionCapabilityResolution: - manifest = _active_manifest(entry) - provider = manifest.get("provider") - verified_entrypoint = _verified_entrypoint(entry) - if ( - not isinstance(provider, Mapping) - or _active_manifest_incompatibility(entry) is not None - or not _matching_capability_implementations( - manifest, capability_id=capability_id, protocol=protocol - ) - ): - return _optional_binding_resolution( - status="extension_incompatible", - extension_id=extension_id, - installed=True, - enabled=bool(entry.get("enabled")), - doctor_verified=verified_entrypoint is not None, - next_action="install_compatible_extension", - ) - if not entry.get("enabled"): - return _optional_binding_resolution( - status=EXTENSION_DISABLED_STATUS, - extension_id=extension_id, - installed=True, - enabled=False, - doctor_verified=False, - next_action="enable_extension", - ) - if verified_entrypoint is None: - return _optional_binding_resolution( - status=EXTENSION_DOCTOR_NOT_READY_STATUS, - extension_id=extension_id, - installed=True, - enabled=True, - doctor_verified=False, - next_action="run_extension_doctor", - ) - try: - binding = _capability_binding_from_entry( - extension_id, - entry=entry, - capability_id=capability_id, - protocol=protocol, - permission=permission, - verified_entrypoint=verified_entrypoint, - ) - except ValueError: - return _optional_binding_resolution( - status="extension_incompatible", - extension_id=extension_id, - installed=True, - enabled=True, - doctor_verified=True, - next_action="install_compatible_extension", - ) - return _optional_binding_resolution( - status="ready", - extension_id=extension_id, - installed=True, - enabled=True, - doctor_verified=True, - next_action=None, - binding=binding, - ) - - -def resolve_optional_capability_binding( - *, - state_file: str | Path, - capability_id: str, - protocol: str, - permission: str, - extension_id: str | None = None, -) -> ExtensionCapabilityResolution: - """Resolve selection, lifecycle readiness, and binding from one state read.""" - - try: - state = _read_state(Path(state_file).expanduser()) - entries = state["extensions"] - if extension_id is not None: - entry = entries.get(extension_id) - if not isinstance(entry, Mapping): - return _optional_binding_resolution( - status="extension_not_installed", - extension_id=extension_id, - installed=False, - enabled=False, - doctor_verified=False, - next_action="install_extension", - ) - return _optional_binding_for_entry( - extension_id, - entry=entry, - capability_id=capability_id, - protocol=protocol, - permission=permission, - ) - - candidates: list[tuple[str, Mapping[str, Any]]] = [] - for candidate_id, candidate_entry in entries.items(): - if not isinstance(candidate_entry, Mapping): - raise ValueError( - f"extension `{candidate_id}` runtime entry is invalid" - ) - manifest = _active_manifest(candidate_entry) - if _matching_capability_implementations( - manifest, capability_id=capability_id, protocol=protocol - ): - candidates.append((str(candidate_id), candidate_entry)) - resolutions = [ - _optional_binding_for_entry( - candidate_id, - entry=candidate_entry, - capability_id=capability_id, - protocol=protocol, - permission=permission, - ) - for candidate_id, candidate_entry in candidates - ] - except (OSError, ValueError): - return _optional_binding_resolution( - status="extension_state_unavailable", - extension_id=extension_id, - installed=None, - enabled=None, - doctor_verified=None, - next_action="repair_extension_state", - ) - - ready = [item for item in resolutions if item.status == "ready"] - if len(ready) == 1: - return ready[0] - if len(ready) > 1: - return _optional_binding_resolution( - status="extension_provider_ambiguous", - extension_id=None, - installed=True, - enabled=True, - doctor_verified=True, - next_action="select_extension_id", - ) - if len(resolutions) == 1: - return resolutions[0] - return _optional_binding_resolution( - status=( - "extension_provider_not_installed" - if not resolutions - else "extension_provider_not_ready" - ), - extension_id=None, - installed=bool(resolutions), - enabled=any(item.enabled is True for item in resolutions), - doctor_verified=False, - next_action=( - "install_or_select_extension" - if not resolutions - else "select_or_repair_extension" - ), - ) - - -def resolve_extension_runtime_binding( - extension_id: str, - *, - state_file: str | Path, - protocol: str, - permission: str, -) -> dict[str, Any]: - """Resolve an extension runtime without coupling dispatch to capability metadata.""" - - active_revision, verified_entrypoint, manifest = _resolved_active_extension( - extension_id, - state_file=state_file, - ) - provider = manifest.get("provider") - runtime = _runtime(manifest) - if not isinstance(provider, Mapping): - raise ValueError("extension active manifest is incomplete") - if permission not in (provider.get("permissions") or []): - raise ValueError( - f"extension `{extension_id}` does not declare permission `{permission}`" - ) - if permission not in (runtime.get("required_permissions") or []): - raise ValueError( - f"extension `{extension_id}` runtime does not require permission " - f"`{permission}`" - ) - if runtime.get("protocol") != protocol: - raise ValueError( - f"extension `{extension_id}` does not expose runtime protocol `{protocol}`" - ) - return { - "schema_version": EXTENSION_BINDING_SCHEMA_VERSION, - "extension_id": extension_id, - "provider_version": provider.get("version"), - "revision": active_revision, - "protocol": protocol, - "argv": [*verified_entrypoint.argv_prefix, *(runtime.get("args") or [])], - "environment_path_prefix": verified_entrypoint.path_prefix, - "doctor_argv": [ - *verified_entrypoint.argv_prefix, - *(runtime.get("args") or []), - *(runtime.get("doctor_args") or []), - ], - "timeout_seconds": runtime["timeout_seconds"], - } def _serialize_extension_request( - request: Mapping[str, Any], + request: Mapping[str, object], *, operation: str, ) -> bytes: @@ -1211,19 +97,12 @@ def _parse_extension_response(response: bytes) -> tuple[bool, object]: return False, None -def run_standalone_extension( +def _validate_standalone_run( extension_id: str, *, - state_file: str | Path, - request: Mapping[str, Any], - execute: bool = False, -) -> dict[str, Any]: - """Run one lifecycle-gated standalone extension over bounded JSON stdin/stdout.""" - - active_revision, verified_entrypoint, manifest = _resolved_active_extension( - extension_id, - state_file=state_file, - ) + manifest: Mapping[str, object], + request: Mapping[str, object], +) -> tuple[Mapping[str, object], Mapping[str, object], list[str], bytes]: provider = manifest.get("provider") runtime = _runtime(manifest) if not isinstance(provider, Mapping): @@ -1236,10 +115,16 @@ def run_standalone_extension( if not isinstance(request, Mapping): raise ValueError("extension run request must be a JSON object") + raw_required = runtime.get("required_permissions") required_permissions = [ - str(value) for value in runtime.get("required_permissions") or [] + str(value) + for value in (raw_required if isinstance(raw_required, list) else []) ] - declared_permissions = {str(value) for value in provider.get("permissions") or []} + raw_declared = provider.get("permissions") + declared_permissions = { + str(value) + for value in (raw_declared if isinstance(raw_declared, list) else []) + } missing_permissions = sorted(set(required_permissions) - declared_permissions) if missing_permissions: raise ValueError( @@ -1253,34 +138,25 @@ def run_standalone_extension( "effect dispatch, so use a capability or domain command that owns " "policy checks and a request-bound execution envelope" ) - request_bytes = _serialize_extension_request(request, operation="run") + return provider, runtime, required_permissions, request_bytes - receipt: dict[str, Any] = { - "ok": True, - "schema_version": EXTENSION_RUN_SCHEMA_VERSION, - "operation": "run", - "extension_id": extension_id, - "provider_version": provider.get("version"), - "revision": active_revision, - "protocol": runtime["protocol"], - "required_permissions": required_permissions, - "dry_run": not execute, - "executed": False, - "status": "ready" if not execute else "running", - "input_schema_version": request.get("schema_version"), - } - if not execute: - return receipt - argv = [*verified_entrypoint.argv_prefix, *(runtime.get("args") or [])] +def _execute_standalone_process( + receipt: dict[str, object], + *, + argv: list[str], + request_bytes: bytes, + timeout_seconds: int, + env: Mapping[str, str] | None, +) -> dict[str, object]: try: completed = run_capped_process( argv, stdin=request_bytes, - timeout_seconds=int(runtime["timeout_seconds"]), + timeout_seconds=timeout_seconds, output_limit_bytes=MAX_EXTENSION_RESPONSE_BYTES, - env=runtime_process_environment(verified_entrypoint.path_prefix), + env=env, ) except OSError: return { @@ -1327,29 +203,57 @@ def run_standalone_extension( } -def resolve_capability_binding( +def run_standalone_extension( + extension_id: str, *, state_file: str | Path, - capability_id: str, - protocol: str, - permission: str, -) -> dict[str, Any]: - extension_id = resolve_capability_extension_id( + request: Mapping[str, object], + execute: bool = False, +) -> dict[str, object]: + """Run one lifecycle-gated standalone extension over bounded JSON stdin/stdout.""" + active_revision, verified_entrypoint, manifest = _resolved_active_extension( + extension_id, state_file=state_file, - capability_id=capability_id, - protocol=protocol, ) - return resolve_extension_binding( + provider, runtime, required_permissions, request_bytes = _validate_standalone_run( extension_id, - state_file=state_file, - capability_id=capability_id, - protocol=protocol, - permission=permission, + manifest=manifest, + request=request, + ) + receipt: dict[str, object] = { + "ok": True, + "schema_version": EXTENSION_RUN_SCHEMA_VERSION, + "operation": "run", + "extension_id": extension_id, + "provider_version": provider.get("version"), + "revision": active_revision, + "protocol": runtime["protocol"], + "required_permissions": required_permissions, + "dry_run": not execute, + "executed": False, + "status": "ready" if not execute else "running", + "input_schema_version": request.get("schema_version"), + } + if not execute: + return receipt + + raw_args = runtime.get("args") + args = [str(value) for value in raw_args] if isinstance(raw_args, list) else [] + argv = [*verified_entrypoint.argv_prefix, *args] + raw_timeout = runtime["timeout_seconds"] + if isinstance(raw_timeout, bool) or not isinstance(raw_timeout, (int, float)): + raise ValueError("extension runtime timeout is invalid") + return _execute_standalone_process( + receipt, + argv=argv, + request_bytes=request_bytes, + timeout_seconds=int(raw_timeout), + env=runtime_process_environment(verified_entrypoint.path_prefix), ) def _runtime_binding_invocation( - binding: Mapping[str, Any], + binding: Mapping[str, object], ) -> tuple[list[str], float]: if binding.get("schema_version") != EXTENSION_BINDING_SCHEMA_VERSION: raise ValueError( @@ -1368,26 +272,29 @@ def _runtime_binding_invocation( timeout_seconds = float(raw_timeout) if not math.isfinite(timeout_seconds) or not 1 <= timeout_seconds <= 120: raise ValueError("extension runtime binding timeout is invalid") - return argv, timeout_seconds + return [str(value) for value in argv], timeout_seconds def execute_extension_runtime_binding( - binding: Mapping[str, Any], + binding: Mapping[str, object], *, - request: Mapping[str, Any], + request: Mapping[str, object], environment: Mapping[str, str] | None = None, -) -> dict[str, Any]: +) -> dict[str, object]: """Execute a resolved binding after its capability authorizes the request.""" - argv, timeout_seconds = _runtime_binding_invocation(binding) request_bytes = _serialize_extension_request(request, operation="runtime") + raw_prefix = binding.get("environment_path_prefix") + if raw_prefix is not None and not isinstance(raw_prefix, str): + raise ValueError("extension runtime search directory must be absolute") + path_prefix = raw_prefix try: completed = run_capped_process( argv, stdin=request_bytes, timeout_seconds=timeout_seconds, output_limit_bytes=MAX_EXTENSION_RESPONSE_BYTES, - env=runtime_process_environment(binding.get("environment_path_prefix"), environment), + env=runtime_process_environment(path_prefix, environment), ) except OSError as exc: raise RuntimeError("extension provider execution failed") from exc @@ -1402,4 +309,4 @@ def execute_extension_runtime_binding( raise RuntimeError("extension provider returned a non-object") if completed.returncode != 0 or provider_result.get("ok") is False: raise RuntimeError("extension provider reported failure") - return provider_result + return _coerce_object_dict(provider_result) diff --git a/loopx/extensions/runtime_bindings.py b/loopx/extensions/runtime_bindings.py new file mode 100644 index 0000000000..5c102c4edc --- /dev/null +++ b/loopx/extensions/runtime_bindings.py @@ -0,0 +1,610 @@ +"""Capability/extension binding resolution without duplicate state walks.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path + +from .readiness import ResolvedRuntimeEntrypoint +from .runtime_state import ( + EXTENSION_ACTIVATION_SCHEMA_VERSION, + EXTENSION_BINDING_SCHEMA_VERSION, + EXTENSION_DISABLED_STATUS, + EXTENSION_DOCTOR_NOT_READY_STATUS, + ExtensionCapabilityResolution, + ExtensionRuntimeBinding, + _active_snapshot_and_manifest, + _coerce_object_dict, + _extensions_dict, + _manifest_incompatibility, + _read_state, + _resolved_active_extension, + _runtime, + _verified_entrypoint, +) + + +def _matching_capability_implementations( + manifest: Mapping[str, object], + *, + capability_id: str, + protocol: str, +) -> list[Mapping[str, object]]: + implementations = manifest.get("implementations") + if not isinstance(implementations, list): + return [] + return [ + _coerce_object_dict(item) + for item in implementations + if isinstance(item, Mapping) + and item.get("capability_id") == capability_id + and item.get("protocol") == protocol + ] + + +def _validate_runtime_binding_access( + extension_id: str, + *, + provider: Mapping[str, object], + runtime: Mapping[str, object], + protocol: str, + permission: str, + mismatch_message: str, +) -> None: + raw_permissions = provider.get("permissions") + declared_permissions = raw_permissions if isinstance(raw_permissions, list) else [] + if permission not in declared_permissions: + raise ValueError( + f"extension `{extension_id}` does not declare permission `{permission}`" + ) + raw_required = runtime.get("required_permissions") + required_permissions = raw_required if isinstance(raw_required, list) else [] + if permission not in required_permissions: + raise ValueError( + f"extension `{extension_id}` runtime does not require permission " + f"`{permission}`" + ) + if runtime.get("protocol") != protocol: + raise ValueError(mismatch_message) + + +def _assemble_runtime_binding( + extension_id: str, + *, + provider: Mapping[str, object], + runtime: Mapping[str, object], + active_revision: str, + verified_entrypoint: ResolvedRuntimeEntrypoint, + protocol: str, +) -> ExtensionRuntimeBinding: + raw_args = runtime.get("args") + args = [str(value) for value in raw_args] if isinstance(raw_args, list) else [] + raw_doctor_args = runtime.get("doctor_args") + doctor_args = ( + [str(value) for value in raw_doctor_args] + if isinstance(raw_doctor_args, list) + else [] + ) + raw_timeout = runtime["timeout_seconds"] + if isinstance(raw_timeout, bool) or not isinstance(raw_timeout, (int, float)): + raise ValueError("extension runtime timeout is invalid") + return ExtensionRuntimeBinding( + schema_version=EXTENSION_BINDING_SCHEMA_VERSION, + extension_id=extension_id, + provider_version=provider.get("version"), + revision=active_revision, + protocol=protocol, + argv=[*verified_entrypoint.argv_prefix, *args], + environment_path_prefix=verified_entrypoint.path_prefix, + doctor_argv=[*verified_entrypoint.argv_prefix, *args, *doctor_args], + timeout_seconds=raw_timeout, + ) + + +@dataclass(frozen=True) +class _ReadyCapabilityMatch: + extension_id: str + entry: dict[str, object] + active_revision: str + manifest: Mapping[str, object] + verified_entrypoint: ResolvedRuntimeEntrypoint + implementation_count: int + + +def _ready_capability_matches_in_state( + state: Mapping[str, object], + *, + capability_id: str, + protocol: str, +) -> list[_ReadyCapabilityMatch]: + matches: list[_ReadyCapabilityMatch] = [] + for extension_id, entry in _extensions_dict(state).items(): + if not isinstance(entry, dict): + raise ValueError(f"extension `{extension_id}` runtime entry is invalid") + active_revision, snapshot, manifest = _active_snapshot_and_manifest(entry) + provider = manifest.get("provider") + if not isinstance(provider, Mapping) or provider.get("id") != extension_id: + raise ValueError(f"extension `{extension_id}` active manifest is invalid") + if not entry.get("enabled"): + continue + if _manifest_incompatibility(entry, manifest) is not None: + continue + verified = _verified_entrypoint( + entry, + active_revision=active_revision, + snapshot=snapshot, + manifest=manifest, + ) + if verified is None: + continue + impl_matches = _matching_capability_implementations( + manifest, capability_id=capability_id, protocol=protocol + ) + if impl_matches: + matches.append( + _ReadyCapabilityMatch( + extension_id=str(provider["id"]), + entry=entry, + active_revision=active_revision, + manifest=manifest, + verified_entrypoint=verified, + implementation_count=len(impl_matches), + ) + ) + return matches + + +def _select_single_capability_match( + matches: list[_ReadyCapabilityMatch], + *, + capability_id: str, + protocol: str, +) -> _ReadyCapabilityMatch: + matching_ids = [item.extension_id for item in matches] + if not matching_ids: + raise ValueError( + f"no enabled, doctor-ready extension implements `{capability_id}` " + f"with protocol `{protocol}`" + ) + if len(matching_ids) != 1: + raise ValueError( + f"multiple enabled, doctor-ready extensions implement `{capability_id}` " + f"with protocol `{protocol}`: {matching_ids}" + ) + return matches[0] + + +def resolve_capability_extension_id( + *, + state_file: str | Path, + capability_id: str, + protocol: str, +) -> str: + """Resolve one ready extension implementation without caller aliases.""" + state = _read_state(Path(state_file).expanduser()) + matches = _ready_capability_matches_in_state( + state, capability_id=capability_id, protocol=protocol + ) + selected = _select_single_capability_match( + matches, capability_id=capability_id, protocol=protocol + ) + return selected.extension_id + + +def resolve_extension_activation( + extension_id: str, + *, + state_file: str | Path, + required_permissions: Sequence[str] = (), +) -> dict[str, object]: + """Resolve one enabled, revision-bound extension compatibility delegate.""" + active_revision, _, manifest = _resolved_active_extension( + extension_id, + state_file=state_file, + ) + provider = manifest.get("provider") + if not isinstance(provider, Mapping): + raise ValueError("extension active manifest is incomplete") + raw_permissions = provider.get("permissions") + declared_permissions = { + str(permission) + for permission in (raw_permissions if isinstance(raw_permissions, list) else []) + if str(permission).strip() + } + required = { + str(permission).strip() + for permission in required_permissions + if str(permission).strip() + } + missing = sorted(required - declared_permissions) + if missing: + raise ValueError( + f"extension `{extension_id}` does not declare permissions {missing}" + ) + return { + "schema_version": EXTENSION_ACTIVATION_SCHEMA_VERSION, + "extension_id": extension_id, + "provider_version": provider.get("version"), + "revision": active_revision, + "enabled": True, + "doctor_verified": True, + "required_permissions": sorted(required), + } + + +def _capability_binding_from_entry( + extension_id: str, + *, + entry: Mapping[str, object], + capability_id: str, + protocol: str, + permission: str, + active_revision: str | None = None, + manifest: Mapping[str, object] | None = None, + incompatibility_checked: bool = False, + verified_entrypoint: ResolvedRuntimeEntrypoint | None = None, + matching_checked: bool = False, +) -> ExtensionRuntimeBinding: + if not entry.get("enabled"): + raise ValueError(f"extension `{extension_id}` is disabled") + if manifest is None or active_revision is None: + active_revision, snapshot, manifest = _active_snapshot_and_manifest(entry) + else: + snapshot = None + if not incompatibility_checked: + incompatibility = _manifest_incompatibility(entry, manifest) + if incompatibility is not None: + raise ValueError( + f"{incompatibility}; upgrade to a compatible manifest or roll back" + ) + if verified_entrypoint is None: + verified_entrypoint = _verified_entrypoint( + entry, + active_revision=active_revision, + snapshot=snapshot, + manifest=manifest, + ) + if verified_entrypoint is None: + raise ValueError( + f"extension `{extension_id}` doctor readiness is stale; run " + f"`loopx extension doctor {extension_id} --execute`" + ) + provider = manifest.get("provider") + runtime = _runtime(manifest) + implementations = manifest.get("implementations") + if not isinstance(provider, Mapping) or not isinstance(implementations, list): + raise ValueError("extension active manifest is incomplete") + mismatch = ( + f"extension `{extension_id}` does not implement `{capability_id}` " + f"with protocol `{protocol}`" + ) + _validate_runtime_binding_access( + extension_id, + provider=provider, + runtime=runtime, + protocol=protocol, + permission=permission, + mismatch_message=mismatch, + ) + if not matching_checked: + matching = _matching_capability_implementations( + manifest, capability_id=capability_id, protocol=protocol + ) + if len(matching) != 1: + raise ValueError(mismatch) + return _assemble_runtime_binding( + extension_id, + provider=provider, + runtime=runtime, + active_revision=active_revision, + verified_entrypoint=verified_entrypoint, + protocol=protocol, + ) + + +def resolve_extension_binding( + extension_id: str, + *, + state_file: str | Path, + capability_id: str, + protocol: str, + permission: str, +) -> ExtensionRuntimeBinding: + state = _read_state(Path(state_file).expanduser()) + entry = _extensions_dict(state).get(extension_id) + if not isinstance(entry, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + return _capability_binding_from_entry( + extension_id, + entry=entry, + capability_id=capability_id, + protocol=protocol, + permission=permission, + ) + + +def _optional_binding_resolution( + *, + status: str, + extension_id: str | None, + installed: bool | None, + enabled: bool | None, + doctor_verified: bool | None, + next_action: str | None, + binding: Mapping[str, object] | None = None, +) -> ExtensionCapabilityResolution: + return ExtensionCapabilityResolution( + status=status, + extension_id=extension_id, + installed=installed, + enabled=enabled, + doctor_verified=doctor_verified, + next_action=next_action, + binding=dict(binding) if binding is not None else None, + ) + + +def _optional_binding_for_entry( + extension_id: str, + *, + entry: Mapping[str, object], + capability_id: str, + protocol: str, + permission: str, + active_revision: str | None = None, + snapshot: Mapping[str, object] | None = None, + manifest: Mapping[str, object] | None = None, + matching_implementations: list[Mapping[str, object]] | None = None, +) -> ExtensionCapabilityResolution: + if active_revision is None or manifest is None: + active_revision, snapshot, manifest = _active_snapshot_and_manifest(entry) + provider = manifest.get("provider") + verified_entrypoint = _verified_entrypoint( + entry, + active_revision=active_revision, + snapshot=snapshot, + manifest=manifest, + ) + matches = ( + matching_implementations + if matching_implementations is not None + else _matching_capability_implementations( + manifest, capability_id=capability_id, protocol=protocol + ) + ) + if ( + not isinstance(provider, Mapping) + or _manifest_incompatibility(entry, manifest) is not None + or not matches + ): + return _optional_binding_resolution( + status="extension_incompatible", + extension_id=extension_id, + installed=True, + enabled=bool(entry.get("enabled")), + doctor_verified=verified_entrypoint is not None, + next_action="install_compatible_extension", + ) + if not entry.get("enabled"): + return _optional_binding_resolution( + status=EXTENSION_DISABLED_STATUS, + extension_id=extension_id, + installed=True, + enabled=False, + doctor_verified=False, + next_action="enable_extension", + ) + if verified_entrypoint is None: + return _optional_binding_resolution( + status=EXTENSION_DOCTOR_NOT_READY_STATUS, + extension_id=extension_id, + installed=True, + enabled=True, + doctor_verified=False, + next_action="run_extension_doctor", + ) + try: + binding = _capability_binding_from_entry( + extension_id, + entry=entry, + capability_id=capability_id, + protocol=protocol, + permission=permission, + active_revision=active_revision, + manifest=manifest, + incompatibility_checked=True, + verified_entrypoint=verified_entrypoint, + matching_checked=len(matches) == 1, + ) + except ValueError: + return _optional_binding_resolution( + status="extension_incompatible", + extension_id=extension_id, + installed=True, + enabled=True, + doctor_verified=True, + next_action="install_compatible_extension", + ) + return ExtensionCapabilityResolution( + status="ready", + extension_id=extension_id, + installed=True, + enabled=True, + doctor_verified=True, + next_action=None, + binding=binding, + ) + + +def resolve_optional_capability_binding( + *, + state_file: str | Path, + capability_id: str, + protocol: str, + permission: str, + extension_id: str | None = None, +) -> ExtensionCapabilityResolution: + """Resolve selection, lifecycle readiness, and binding from one state read.""" + try: + state = _read_state(Path(state_file).expanduser()) + entries = _extensions_dict(state) + if extension_id is not None: + entry = entries.get(extension_id) + if not isinstance(entry, Mapping): + return _optional_binding_resolution( + status="extension_not_installed", + extension_id=extension_id, + installed=False, + enabled=False, + doctor_verified=False, + next_action="install_extension", + ) + return _optional_binding_for_entry( + extension_id, + entry=entry, + capability_id=capability_id, + protocol=protocol, + permission=permission, + ) + + resolutions: list[ExtensionCapabilityResolution] = [] + for candidate_id, candidate_entry in entries.items(): + if not isinstance(candidate_entry, Mapping): + raise ValueError( + f"extension `{candidate_id}` runtime entry is invalid" + ) + active_rev, candidate_snap, manifest = _active_snapshot_and_manifest( + candidate_entry + ) + matches = _matching_capability_implementations( + manifest, capability_id=capability_id, protocol=protocol + ) + if matches: + resolutions.append( + _optional_binding_for_entry( + str(candidate_id), + entry=candidate_entry, + capability_id=capability_id, + protocol=protocol, + permission=permission, + active_revision=active_rev, + snapshot=candidate_snap, + manifest=manifest, + matching_implementations=matches, + ) + ) + except (OSError, ValueError): + return _optional_binding_resolution( + status="extension_state_unavailable", + extension_id=extension_id, + installed=None, + enabled=None, + doctor_verified=None, + next_action="repair_extension_state", + ) + + ready = [item for item in resolutions if item.status == "ready"] + if len(ready) == 1: + return ready[0] + if len(ready) > 1: + return _optional_binding_resolution( + status="extension_provider_ambiguous", + extension_id=None, + installed=True, + enabled=True, + doctor_verified=True, + next_action="select_extension_id", + ) + if len(resolutions) == 1: + return resolutions[0] + return _optional_binding_resolution( + status=( + "extension_provider_not_installed" + if not resolutions + else "extension_provider_not_ready" + ), + extension_id=None, + installed=bool(resolutions), + enabled=any(item.enabled is True for item in resolutions), + doctor_verified=False, + next_action=( + "install_or_select_extension" + if not resolutions + else "select_or_repair_extension" + ), + ) + + +def resolve_extension_runtime_binding( + extension_id: str, + *, + state_file: str | Path, + protocol: str, + permission: str, +) -> ExtensionRuntimeBinding: + """Resolve an extension runtime without coupling dispatch to capability metadata.""" + active_revision, verified_entrypoint, manifest = _resolved_active_extension( + extension_id, + state_file=state_file, + ) + provider = manifest.get("provider") + runtime = _runtime(manifest) + if not isinstance(provider, Mapping): + raise ValueError("extension active manifest is incomplete") + _validate_runtime_binding_access( + extension_id, + provider=provider, + runtime=runtime, + protocol=protocol, + permission=permission, + mismatch_message=( + f"extension `{extension_id}` does not expose runtime protocol `{protocol}`" + ), + ) + return _assemble_runtime_binding( + extension_id, + provider=provider, + runtime=runtime, + active_revision=active_revision, + verified_entrypoint=verified_entrypoint, + protocol=protocol, + ) + + +def resolve_capability_binding( + *, + state_file: str | Path, + capability_id: str, + protocol: str, + permission: str, +) -> ExtensionRuntimeBinding: + state = _read_state(Path(state_file).expanduser()) + matches = _ready_capability_matches_in_state( + state, capability_id=capability_id, protocol=protocol + ) + selected = _select_single_capability_match( + matches, capability_id=capability_id, protocol=protocol + ) + return _capability_binding_from_entry( + selected.extension_id, + entry=selected.entry, + capability_id=capability_id, + protocol=protocol, + permission=permission, + active_revision=selected.active_revision, + manifest=selected.manifest, + incompatibility_checked=True, + verified_entrypoint=selected.verified_entrypoint, + matching_checked=selected.implementation_count == 1, + ) + + +__all__ = [ + "resolve_capability_binding", + "resolve_capability_extension_id", + "resolve_extension_activation", + "resolve_extension_binding", + "resolve_extension_runtime_binding", + "resolve_optional_capability_binding", +] diff --git a/loopx/extensions/runtime_lifecycle.py b/loopx/extensions/runtime_lifecycle.py new file mode 100644 index 0000000000..4bdb591ab5 --- /dev/null +++ b/loopx/extensions/runtime_lifecycle.py @@ -0,0 +1,621 @@ +"""Extension installation, enablement, rollback, status, doctor, and catalog.""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from contextlib import nullcontext +from copy import deepcopy +from pathlib import Path +from typing import cast + +from ..file_lock import exclusive_file_lock +from .manifest import load_extension_manifest, loopx_api_incompatibility +from .readiness import EXTENSION_DOCTOR_SCHEMA_VERSION, ResolvedRuntimeEntrypoint +from .runtime_location import probe_runtime_location, record_runtime_location +from .runtime_state import ( + EXTENSION_DOCTOR_BATCH_SCHEMA_VERSION, + EXTENSION_OPERATION_SCHEMA_VERSION, + EXTENSION_STATE_SCHEMA_VERSION, + ExtensionCatalogEntry, + _active_snapshot_and_manifest, + _coerce_object_dict, + _entry_for_revision, + _extensions_dict, + _manifest_incompatibility, + _manifest_snapshot, + _read_state, + _record_doctor, + _retain_revisions, + _revision, + _runtime, + _verified_entrypoint, + _verified_identities, + _write_state, +) + + +def _require_mapping_field( + container: Mapping[str, object], key: str, *, error: str +) -> Mapping[str, object]: + value = container.get(key) + if not isinstance(value, Mapping): + raise ValueError(error) + return _coerce_object_dict(value) + + +def _commit_locked_doctor_update( + path: Path, + extension_id: str, + *, + active_revision: str, + expected_enabled: bool, + doctor: Mapping[str, object], + location: str | None, + expected_location: object, + operation_label: str, + clear_verified_proof: bool = False, + new_enabled: bool | None = None, +) -> bool: + with exclusive_file_lock(path): + current_state = _read_state(path) + current_entry = _extensions_dict(current_state).get(extension_id) + if ( + not isinstance(current_entry, dict) + or current_entry.get("active_revision") != active_revision + or bool(current_entry.get("enabled")) != expected_enabled + ): + raise ValueError(f"extension state changed during {operation_label}; retry") + if clear_verified_proof: + current_entry.pop("doctor_verified_revision", None) + current_entry.pop("doctor_verified_entrypoint_identities", None) + current_entry.pop("doctor_verified_entrypoint_identity", None) + if doctor.get("verified"): + record_runtime_location( + _entry_for_revision(current_entry, active_revision), + location=location, + expected=expected_location, + ) + if new_enabled is not None: + current_entry["enabled"] = new_enabled + _record_doctor(current_entry, active_revision, doctor) + _write_state(path, current_state) + return bool(current_entry.get("enabled")) + + +def install_extension( + manifest_path: str | Path, + *, + state_file: str | Path, + operation: str = "install", + execute: bool = False, +) -> dict[str, object]: + if operation not in {"install", "upgrade"}: + raise ValueError("extension operation must be install or upgrade") + manifest = load_extension_manifest(manifest_path) + _runtime(manifest) + provider = _require_mapping_field( + manifest, "provider", error="extension active manifest is invalid" + ) + extension_id = str(provider["id"]) + revision = _revision(manifest) + doctor, location = probe_runtime_location(manifest, execute=execute) + if execute and not doctor["verified"]: + raise ValueError( + f"extension `{extension_id}` doctor is not ready: {doctor['status']}" + ) + path = Path(state_file).expanduser() + changed = False + lock = exclusive_file_lock(path) if execute else nullcontext() + with lock: + state = _read_state(path) + extensions = _extensions_dict(state) + existing = extensions.get(extension_id) + if operation == "install" and existing is not None: + raise ValueError(f"extension `{extension_id}` is already installed") + if operation == "upgrade" and not isinstance(existing, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + if isinstance(existing, dict) and existing.get("active_revision") == revision: + raise ValueError(f"extension `{extension_id}` revision is already active") + previous_revision = ( + str(existing.get("active_revision")) if isinstance(existing, dict) else None + ) + # A fresh install activates the provider. An upgrade changes only the + # active revision; the operator's enable/disable decision is separate + # state and survives the revision change. + enabled = bool(existing.get("enabled")) if isinstance(existing, dict) else True + if execute: + raw_revisions = ( + existing.get("revisions") if isinstance(existing, dict) else None + ) + revisions = ( + [item for item in raw_revisions if isinstance(item, dict)] + if isinstance(raw_revisions, list) + else [] + ) + revisions = _retain_revisions( + revisions, + { + "revision": revision, + "version": provider["version"], + "manifest": _manifest_snapshot(manifest), + **({"entrypoint_path": location} if location is not None else {}), + }, + required_revision=previous_revision, + ) + entry_payload: dict[str, object] = { + "id": extension_id, + "enabled": enabled, + "active_revision": revision, + "rollback_revision": previous_revision, + "revisions": revisions, + } + _record_doctor(entry_payload, revision, doctor) + extensions[extension_id] = entry_payload + _write_state(path, state) + changed = True + return { + "ok": True, + "schema_version": EXTENSION_OPERATION_SCHEMA_VERSION, + "operation": operation, + "dry_run": not execute, + "changed": changed, + "extension_id": extension_id, + "version": provider["version"], + "revision": revision, + "previous_revision": previous_revision, + "enabled": enabled if execute else None, + "doctor": doctor, + "rollback_available": previous_revision is not None, + } + + +def enable_extension( + extension_id: str, + *, + state_file: str | Path, + execute: bool = False, +) -> dict[str, object]: + path = Path(state_file).expanduser() + state = _read_state(path) + entry = _extensions_dict(state).get(extension_id) + if not isinstance(entry, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + active_revision, snapshot, manifest = _active_snapshot_and_manifest(entry) + already_enabled = bool(entry.get("enabled")) + incompatibility = _manifest_incompatibility(entry, manifest) + if incompatibility is not None: + raise ValueError( + f"{incompatibility}; upgrade to a compatible manifest or roll back" + ) + doctor, location = probe_runtime_location( + manifest, location=snapshot.get("entrypoint_path"), execute=execute + ) + if execute and not doctor["verified"]: + _commit_locked_doctor_update( + path, + extension_id, + active_revision=active_revision, + expected_enabled=already_enabled, + doctor=doctor, + location=location, + expected_location=snapshot.get("entrypoint_path"), + operation_label="enable", + ) + raise ValueError( + f"extension `{extension_id}` enable doctor is not ready: {doctor['status']}" + ) + changed = False + if execute: + _commit_locked_doctor_update( + path, + extension_id, + active_revision=active_revision, + expected_enabled=already_enabled, + doctor=doctor, + location=location, + expected_location=snapshot.get("entrypoint_path"), + operation_label="enable", + new_enabled=True, + ) + changed = not already_enabled + return { + "ok": True, + "schema_version": EXTENSION_OPERATION_SCHEMA_VERSION, + "operation": "enable", + "dry_run": not execute, + "changed": changed, + "would_change": not already_enabled, + "extension_id": extension_id, + "enabled": True if execute else already_enabled, + "active_revision": active_revision, + "doctor": doctor, + } + + +def disable_extension( + extension_id: str, + *, + state_file: str | Path, + execute: bool = False, +) -> dict[str, object]: + path = Path(state_file).expanduser() + lock = exclusive_file_lock(path) if execute else nullcontext() + with lock: + state = _read_state(path) + entry = _extensions_dict(state).get(extension_id) + if not isinstance(entry, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + changed = bool(entry.get("enabled")) + if execute and changed: + entry["enabled"] = False + _write_state(path, state) + return { + "ok": True, + "schema_version": EXTENSION_OPERATION_SCHEMA_VERSION, + "operation": "disable", + "dry_run": not execute, + "changed": changed if execute else False, + "would_change": changed, + "extension_id": extension_id, + "enabled": False if execute else bool(entry.get("enabled")), + "active_revision": entry.get("active_revision"), + } + + +def rollback_extension( + extension_id: str, + *, + state_file: str | Path, + execute: bool = False, +) -> dict[str, object]: + path = Path(state_file).expanduser() + state = _read_state(path) + entry = _extensions_dict(state).get(extension_id) + if not isinstance(entry, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + target_revision = str(entry.get("rollback_revision") or "") + if not target_revision: + raise ValueError(f"extension `{extension_id}` has no rollback revision") + target = _entry_for_revision(entry, target_revision) + manifest = target.get("manifest") + if not isinstance(manifest, dict): + raise ValueError("extension rollback manifest is invalid") + target_provider = manifest.get("provider") + incompatibility = loopx_api_incompatibility( + target_provider.get("requires_loopx_api") + if isinstance(target_provider, Mapping) + else None, + context=f"extension `{extension_id}` rollback revision `{target_revision}`", + ) + if incompatibility is not None: + # Probing the entrypoint cannot admit a snapshot this runtime rejects; + # refuse before switching rather than leaving an active revision that + # every reader then fails closed on. + raise ValueError( + f"{incompatibility}; roll forward with a compatible manifest instead" + ) + doctor, location = probe_runtime_location( + manifest, location=target.get("entrypoint_path"), execute=execute + ) + if execute and not doctor["verified"]: + raise ValueError( + f"extension `{extension_id}` rollback doctor is not ready: {doctor['status']}" + ) + previous_revision = str(entry.get("active_revision") or "") + # Dry-run previews the enablement read before the probe; the execute path + # replaces it with the value committed under the lock below. + enabled = bool(entry.get("enabled")) + if execute: + with exclusive_file_lock(path): + current_state = _read_state(path) + current_entry = _extensions_dict(current_state).get(extension_id) + if not isinstance(current_entry, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + if ( + current_entry.get("active_revision") != previous_revision + or current_entry.get("rollback_revision") != target_revision + ): + raise ValueError("extension state changed during rollback; retry") + record_runtime_location( + _entry_for_revision(current_entry, target_revision), + location=location, + expected=target.get("entrypoint_path"), + ) + current_entry["active_revision"] = target_revision + current_entry["rollback_revision"] = previous_revision + _record_doctor(current_entry, target_revision, doctor) + # Rollback switches the active revision only; it does not undo an + # operator's enable/disable decision, including one that completed + # while the probe ran. The result must report what was committed + # here, not the pre-probe snapshot. + enabled = bool(current_entry.get("enabled")) + _write_state(path, current_state) + return { + "ok": True, + "schema_version": EXTENSION_OPERATION_SCHEMA_VERSION, + "operation": "rollback", + "dry_run": not execute, + "changed": execute, + "extension_id": extension_id, + "version": target.get("version"), + "revision": target_revision, + "previous_revision": previous_revision, + "enabled": enabled, + "doctor": doctor, + } + + +def _status_doctor_verified(entry: Mapping[str, object]) -> bool: + if not entry.get("enabled"): + return False + # Resolve proof before parsing the active manifest; a valid proof must + # still match this runtime's extension API. + active_revision = str(entry.get("active_revision") or "") + if entry.get("doctor_verified_revision") != active_revision: + return False + try: + snapshot = _entry_for_revision(entry, active_revision) + except ValueError: + return False + raw_manifest = snapshot.get("manifest") + if not isinstance(raw_manifest, Mapping): + return False + manifest = _coerce_object_dict(raw_manifest) + verified: ResolvedRuntimeEntrypoint | None = _verified_entrypoint( + entry, + active_revision=active_revision, + snapshot=snapshot, + manifest=manifest, + ) + if verified is None: + return False + return _manifest_incompatibility(entry, manifest) is None + + +def extension_status( + *, + state_file: str | Path, + extension_id: str | None = None, +) -> dict[str, object]: + state = _read_state(Path(state_file).expanduser()) + entries = _extensions_dict(state) + if extension_id is not None: + entry = entries.get(extension_id) + if not isinstance(entry, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + visible = [entry] + else: + visible = [entry for entry in entries.values() if isinstance(entry, dict)] + rows: list[dict[str, object]] = [] + for entry in visible: + raw_revisions = entry.get("revisions") + revision_count = len(raw_revisions) if isinstance(raw_revisions, list) else 0 + rows.append( + { + "id": entry.get("id"), + "enabled": bool(entry.get("enabled")), + "active_revision": entry.get("active_revision"), + "rollback_available": bool(entry.get("rollback_revision")), + "doctor_verified": _status_doctor_verified(entry), + "revision_count": revision_count, + } + ) + return { + "ok": True, + "schema_version": EXTENSION_STATE_SCHEMA_VERSION, + "extensions": rows, + } + + +def doctor_installed_extension( + extension_id: str, + *, + state_file: str | Path, + execute: bool = False, +) -> dict[str, object]: + path = Path(state_file).expanduser() + state = _read_state(path) + entry = _extensions_dict(state).get(extension_id) + if not isinstance(entry, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + if not entry.get("enabled"): + return { + "ok": True, + "schema_version": EXTENSION_DOCTOR_SCHEMA_VERSION, + "extension_id": extension_id, + "status": "disabled", + "available": False, + "verified": False, + "entrypoint_identity": None, + "failure_kind": None, + "external_writes_performed": False, + } + active_revision, snapshot, manifest = _active_snapshot_and_manifest(entry) + incompatibility = _manifest_incompatibility(entry, manifest) + if incompatibility is not None: + # The snapshot was valid for the runtime that installed it; this + # runtime's extension API moved. No probe can repair that, so the + # doctor fails closed and, when executed, revokes the stale proof. + raw_provider = manifest.get("provider") + version = ( + raw_provider.get("version") if isinstance(raw_provider, Mapping) else None + ) + doctor: dict[str, object] = { + "ok": True, + "schema_version": EXTENSION_DOCTOR_SCHEMA_VERSION, + "extension_id": extension_id, + "version": version, + "status": "api_incompatible", + "available": False, + "verified": False, + "entrypoint_identity": None, + "probed_entrypoint_identity": None, + "failure_kind": "api_incompatible", + "reason": incompatibility, + "external_writes_performed": False, + } + location: str | None = None + else: + doctor, location = probe_runtime_location( + manifest, location=snapshot.get("entrypoint_path"), execute=execute + ) + if execute: + _commit_locked_doctor_update( + path, + extension_id, + active_revision=active_revision, + expected_enabled=True, + doctor=doctor, + location=location, + expected_location=snapshot.get("entrypoint_path"), + operation_label="doctor", + clear_verified_proof=incompatibility is not None, + ) + return doctor + + +def doctor_enabled_extensions( + *, + state_file: str | Path, + execute: bool = False, +) -> dict[str, object]: + """Revalidate every enabled extension after a runtime release transition. + + Extension doctors are declared read-only provider probes. Running them as + one bounded batch lets installers and rollback paths refresh the runtime + identity without weakening the fail-closed activation fence. + """ + path = Path(state_file).expanduser() + state = _read_state(path) + extension_ids = sorted( + str(extension_id) + for extension_id, entry in _extensions_dict(state).items() + if isinstance(entry, Mapping) and entry.get("enabled") + ) + doctors = [ + doctor_installed_extension( + extension_id, + state_file=path, + execute=execute, + ) + for extension_id in extension_ids + ] + verified_count = sum(bool(doctor.get("verified")) for doctor in doctors) + blocked_count = len(doctors) - verified_count if execute else 0 + return { + "ok": blocked_count == 0, + "schema_version": EXTENSION_DOCTOR_BATCH_SCHEMA_VERSION, + "status": ( + "ready" + if execute and blocked_count == 0 + else "blocked" + if execute + else "probe_required" + if doctors + else "ready" + ), + "execute": execute, + "enabled_count": len(doctors), + "verified_count": verified_count, + "blocked_count": blocked_count, + "extensions": doctors, + "local_state_write_performed": execute and bool(doctors), + "external_writes_performed": False, + } + + +def _catalog_entry_snapshot( + manifest: Mapping[str, object], + lifecycle_state: Mapping[str, object], +) -> ExtensionCatalogEntry: + normalized = deepcopy(dict(manifest)) + provider_raw = normalized.get("provider") + provider_map = dict(provider_raw) if isinstance(provider_raw, Mapping) else {} + provider_map.update(lifecycle_state) + normalized["provider"] = provider_map + return cast(ExtensionCatalogEntry, normalized) + + +def extension_catalog_entries( + extension_manifest_paths: Iterable[str | Path] = (), + *, + state_file: str | Path | None = None, +) -> list[ExtensionCatalogEntry]: + """Compose declared manifests with installed runtime lifecycle state.""" + manifests: dict[str, Mapping[str, object]] = {} + lifecycle: dict[str, dict[str, object]] = {} + for manifest_path in extension_manifest_paths: + declared_manifest = load_extension_manifest(manifest_path) + declared_provider = declared_manifest.get("provider") + if not isinstance(declared_provider, Mapping): + raise ValueError("extension active manifest is invalid") + extension_id = str(declared_provider["id"]) + if extension_id in manifests: + raise ValueError(f"duplicate capability provider `{extension_id}`") + manifests[extension_id] = declared_manifest + lifecycle[extension_id] = { + "declared": True, + "installed": False, + "enabled": False, + "ready": False, + } + + if state_file is not None: + state = _read_state(Path(state_file).expanduser()) + for extension_id, entry in _extensions_dict(state).items(): + if not isinstance(entry, Mapping): + raise ValueError(f"extension `{extension_id}` runtime entry is invalid") + active_revision, snapshot, active_manifest = _active_snapshot_and_manifest( + entry + ) + provider = active_manifest.get("provider") + if not isinstance(provider, Mapping) or provider.get("id") != extension_id: + raise ValueError(f"extension `{extension_id}` active manifest is invalid") + declared = manifests.get(extension_id) + if declared is not None and _revision(declared) != active_revision: + # Two different manifests for one id: the installed state is + # the lifecycle source, so a declaration may only repeat it. + raise ValueError( + f"duplicate capability provider `{extension_id}`: declared " + f"manifest revision `{_revision(declared)}` differs from the " + f"installed active revision `{active_revision}`" + ) + manifests[extension_id] = active_manifest + enabled = bool(entry.get("enabled")) + compatible = _manifest_incompatibility(entry, active_manifest) is None + verified = ( + enabled + and compatible + and _verified_entrypoint( + entry, + active_revision=active_revision, + snapshot=snapshot, + manifest=active_manifest, + ) + is not None + ) + lifecycle[extension_id] = { + "declared": True, + "installed": True, + "enabled": enabled, + "ready": verified, + "active_revision": active_revision, + } + + return [ + _catalog_entry_snapshot(manifest, lifecycle[extension_id]) + for extension_id, manifest in manifests.items() + ] + + +__all__ = [ + "_verified_identities", + "disable_extension", + "doctor_enabled_extensions", + "doctor_installed_extension", + "enable_extension", + "extension_catalog_entries", + "extension_status", + "install_extension", + "rollback_extension", +] diff --git a/loopx/extensions/runtime_state.py b/loopx/extensions/runtime_state.py new file mode 100644 index 0000000000..6f0b01ea30 --- /dev/null +++ b/loopx/extensions/runtime_state.py @@ -0,0 +1,376 @@ +"""Extension runtime state persistence, revision retention, and readiness helpers.""" + +from __future__ import annotations + +from collections.abc import Mapping +from copy import deepcopy +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +from typing import TypedDict + +from ..paths import select_default_runtime_root +from .manifest import loopx_api_incompatibility +from .readiness import ( + ResolvedRuntimeEntrypoint, + declared_view_validators, + extension_runtime, + resolve_runtime_entrypoint, +) +from .runtime_location import located_runtime + +EXTENSION_STATE_SCHEMA_VERSION = "loopx_extension_state_v0" +EXTENSION_OPERATION_SCHEMA_VERSION = "loopx_extension_operation_v0" +EXTENSION_BINDING_SCHEMA_VERSION = "loopx_extension_runtime_binding_v0" +EXTENSION_PROVIDER_READINESS_SCHEMA_VERSION = "loopx_extension_provider_readiness_v0" +EXTENSION_ACTIVATION_SCHEMA_VERSION = "loopx_extension_activation_v0" +EXTENSION_RUN_SCHEMA_VERSION = "loopx_extension_run_receipt_v0" +EXTENSION_DOCTOR_BATCH_SCHEMA_VERSION = "loopx_extension_doctor_batch_v0" +# Content-free lifecycle non-admission codes. Optional capability resolution +# reports them as `ExtensionCapabilityResolution.status`; hook-adapter discovery +# reuses them for declared adapters whose extension it does not activate. +EXTENSION_DISABLED_STATUS = "extension_disabled" +EXTENSION_DOCTOR_NOT_READY_STATUS = "extension_doctor_not_ready" +MAX_REVISIONS = 5 +# Requalification is required on eviction; unprobed artifacts never activate. +MAX_VERIFIED_ENTRYPOINTS = 32 +MAX_EXTENSION_REQUEST_BYTES = 1_000_000 +MAX_EXTENSION_RESPONSE_BYTES = 1_000_000 + + +class ExtensionRuntimeBinding(TypedDict): + """Strict runtime binding packet resolved from an active extension manifest.""" + + schema_version: str + extension_id: str + provider_version: object + revision: str + protocol: str + argv: list[str] + environment_path_prefix: str | None + doctor_argv: list[str] + timeout_seconds: int | float + + +class ExtensionHookAdapterEntry(TypedDict, total=False): + """Manifest hook adapter record consumed by hook adapter discovery.""" + + id: str + phase: str + capability_id: str + target_hook_id: str + factory: str + required_permissions: list[str] + ports: list[str] + + +class _ExtensionCatalogEntryBase(TypedDict): + provider: dict[str, object] + capabilities: list[dict[str, object]] + implementations: list[dict[str, object]] + + +class ExtensionCatalogEntry(_ExtensionCatalogEntryBase, total=False): + """Typed extension manifest enriched with lifecycle readiness metadata.""" + + runtime: dict[str, object] | None + hook_adapters: list[ExtensionHookAdapterEntry] + presentation_surfaces: list[dict[str, object]] + documentation: dict[str, object] | None + + +@dataclass(frozen=True) +class ExtensionCapabilityResolution: + """One atomic lifecycle/readiness snapshot for an optional provider.""" + + status: str + extension_id: str | None + installed: bool | None + enabled: bool | None + doctor_verified: bool | None + next_action: str | None + binding: Mapping[str, object] | None = None + + def __post_init__(self) -> None: + if (self.status == "ready") != (self.binding is not None): + raise ValueError( + "a ready extension capability resolution requires exactly one binding" + ) + + def public_readiness(self) -> dict[str, object]: + return { + "schema_version": EXTENSION_PROVIDER_READINESS_SCHEMA_VERSION, + "status": self.status, + "extension_id": self.extension_id, + "installed": self.installed, + "enabled": self.enabled, + "doctor_verified": self.doctor_verified, + "next_action": self.next_action, + } + + +def _coerce_object_dict(mapping: Mapping[object, object]) -> dict[str, object]: + return {str(key): value for key, value in mapping.items()} + + +def _coerce_runtime_mapping(mapping: Mapping[object, object]) -> Mapping[str, object]: + if all(isinstance(key, str) for key in mapping): + return {str(key): value for key, value in mapping.items()} + return _coerce_object_dict(mapping) + + +def default_extension_state_file(runtime_root: str | Path | None = None) -> Path: + root = ( + Path(runtime_root).expanduser() + if runtime_root is not None + else select_default_runtime_root() + ) + return root / "extensions" / "state.json" + + +def _empty_state() -> dict[str, object]: + return { + "schema_version": EXTENSION_STATE_SCHEMA_VERSION, + "extensions": {}, + } + + +def _read_state(path: Path) -> dict[str, object]: + if not path.exists(): + return _empty_state() + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise ValueError("extension runtime state is unreadable") from exc + if ( + not isinstance(payload, dict) + or payload.get("schema_version") != EXTENSION_STATE_SCHEMA_VERSION + or not isinstance(payload.get("extensions"), dict) + ): + raise ValueError( + f"extension runtime state must use {EXTENSION_STATE_SCHEMA_VERSION}" + ) + return _coerce_object_dict(payload) + + +def _extensions_dict(state: Mapping[str, object]) -> dict[str, object]: + raw = state.get("extensions") + if not isinstance(raw, dict): + raise ValueError( + f"extension runtime state must use {EXTENSION_STATE_SCHEMA_VERSION}" + ) + return raw + + +def _write_state(path: Path, payload: Mapping[str, object]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}") + temporary.write_text( + json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + temporary.chmod(0o600) + os.replace(temporary, path) + + +def _revision(manifest: Mapping[str, object]) -> str: + serialized = json.dumps( + manifest, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ) + return hashlib.sha256(serialized.encode("utf-8")).hexdigest()[:16] + + +def _runtime(manifest: Mapping[str, object]) -> Mapping[str, object]: + return extension_runtime(manifest) + + +def _manifest_snapshot(manifest: Mapping[str, object]) -> dict[str, object]: + return deepcopy(dict(manifest)) + + +def _entry_for_revision(entry: Mapping[str, object], revision: str) -> dict[str, object]: + revisions = entry.get("revisions") + if not isinstance(revisions, list): + raise ValueError("extension revision history is invalid") + for item in revisions: + if isinstance(item, dict) and item.get("revision") == revision: + return item + raise ValueError("extension active revision is missing") + + +def _retain_revisions( + revisions: list[dict[str, object]], + new_revision: dict[str, object], + *, + required_revision: str | None, +) -> list[dict[str, object]]: + deduplicated = [ + item + for item in revisions + if item.get("revision") != new_revision.get("revision") + ] + required = next( + ( + item + for item in deduplicated + if required_revision and item.get("revision") == required_revision + ), + None, + ) + retained = [*deduplicated, new_revision][-MAX_REVISIONS:] + if required is not None and required not in retained: + retained = [required, *retained[-(MAX_REVISIONS - 1) :]] + return retained + + +def _verified_identities(entry: Mapping[str, object], revision: str) -> list[str]: + if entry.get("doctor_verified_revision") != revision: + return [] + identities = entry.get("doctor_verified_entrypoint_identities") + if identities is None: + # Read legacy state without rewriting it during status/activation. + identities = [entry.get("doctor_verified_entrypoint_identity")] + if not isinstance(identities, list): + return [] + return list( + dict.fromkeys( + identity for identity in identities if isinstance(identity, str) and identity + ) + )[-MAX_VERIFIED_ENTRYPOINTS:] + + +def _record_doctor( + entry: dict[str, object], revision: str, doctor: Mapping[str, object] +) -> None: + identities = _verified_identities(entry, revision) + identity = doctor.get("probed_entrypoint_identity") + if doctor.get("verified") is True: + identity = doctor.get("entrypoint_identity") + if isinstance(identity, str) and identity: + identities = [value for value in identities if value != identity] + if doctor.get("verified") is True: + identities.append(identity) + entry.pop("doctor_verified_entrypoint_identity", None) + if identities: + entry["doctor_verified_revision"] = revision + entry["doctor_verified_entrypoint_identities"] = identities[ + -MAX_VERIFIED_ENTRYPOINTS: + ] + else: + entry.pop("doctor_verified_revision", None) + entry.pop("doctor_verified_entrypoint_identities", None) + + +def _active_snapshot_and_manifest( + entry: Mapping[str, object], +) -> tuple[str, dict[str, object], Mapping[str, object]]: + active_revision = str(entry.get("active_revision") or "") + snapshot = _entry_for_revision(entry, active_revision) + manifest = snapshot.get("manifest") + if not isinstance(manifest, Mapping): + raise ValueError("extension active manifest is invalid") + return active_revision, snapshot, _coerce_runtime_mapping(manifest) + + +def _verified_entrypoint( + entry: Mapping[str, object], + *, + active_revision: str | None = None, + snapshot: Mapping[str, object] | None = None, + manifest: Mapping[str, object] | None = None, +) -> ResolvedRuntimeEntrypoint | None: + resolved_revision = ( + str(entry.get("active_revision") or "") + if active_revision is None + else active_revision + ) + if entry.get("doctor_verified_revision") != resolved_revision: + return None + if snapshot is None: + try: + snapshot = _entry_for_revision(entry, resolved_revision) + except ValueError: + return None + resolved_manifest: Mapping[str, object] + if manifest is None: + raw_manifest = snapshot.get("manifest") + if not isinstance(raw_manifest, Mapping): + return None + resolved_manifest = _coerce_runtime_mapping(raw_manifest) + else: + resolved_manifest = manifest + runtime = located_runtime(resolved_manifest, snapshot.get("entrypoint_path")) + identity = resolve_runtime_entrypoint( + runtime, + view_validators=declared_view_validators(resolved_manifest), + ) + if identity is None or identity.identity not in _verified_identities( + entry, resolved_revision + ): + return None + return identity + + +def _active_manifest(entry: Mapping[str, object]) -> Mapping[str, object]: + _, _, manifest = _active_snapshot_and_manifest(entry) + return manifest + + +def _manifest_incompatibility( + entry: Mapping[str, object], + manifest: Mapping[str, object], +) -> str | None: + provider = manifest.get("provider") + if not isinstance(provider, Mapping): + return "extension active manifest is incomplete" + extension_id = str(provider.get("id") or entry.get("id") or "") + return loopx_api_incompatibility( + provider.get("requires_loopx_api"), + context=f"extension `{extension_id}` active manifest", + ) + + +def _active_manifest_incompatibility(entry: Mapping[str, object]) -> str | None: + """Re-check the installed snapshot against the runtime reading it. + + `install`/`upgrade` validate `requires_loopx_api` when they load the + manifest, but the saved copy outlives that runtime. A later LoopX whose + extension API moved must treat the snapshot as incompatible, not ready. + """ + return _manifest_incompatibility(entry, _active_manifest(entry)) + + +def _resolved_active_extension( + extension_id: str, + *, + state_file: str | Path, +) -> tuple[str, ResolvedRuntimeEntrypoint, Mapping[str, object]]: + state = _read_state(Path(state_file).expanduser()) + entry = _extensions_dict(state).get(extension_id) + if not isinstance(entry, dict): + raise ValueError(f"extension `{extension_id}` is not installed") + if not entry.get("enabled"): + raise ValueError(f"extension `{extension_id}` is disabled") + active_revision, snapshot, manifest = _active_snapshot_and_manifest(entry) + incompatibility = _manifest_incompatibility(entry, manifest) + if incompatibility is not None: + raise ValueError( + f"{incompatibility}; upgrade to a compatible manifest or roll back" + ) + verified_entrypoint = _verified_entrypoint( + entry, + active_revision=active_revision, + snapshot=snapshot, + manifest=manifest, + ) + if verified_entrypoint is None: + raise ValueError( + f"extension `{extension_id}` doctor readiness is stale; run " + f"`loopx extension doctor {extension_id} --execute`" + ) + return active_revision, verified_entrypoint, manifest diff --git a/tests/extensions/test_extension_runtime_contract.py b/tests/extensions/test_extension_runtime_contract.py new file mode 100644 index 0000000000..69078b0914 --- /dev/null +++ b/tests/extensions/test_extension_runtime_contract.py @@ -0,0 +1,464 @@ +"""Contract, budget, efficiency, and negative-path tests for extension runtime modules.""" + +from __future__ import annotations + +import ast +from collections.abc import Mapping +from copy import deepcopy +import json +from pathlib import Path +import re +import sys +from types import MappingProxyType +import pytest + +from loopx.extensions import ( + manifest as ext_manifest, + process_runtime as ext_process, + runtime as ext_runtime, + runtime_bindings as ext_bindings, + runtime_lifecycle as ext_lifecycle, + runtime_state as ext_state, +) +from loopx.extensions.process_runtime import CappedProcessResult +from loopx.extensions.readiness import ResolvedRuntimeEntrypoint + + +def _write_provider_script(path: Path, *, doctor_exit: int = 0) -> Path: + path.write_text( + f"#!{sys.executable}\n" + "import json, sys\n" + f"if '--doctor' in sys.argv:\n raise SystemExit({doctor_exit})\n" + "req = json.load(sys.stdin)\n" + "json.dump({'ok': True, 'echo': req.get('msg')}, sys.stdout)\n", + encoding="utf-8", + ) + path.chmod(0o755) + return path + + +def _write_manifest( + path: Path, + *, + entrypoint: Path, + extension_id: str = "ext-contract", + version: str = "1.0.0", + requires_api: str = ">=1,<2", + permissions: list[str] | None = None, + protocol: str = "cap_v0", + capability_id: str | None = None, + implements_count: int = 1, +) -> Path: + perms = list(permissions or []) + lines = [ + 'schema_version = "loopx_extension_manifest_v0"', + f"id = {json.dumps(extension_id)}", + f"version = {json.dumps(version)}", + f"requires_loopx_api = {json.dumps(requires_api)}", + f"permissions = {json.dumps(perms)}", + "", + "[runtime]", + f"protocol = {json.dumps(protocol)}", + f"entrypoint = {json.dumps(str(entrypoint))}", + 'doctor_args = ["--doctor"]', + f"required_permissions = {json.dumps(perms)}", + "timeout_seconds = 5", + ] + if capability_id is not None: + lines += [ + "", + "[[provides]]", + f"id = {json.dumps(capability_id)}", + 'kind = "advisory"', + ] + for _ in range(implements_count): + lines += [ + "", + "[[implements]]", + f"capability_id = {json.dumps(capability_id)}", + f"protocol = {json.dumps(protocol)}", + ] + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return path + + +def test_extension_runtime_module_budgets_and_reexports() -> None: + root = Path(ext_runtime.__file__).resolve().parents[2] + targets = [ + ("loopx/extensions/runtime.py", 650), + ("loopx/extensions/runtime_state.py", 750), + ("loopx/extensions/runtime_lifecycle.py", 750), + ("loopx/extensions/runtime_bindings.py", 750), + ("tests/extensions/test_extension_runtime_contract.py", 700), + ] + internal_edges: dict[str, set[str]] = {} + for rel, limit in targets: + path = root / rel + src = path.read_text(encoding="utf-8") + lines = src.splitlines() + assert len(lines) <= limit, f"{rel} exceeded {limit} LOC ({len(lines)})" + assert not re.search(r"#\s*type:\s*ignore", src), f"type ignore in {rel}" + assert not re.search(r"#\s*noqa\b", src), f"noqa in {rel}" + tree = ast.parse(src, filename=str(path)) + assert not any( + isinstance(node, ast.Name) and node.id == "Any" for node in ast.walk(tree) + ), f"AST Any present in {rel}" + internal_edges[path.stem] = { + node.module + for node in ast.walk(tree) + if isinstance(node, ast.ImportFrom) + and node.module + and node.module.startswith("runtime") + } + + assert not ( + internal_edges["runtime_state"] & {"runtime", "runtime_lifecycle", "runtime_bindings"} + ) + assert "runtime" not in internal_edges["runtime_lifecycle"] + assert "runtime" not in internal_edges["runtime_bindings"] + + assert ext_runtime.ExtensionCapabilityResolution is ext_state.ExtensionCapabilityResolution + assert ext_runtime.ExtensionCatalogEntry is ext_state.ExtensionCatalogEntry + assert ext_runtime.ExtensionHookAdapterEntry is ext_state.ExtensionHookAdapterEntry + assert ext_runtime.ExtensionRuntimeBinding is ext_state.ExtensionRuntimeBinding + assert ext_runtime.default_extension_state_file is ext_state.default_extension_state_file + assert ext_runtime._resolved_active_extension is ext_state._resolved_active_extension + assert ext_runtime.run_capped_process is ext_process.run_capped_process + for name in ( + "install_extension", + "enable_extension", + "disable_extension", + "rollback_extension", + "extension_status", + "doctor_installed_extension", + "doctor_enabled_extensions", + "extension_catalog_entries", + ): + assert getattr(ext_runtime, name) is getattr(ext_lifecycle, name) + for name in ( + "resolve_capability_extension_id", + "resolve_extension_activation", + "resolve_extension_binding", + "resolve_optional_capability_binding", + "resolve_extension_runtime_binding", + "resolve_capability_binding", + ): + assert getattr(ext_runtime, name) is getattr(ext_bindings, name) + + +def test_extension_capability_resolution_and_state_validation(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="requires exactly one binding"): + ext_runtime.ExtensionCapabilityResolution( + status="ready", + extension_id="ext-1", + installed=True, + enabled=True, + doctor_verified=True, + next_action=None, + binding=None, + ) + with pytest.raises(ValueError, match="requires exactly one binding"): + ext_runtime.ExtensionCapabilityResolution( + status="extension_disabled", + extension_id="ext-1", + installed=True, + enabled=False, + doctor_verified=False, + next_action="enable_extension", + binding={"schema_version": ext_runtime.EXTENSION_BINDING_SCHEMA_VERSION}, + ) + res = ext_runtime.ExtensionCapabilityResolution( + status="ready", + extension_id="ext-1", + installed=True, + enabled=True, + doctor_verified=True, + next_action=None, + binding=MappingProxyType({"extension_id": "ext-1"}), + ) + assert res.public_readiness()["status"] == "ready" + + retained = ext_state._retain_revisions( + [{"revision": f"r{idx}"} for idx in range(7)], + {"revision": "r7"}, + required_revision="r0", + ) + assert [row["revision"] for row in retained][0] == "r0" + assert len(retained) == ext_state.MAX_REVISIONS + + legacy_entry = { + "doctor_verified_revision": "r1", + "doctor_verified_entrypoint_identity": "id-legacy", + } + assert ext_state._verified_identities(legacy_entry, "r1") == ["id-legacy"] + + bad_state = tmp_path / "bad-state.json" + bad_state.write_text("{not json", encoding="utf-8") + with pytest.raises(ValueError, match="unreadable"): + ext_state._read_state(bad_state) + bad_state.write_text(json.dumps({"schema_version": "wrong", "extensions": {}}), encoding="utf-8") + with pytest.raises(ValueError, match=ext_state.EXTENSION_STATE_SCHEMA_VERSION): + ext_state._read_state(bad_state) + + +def test_efficiency_single_read_and_single_revision_scan_per_entry( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + provider = _write_provider_script(tmp_path / "provider.py") + manifest = _write_manifest( + tmp_path / "ext.toml", + entrypoint=provider, + extension_id="ext-eff", + permissions=["cap.read"], + capability_id="cap-eff", + ) + state_file = tmp_path / "state.json" + installed = ext_runtime.install_extension(manifest, state_file=state_file, execute=True) + assert installed["changed"] is True + + read_calls = 0 + rev_calls = 0 + deepcopy_calls = 0 + verify_calls = 0 + orig_read = ext_state._read_state + orig_rev = ext_state._entry_for_revision + orig_deepcopy = deepcopy + orig_verify = ext_state._verified_entrypoint + + def count_read(path: Path) -> dict[str, object]: + nonlocal read_calls + read_calls += 1 + return orig_read(path) + + def count_rev(entry: Mapping[str, object], revision: str) -> dict[str, object]: + nonlocal rev_calls + rev_calls += 1 + return orig_rev(entry, revision) + + def count_deepcopy(obj: object) -> object: + nonlocal deepcopy_calls + deepcopy_calls += 1 + return orig_deepcopy(obj) + + def count_verify( + entry: Mapping[str, object], + *, + active_revision: str | None = None, + snapshot: Mapping[str, object] | None = None, + manifest: Mapping[str, object] | None = None, + ) -> ResolvedRuntimeEntrypoint | None: + nonlocal verify_calls + verify_calls += 1 + return orig_verify( + entry, + active_revision=active_revision, + snapshot=snapshot, + manifest=manifest, + ) + + monkeypatch.setattr(ext_bindings, "_read_state", count_read) + monkeypatch.setattr(ext_lifecycle, "_read_state", count_read) + monkeypatch.setattr(ext_state, "_entry_for_revision", count_rev) + monkeypatch.setattr(ext_lifecycle, "_entry_for_revision", count_rev) + monkeypatch.setattr(ext_lifecycle, "deepcopy", count_deepcopy) + monkeypatch.setattr(ext_bindings, "_verified_entrypoint", count_verify) + monkeypatch.setattr(ext_lifecycle, "_verified_entrypoint", count_verify) + + # resolve_capability_binding: 1 state read, 1 revision lookup, 0 deepcopies. + binding = ext_runtime.resolve_capability_binding( + state_file=state_file, + capability_id="cap-eff", + protocol="cap_v0", + permission="cap.read", + ) + assert binding["extension_id"] == "ext-eff" + assert read_calls == 1 and rev_calls == 1 and deepcopy_calls == 0 + + # resolve_optional_capability_binding (auto-discovery): 1 state read, 1 revision lookup, 1 verify. + read_calls = rev_calls = verify_calls = 0 + opt = ext_runtime.resolve_optional_capability_binding( + state_file=state_file, + capability_id="cap-eff", + protocol="cap_v0", + permission="cap.read", + ) + assert opt.status == "ready" + assert read_calls == 1 and rev_calls == 1 and verify_calls == 1 + + # extension_catalog_entries: 1 revision scan & 1 deepcopy per entry, caller mutation isolated. + rev_calls = deepcopy_calls = verify_calls = 0 + catalog = ext_runtime.extension_catalog_entries(state_file=state_file) + assert len(catalog) == 1 and rev_calls == 1 and deepcopy_calls == 1 and verify_calls == 1 + perms = catalog[0]["provider"]["permissions"] + assert isinstance(perms, list) + perms.append("mutated-by-caller") + assert ext_runtime.extension_catalog_entries(state_file=state_file)[0]["provider"]["permissions"] == ["cap.read"] + + # doctor_installed_extension (dry-run): 1 revision scan before probe. + rev_calls = 0 + doc_dry = ext_runtime.doctor_installed_extension("ext-eff", state_file=state_file, execute=False) + assert doc_dry["available"] is True and doc_dry["status"] == "probe_required" and rev_calls == 1 + doc_exec = ext_runtime.doctor_installed_extension("ext-eff", state_file=state_file, execute=True) + assert doc_exec["verified"] is True and rev_calls == 3 + + +def test_lifecycle_rollback_api_guard_and_runtime_failure_modes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + provider = _write_provider_script(tmp_path / "provider.py") + v1 = _write_manifest( + tmp_path / "v1.toml", + entrypoint=provider, + extension_id="ext-solo", + version="1.0.0", + protocol="solo_v0", + ) + v2 = _write_manifest( + tmp_path / "v2.toml", + entrypoint=provider, + extension_id="ext-solo", + version="2.0.0", + protocol="solo_v0", + ) + state_file = tmp_path / "state.json" + + with pytest.raises(ValueError, match="install or upgrade"): + ext_runtime.install_extension(v1, state_file=state_file, operation="reinstall") + ext_runtime.install_extension(v1, state_file=state_file, execute=True) + with pytest.raises(ValueError, match="has no rollback revision"): + ext_runtime.rollback_extension("ext-solo", state_file=state_file, execute=True) + + ext_runtime.install_extension(v2, state_file=state_file, operation="upgrade", execute=True) + # Force rollback manifest incompatible API and confirm rollback fails closed before switching. + raw = ext_state._read_state(state_file) + entry = ext_state._extensions_dict(raw)["ext-solo"] + assert isinstance(entry, dict) + target = ext_state._entry_for_revision(entry, str(entry["rollback_revision"])) + manifest_obj = target["manifest"] + assert isinstance(manifest_obj, dict) and isinstance(manifest_obj["provider"], dict) + manifest_obj["provider"]["requires_loopx_api"] = ">=99,<100" + ext_state._write_state(state_file, raw) + with pytest.raises(ValueError, match="roll forward"): + ext_runtime.rollback_extension("ext-solo", state_file=state_file, execute=True) + + # Valid standalone dry-run/execute + capped process failure modes via run_capped_process seam. + dry = ext_runtime.run_standalone_extension( + "ext-solo", + state_file=state_file, + request=MappingProxyType({"schema_version": "req_v0"}), + execute=False, + ) + assert dry["status"] == "ready" and dry["dry_run"] is True + + monkeypatch.setattr( + ext_runtime, + "run_capped_process", + lambda *_a, **_kw: CappedProcessResult(stdout=b"", stderr=b"", returncode=-1, failure_kind="timeout"), + ) + timed_out = ext_runtime.run_standalone_extension( + "ext-solo", state_file=state_file, request={"msg": "slow"}, execute=True + ) + assert timed_out["ok"] is False and timed_out["failure_kind"] == "timeout" and timed_out["exit_code"] is None + + monkeypatch.setattr( + ext_runtime, + "run_capped_process", + lambda *_a, **_kw: (_ for _ in ()).throw(OSError("spawn failed")), + ) + failed_spawn = ext_runtime.run_standalone_extension( + "ext-solo", state_file=state_file, request={"msg": "err"}, execute=True + ) + assert failed_spawn["failure_kind"] == "execution_failed" + + monkeypatch.setattr( + ext_runtime, + "run_capped_process", + lambda *_a, **_kw: CappedProcessResult(stdout=b"{bad", stderr=b"", returncode=0, failure_kind=None), + ) + bad_json = ext_runtime.run_standalone_extension( + "ext-solo", state_file=state_file, request={"msg": "badjson"}, execute=True + ) + assert bad_json["failure_kind"] == "response_not_json_object" + + # Binding execution negative validations (fail closed). + valid_binding: ext_runtime.ExtensionRuntimeBinding = { + "schema_version": ext_runtime.EXTENSION_BINDING_SCHEMA_VERSION, + "extension_id": "ext-solo", + "provider_version": "2.0.0", + "revision": "rev", + "protocol": "solo_v0", + "argv": [str(provider)], + "environment_path_prefix": None, + "doctor_argv": [str(provider), "--doctor"], + "timeout_seconds": 5, + } + with pytest.raises(ValueError, match="argv is invalid"): + ext_runtime.execute_extension_runtime_binding({**valid_binding, "argv": []}, request={}) + with pytest.raises(ValueError, match="timeout is invalid"): + ext_runtime.execute_extension_runtime_binding({**valid_binding, "timeout_seconds": True}, request={}) + with pytest.raises(ValueError, match="timeout is invalid"): + ext_runtime.execute_extension_runtime_binding({**valid_binding, "timeout_seconds": float("nan")}, request={}) + with pytest.raises(ValueError, match="search directory must be absolute"): + ext_runtime.execute_extension_runtime_binding({**valid_binding, "environment_path_prefix": 123}, request={}) + with pytest.raises(RuntimeError, match="invalid JSON"): + ext_runtime.execute_extension_runtime_binding(valid_binding, request={}) + + # Silence unused import check while anchoring manifest version coupling. + assert ext_manifest.EXTENSION_MANIFEST_SCHEMA_VERSION == "loopx_extension_manifest_v0" + + +def test_duplicate_implements_rejects_auto_explicit_and_optional_consistently( + tmp_path: Path, +) -> None: + provider = _write_provider_script(tmp_path / "dup_provider.py") + manifest = _write_manifest( + tmp_path / "dup_manifest.toml", + entrypoint=provider, + extension_id="ext-dup", + permissions=["read_state"], + protocol="dup_v0", + capability_id="cap.dup", + implements_count=2, + ) + state_file = tmp_path / "ext_state.json" + install = ext_runtime.install_extension(manifest, state_file=state_file, execute=True) + assert install["changed"] is True + assert install["enabled"] is True + assert ( + ext_runtime.resolve_capability_extension_id( + state_file=state_file, + capability_id="cap.dup", + protocol="dup_v0", + ) + == "ext-dup" + ) + with pytest.raises(ValueError, match="does not implement"): + ext_runtime.resolve_capability_binding( + state_file=state_file, + capability_id="cap.dup", + protocol="dup_v0", + permission="read_state", + ) + with pytest.raises(ValueError, match="does not implement"): + ext_runtime.resolve_extension_binding( + "ext-dup", + state_file=state_file, + capability_id="cap.dup", + protocol="dup_v0", + permission="read_state", + ) + for explicit_id in (None, "ext-dup"): + opt = ext_runtime.resolve_optional_capability_binding( + state_file=state_file, + capability_id="cap.dup", + protocol="dup_v0", + permission="read_state", + extension_id=explicit_id, + ) + assert opt.status == "extension_incompatible" + assert opt.extension_id == "ext-dup" + assert opt.installed is True + assert opt.enabled is True + assert opt.doctor_verified is True + assert opt.next_action == "install_compatible_extension" + assert opt.binding is None