diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index 8421b2ee5e..9a364a42db 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -264,9 +264,15 @@ jobs: python -m pytest -q --no-cov tests/test_stage2c_dependency_lock.py tests/architecture/test_top_level_module_budget.py + tests/architecture/test_external_request_lint.py tests/test_repository_instruction_delivery.py tests/test_contributing_guide.py + - name: Lint external request dispatch boundaries + run: | + python -m ruff check --ignore-noqa --config scripts/ci/external-request-lint.toml loopx packages scripts apps + python -m ruff check --ignore-noqa --config scripts/ci/external-transport-lint.toml loopx packages/*/src + - name: Lint test suite run: >- python -m ruff check @@ -308,6 +314,9 @@ jobs: - name: Install test dependencies run: python -m pip install --disable-pip-version-check -e ".[test]" + - name: Check external provider recovery + run: python -m pytest -q --no-cov tests/extensions/test_governed_capability_execution.py + - name: Verify file authority on the core runtime run: >- node --no-warnings --experimental-strip-types --test @@ -372,6 +381,12 @@ jobs: python -m pip install --disable-pip-version-check -e ".[test]" npm ci --ignore-scripts + - name: Lint external JS and TS transports + if: matrix.shard == 1 + run: | + node --test scripts/ci/lint-external-transports.test.mjs + node scripts/ci/lint-external-transports.mjs + - name: Type-check the TypeScript Effect core if: matrix.shard == 1 run: npm run typecheck:control-plane diff --git a/docs/reference/extensions.md b/docs/reference/extensions.md index 1f9aad11af..71a2bc06ad 100644 --- a/docs/reference/extensions.md +++ b/docs/reference/extensions.md @@ -546,15 +546,88 @@ materialized proposal is checkpointed immediately. Monitor upserts belong to the pre-settlement phase; monitor completion belongs to the post-settlement phase. A crash between either Todo write and its checkpoint recovers by the proposal's stable monitor key and completion identity instead of duplicating -work. A crash after an external -effect replays with the same idempotency key and reconciles the receipt instead -of starting an unrelated operation. One settlement effect id owns exactly one +work. If the journal contains an armed start intent but no accepted provider result, +a second start is refused, including with the original idempotency key. A trusted +integration may pass `read_start_result` to `start_governed_external_capability` +with the original request and current admission to look up the original +operation by provider, invocation, effect key and request digest. This callback +must only observe the original operation. An unresolved lookup returns `None`; +the journal is retained and no quota is spent. A matching result goes through +the normal provider-result validation, asynchronous polling and settlement. +For a provider without reliable lookup, the operation remains unresolved. +In a shared run directory, an unsettled write for the same Goal, Todo, +capability and operation also holds starts from a different Agent or Turn. +The error identifies the original invocation. The reservation index is built +from existing journals on first use. Quiesce older writers when upgrading +and retain the run directory during handoff. A new independently admitted +Turn can start after the prior invocation has committed. Separate business +intents across Todos or run directories still need provider-level identity. + +**Recovery from an older backup.** `backup-state verify --execute` leaves a +`.loopx-restored-inert` entry in each extracted runtime root. Keep it when +copying the runtime. The verified copy grants no execution authority. The +governed writer checks the Goal's source and invoked runtime as well as the +journal path, including when an integration selects a different run directory. +Ordinary fresh start and its preview on that runtime report that provider +reconciliation is required. A running operation requires a trusted +`read_running_result(request)` for polling on a restored runtime. + +A successor with current runnable admission for the same Goal, Todo and +applicable operation can supply the original invocation arguments and +`read_start_result`. The result retains the original effect identity for +writeback and quota. On a restored runtime, even if the backup predates the +journal, the trusted service lookup must return `{request_digest, target_key, result}` from its own +records, with the original digest, admitted target, and matching typed provider +result. An unknown result, a mismatched identity or a missing original team +plan basis holds recovery. Readback alone never dispatches a new start. + +When the service can prove the prior attempt reached a terminal state without +an effect, a trusted integration may supply `reserve_restored_start(query)`. +The query contains the original-form provider request, the admitted target, +a stable operation key (Goal, capability, operation and target), an intent +digest (Goal binding, provider, context and input), the current request digest, +invocation id and a fresh challenge. The service must check the business +operation across all prior attempts, fence any outstanding writer, and +atomically grant **one** conditional start. Its receipt must echo +`operation_key`, `intent_digest`, `request_digest`, `invocation_id` and +`challenge`, set `status` to `reserved_after_terminal_no_effect`, and include +a bounded non-secret `reservation_ref`. The provider must validate and +consume this grant atomically with delivery, using +`request.lifecycle.restored_start_reservation`. An empty lookup, timeout or +cached grant does not authorize dispatch. While obtaining the grant, the local +journal remains unarmed. If the process exits here, the original or successor +Turn can ask the service again. The service must reconcile any outstanding +grant by operation and intent and fence the old grant before issuing a fresh +one. LoopX publishes the validated grant and the armed state in one durable +checkpoint immediately before calling the provider. After that point an +unknown delivery requires original-result readback. Older armed records with +no saved grant also require service reconciliation: local state alone cannot +establish whether an older writer sent the request. Integrations without a +suitable service primitive stay held. + +The interlock covers runtime copies published by this verifier, including +older compatible archives verified with the updated code. A raw filesystem +rollback, a previously extracted unmarked copy, an omitted marker or an older +writer does not carry this protection. Quiesce older writers and retain +independent provider records across recovery. + +One settlement effect id owns exactly one material invocation: retrying the same request replays it, while attempting a different operation or input under the same Turn receipt fails before provider dispatch. A new invocation also requires `should_run=true`; an existing journal may still be recovered with its exact typed receipt after the runnable decision has changed. +CI checks Python dispatch with Ruff (`scripts/ci/external-request-lint.toml`). +Production Python HTTP transports under `loopx/` and `packages/*/src/` are +listed in `scripts/ci/external-transport-lint.toml`. For JS/TS in the same +trees, `node scripts/ci/lint-external-transports.mjs` checks direct fetch +and common HTTP module references. Adding a raw transport outside an existing +owner fails the applicable check. Review new owners for operation identity, +remote readback and recovery before allowing them. These source checks cover +the named transports. Provider internals, dynamic loading, third-party SDKs +and shell effects require enforcement by their respective runtime or provider. + Transition proposals are deliberately narrower than arbitrary Goal mutation. The first version supports only continuous-monitor upsert and completion. It cannot create a general advancement Todo, change a Goal, widen capability diff --git a/loopx/control_plane/governed_capability.ts b/loopx/control_plane/governed_capability.ts index bda8947b2e..628aa864ba 100644 --- a/loopx/control_plane/governed_capability.ts +++ b/loopx/control_plane/governed_capability.ts @@ -105,7 +105,7 @@ const LIFECYCLE_PACKET_FIELDS = new Set([ "admission", "journal", ]); -const LIFECYCLE_PHASES = ["inspect", "observe_result"] as const; +const LIFECYCLE_PHASES = ["inspect", "observe_result", "authorize_dispatch"] as const; const JOURNAL_STATUSES = [ "ready", "starting", @@ -115,6 +115,33 @@ const JOURNAL_STATUSES = [ "committed", ] as const; type GovernedCapabilityJournalStatus = typeof JOURNAL_STATUSES[number]; +type StartDisposition = "allow_retry" | "unsettled_reconcile_required" | "settled_committed"; + +const RESTORED_RESERVATION_PROOF_FIELDS = [ + "operation_key", + "intent_digest", + "request_digest", + "invocation_id", + "challenge", +]; +const RESTORED_RESERVATION_FIELDS = new Set([ + ...RESTORED_RESERVATION_PROOF_FIELDS, + "status", + "reservation_ref", +]); +type RestoredStartReservation = { + operation_key: string; + intent_digest: string; + request_digest: string; + invocation_id: string; + challenge: string; + status: "reserved_after_terminal_no_effect"; + reservation_ref: string; +}; +type DispatchCheckpoint = { + dispatch_armed: true; + restored_start_reservation?: RestoredStartReservation; +}; function requiredObject(value: unknown, label: string): JsonObject { if (typeof value !== "object" || value === null || Array.isArray(value)) { @@ -610,6 +637,94 @@ function validateStoredSettlementCallback(input: { return payload; } +function restoredReservationReference(value: unknown): string { + const message = "restored external start requires a bounded provider reservation reference"; + requireCondition(typeof value === "string" && value.length <= 512, message); + const ref = value; + const points = [...ref]; + requireCondition( + ref.trim().length > 0 && points.length <= 256 && + points.every((point) => point === " " || !/[\p{C}\p{Z}]/u.test(point)), + message, + ); + return ref; +} + +function validateRestoredStartReservation( + reservation: JsonObject, + journal: JsonObject, +): RestoredStartReservation { + const label = "restored external start provider reservation"; + requireCondition( + reservation.status === "reserved_after_terminal_no_effect" && + reservation.invocation_id === journal.invocation_id && + reservation.request_digest === journal.request_digest, + `${label} status or journal identity is invalid`, + ); + return { + operation_key: requiredCanonicalDigest(reservation.operation_key, `${label} operation_key`), + intent_digest: requiredCanonicalDigest(reservation.intent_digest, `${label} intent_digest`), + request_digest: requiredCanonicalDigest(reservation.request_digest, `${label} request_digest`), + invocation_id: requiredString(reservation.invocation_id, `${label} invocation_id`), + challenge: requiredString(reservation.challenge, `${label} challenge`), + status: reservation.status, + reservation_ref: restoredReservationReference(reservation.reservation_ref), + }; +} + +function validateStoredDispatchState(journal: JsonObject): void { + requireCondition( + journal.dispatch_armed === undefined || typeof journal.dispatch_armed === "boolean", + "governed capability journal dispatch_armed must be boolean", + ); + if (journal.restored_start_reservation === undefined) return; + requireCondition( + journal.dispatch_armed === true, + "governed capability journal restored_start_reservation requires an armed dispatch", + ); + const label = "governed capability journal restored_start_reservation"; + const reservation = requiredObject(journal.restored_start_reservation, label); + requireExactFields(reservation, RESTORED_RESERVATION_FIELDS, label); + validateRestoredStartReservation(reservation, journal); +} + +function authorizeDispatch( + journal: JsonObject, facts: unknown, disposition: StartDisposition, +): DispatchCheckpoint { + requireCondition( + disposition === "allow_retry", + "external write dispatch may already be armed; reconcile original invocation", + ); + const dispatch = requiredObject(facts, "governed capability dispatch facts"); + if (dispatch.restored_runtime === false) { + requireExactFields(dispatch, new Set(["restored_runtime"]), "governed capability dispatch facts"); + return { dispatch_armed: true }; + } + const message = "restored external start lacks a current provider reservation after terminal no-effect"; + requireCondition( + dispatch.restored_runtime === true && dispatch.reservation != null, + message, + ); + const proof = requiredObject(dispatch.proof, "restored external start reservation proof"); + const reservation = requiredObject(dispatch.reservation, "restored external start provider reservation"); + requireCondition(RESTORED_RESERVATION_PROOF_FIELDS.every((field) => reservation[field] === proof[field]), message); + return { + dispatch_armed: true, + restored_start_reservation: validateRestoredStartReservation(reservation, journal), + }; +} + +function startDisposition( + journal: JsonObject, + status: GovernedCapabilityJournalStatus, +): StartDisposition { + if (status === "committed") return "settled_committed"; + if (status === "starting" && journal.provider_result == null && journal.dispatch_armed === false) { + return "allow_retry"; + } + return "unsettled_reconcile_required"; +} + function reduceGovernedCapabilityLifecycle(input: { packet: JsonObject; invocation_id: string; @@ -620,7 +735,9 @@ function reduceGovernedCapabilityLifecycle(input: { }): JsonObject { requireExactFields( input.packet, - LIFECYCLE_PACKET_FIELDS, + input.packet.phase === "authorize_dispatch" + ? new Set([...LIFECYCLE_PACKET_FIELDS, "dispatch"]) + : LIFECYCLE_PACKET_FIELDS, "governed capability lifecycle packet", ); const phase = requireStringLiteral( @@ -704,6 +821,7 @@ function reduceGovernedCapabilityLifecycle(input: { journal.request_digest === requestDigest, "governed capability journal request digest is invalid", ); + validateStoredDispatchState(journal); const operationProfile = requiredObject( journal.operation_profile, @@ -728,7 +846,7 @@ function reduceGovernedCapabilityLifecycle(input: { const rawResult = journal.provider_result; if (rawResult === null || rawResult === undefined) { requireCondition( - phase === "inspect" && + (phase === "inspect" || (phase === "authorize_dispatch" && !input.packet.dry_run)) && currentStatus === (input.packet.dry_run ? "ready" : "starting"), "governed capability journal provider state is invalid", ); @@ -747,10 +865,15 @@ function reduceGovernedCapabilityLifecycle(input: { todo_contract: operationProfile.todo_contract, }); } + const disposition = startDisposition(journal, currentStatus); + const start = phase === "authorize_dispatch" + ? { dispatch_checkpoint: authorizeDispatch(journal, input.packet.dispatch, disposition) } + : { start_disposition: disposition }; return { schema_version: GOVERNED_CAPABILITY_LIFECYCLE_REDUCTION_SCHEMA_VERSION, journal_status: currentStatus, provider_result: null, + ...(input.packet.dry_run ? {} : start), public_receipt: lifecyclePublicReceipt({ journal, status: currentStatus, @@ -760,6 +883,10 @@ function reduceGovernedCapabilityLifecycle(input: { }; } + requireCondition( + phase !== "authorize_dispatch", + "governed capability dispatch requires a journal without a provider result", + ); if (input.packet.admission !== null) { requireCondition( phase === "inspect", @@ -877,6 +1004,7 @@ function reduceGovernedCapabilityLifecycle(input: { schema_version: GOVERNED_CAPABILITY_LIFECYCLE_REDUCTION_SCHEMA_VERSION, journal_status: journalStatus, provider_result: validated.result, + ...(phase === "inspect" ? { start_disposition: startDisposition(journal, journalStatus) } : {}), public_receipt: lifecyclePublicReceipt({ journal: reducedJournal, status: journalStatus, diff --git a/loopx/control_plane/state_recovery_io.py b/loopx/control_plane/state_recovery_io.py index 731565ba9e..f4fdaf2197 100644 --- a/loopx/control_plane/state_recovery_io.py +++ b/loopx/control_plane/state_recovery_io.py @@ -23,7 +23,9 @@ import zlib from typing import Any, BinaryIO, Iterator, NoReturn +from ..paths import RESTORED_RUNTIME_MARKER from .effect_runtime import _node_executable, effect_runtime_result, effect_runtime_request_scope +from .runtime.document_io import fsync_state_directory from .runtime.node_probe import node_typescript_flags MAX_ARCHIVE_BYTES = 128 * 1024 * 1024 @@ -419,6 +421,27 @@ def _scan(handle: BinaryIO, archive_size: int, output: Path | None = None) -> di "entry_count": len(names)} +def _mark_restored_runtimes(data: Path) -> None: + # This interlock travels with a copied runtime. Never traverse an archived link + # or replace a member of the verified archive. + roots = [data / "runtime-root"] + sources = data / "source-runtimes" + if sources.is_symlink(): + raise StateRecoveryError("recovery_runtime_not_physical") + if sources.is_dir(): + roots.extend(sources.iterdir()) + for root in roots: + if root.is_symlink(): + raise StateRecoveryError("recovery_runtime_not_physical") + if root.is_dir(): + marker = root / RESTORED_RUNTIME_MARKER + try: + marker.touch(mode=0o600, exist_ok=False) + except FileExistsError: + pass # Any entry, including a dangling link, already holds dispatch. + fsync_state_directory(marker) + + @effect_runtime_request_scope() def verify_state_backup( *, archive: Path, manifest: Path, destination: Path, execute: bool = False, @@ -473,6 +496,7 @@ def verify_state_backup( with (data / member["archive_path"]).open("rb") as handle: digest = hashlib.file_digest(handle, "sha256").hexdigest() _require(digest == member["sha256"], "recovery_owner_mutated_source") + _mark_restored_runtimes(data) audit_path = staging / "recovery-audit.json" with audit_path.open("x", encoding="utf-8") as handle: os.chmod(audit_path, 0o600) diff --git a/loopx/extensions/capability_admission.py b/loopx/extensions/capability_admission.py index 9dc060657b..8cd24630e5 100644 --- a/loopx/extensions/capability_admission.py +++ b/loopx/extensions/capability_admission.py @@ -13,7 +13,7 @@ from ..registry import find_registry_goal from .manifest import EXTERNAL_CAPABILITY_PROFILE_SCHEMA_VERSION from .runtime import ( - execute_extension_runtime_binding, + _execute_extension_runtime_binding, extension_catalog_entries, resolve_extension_runtime_binding, ) @@ -661,7 +661,7 @@ def invoke_external_capability( } if not execute: return receipt - provider_result = execute_extension_runtime_binding( + provider_result = _execute_extension_runtime_binding( binding, request=request, environment=environment, diff --git a/loopx/extensions/governed_capability_execution.py b/loopx/extensions/governed_capability_execution.py index af48fd4c81..5d578690de 100644 --- a/loopx/extensions/governed_capability_execution.py +++ b/loopx/extensions/governed_capability_execution.py @@ -9,9 +9,11 @@ import json import os -import tempfile -from collections.abc import Callable, Mapping +import secrets +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager from copy import deepcopy +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -21,7 +23,9 @@ HostGuardState, classify_host_guard_snapshot, ) +from ..control_plane.runtime.document_io import fsync_state_directory from ..control_plane.runtime.public_safety import validate_public_safe_value +from ..control_plane.runtime.runtime_projection_route import resolve_goal_source_runtime_route from ..control_plane.turn_driver.settlement import execute_turn_driver_settlement from ..control_plane.turn_driver.transaction import ( TRANSACTION_PHASES, @@ -34,10 +38,10 @@ validate_governed_transition_receipts, ) from ..control_plane.work_items.team_plan_adapter import team_plan_state_fingerprint -from ..file_lock import exclusive_file_lock -from ..paths import select_default_runtime_root +from ..file_lock import exclusive_file_lock, write_json_atomic +from ..paths import RESTORED_RUNTIME_MARKER, select_default_runtime_root from .capability_admission import prepare_external_capability_invocation -from .runtime import execute_extension_runtime_binding +from .runtime import _execute_extension_runtime_binding GOVERNED_CAPABILITY_RUN_SCHEMA_VERSION = "loopx_governed_capability_run_v0" GOVERNED_CAPABILITY_RECEIPT_SCHEMA_VERSION = ( @@ -52,6 +56,15 @@ MaterialEffect = Callable[[Mapping[str, Any]], Mapping[str, Any]] +@dataclass(frozen=True) +class _LifecycleReduction: + provider_result: dict[str, Any] | None + journal_status: str + receipt: dict[str, Any] + start_disposition: object + dispatch_checkpoint: object + + def default_governed_capability_run_dir( runtime_root: str | Path | None = None, ) -> Path: @@ -146,20 +159,125 @@ def _read_journal(path: Path) -> dict[str, Any]: def _write_journal(path: Path, value: Mapping[str, Any]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - serialized = json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n" - descriptor, temporary_name = tempfile.mkstemp( - prefix=f".{path.name}.tmp.", - dir=path.parent, - ) - temporary = Path(temporary_name) - try: - with os.fdopen(descriptor, "w", encoding="utf-8") as output: - output.write(serialized) - os.replace(temporary, path) - except BaseException: - temporary.unlink(missing_ok=True) - raise + write_json_atomic(path, value, fsync_directory=True) + + +def _restored_runtime(registry_path: str | Path | None, goal_id: str, run_dir: str | Path) -> bool: + runs = Path(run_dir).expanduser().resolve() + # An explicit journal location may be outside the Goal's restored runtime. + roots = {runs, *runs.parents} + if registry_path is not None: + route = resolve_goal_source_runtime_route(registry_path=Path(registry_path), goal_id=goal_id) + roots.update((Path(route["source_runtime_root"]), Path(route["invoked_runtime_root"]))) + for root in roots: + try: + (root / RESTORED_RUNTIME_MARKER).lstat() + except FileNotFoundError: + continue + return True + return False + + +def _start_scope(journal: Mapping[str, Any]) -> str: + # The handoff can change both actor and Turn. Neither identifies the work to repeat. + request = journal["request"] + return _canonical_digest([ + journal["goal_id"], journal["todo_id"], request["capability_id"], request["operation"], + ]).removeprefix("sha256:") + + +def _query_restored_start_reservation( + journal: Mapping[str, Any], reserve: Callable[[Mapping[str, Any]], Mapping[str, Any] | None], +) -> dict[str, Any]: + request = journal["request"] + target = journal["admitted_target_key"] + proof = { + "operation_key": _canonical_digest([journal["goal_id"], request["capability_id"], request["operation"], target]), + "intent_digest": _canonical_digest([request["goal"], request["provider"], request["context_refs"], request["input"]]), + "request_digest": journal["request_digest"], + "invocation_id": journal["invocation_id"], + "challenge": secrets.token_hex(16), + } + # The service must atomically fence the old work and grant this challenge once. + receipt = reserve({**proof, "target_key": target, "request": deepcopy(request)}) + return {"proof": proof, "reservation": dict(receipt) if isinstance(receipt, Mapping) else None} + + +@contextmanager +def _locked_start_scope(path: Path, journal: Mapping[str, Any]) -> Iterator[Path]: + """Serialize starts of one Todo operation across Turns.""" + index = path.parent / ".start-reservations-v1" + index.mkdir(mode=0o700, exist_ok=True) + with exclusive_file_lock(index / "catalog", operation="reserve_external_start"): + initialized = index / "initialized" + if not initialized.exists(): + # Older journals have only a per-Turn name. Index them once without changing them. + for previous_path in path.parent.glob("capability-" + "[0-9a-f]" * 24 + ".json"): + previous = _read_journal(previous_path) + if _journal_path(path.parent, previous["invocation_id"]) != previous_path: + raise ValueError("external write journal identity mismatch during indexing") + group = index / _start_scope(previous) + group.mkdir(mode=0o700, exist_ok=True) + (group / previous_path.stem).touch(mode=0o600, exist_ok=True) + fsync_state_directory(group / previous_path.stem) + fsync_state_directory(initialized) + initialized.touch(mode=0o600, exist_ok=False) + + group = index / _start_scope(journal) + # A service lookup serializes only other starts of this operation. + with exclusive_file_lock(group, operation="reserve_external_start"): + group.mkdir(mode=0o700, exist_ok=True) + for reservation in group.iterdir(): + previous_path = _journal_path(path.parent, reservation.name) + if not previous_path.exists(): + raise ValueError(f"external start has no original journal: {reservation.name}") + previous = _read_journal(previous_path) + if (_start_scope(previous) != group.name or previous["invocation_id"] != reservation.name): + raise ValueError("external start reservation does not match the original request") + reduction = _reduce_governed_capability_journal( + previous, invocation_id=reservation.name, phase="inspect", dry_run=False, + ) + if reduction.start_disposition not in ("allow_retry", "settled_committed"): + raise ValueError(f"external write is unsettled; reconcile original invocation {reservation.name}") + reservation.unlink() + yield group + + +def _checkpoint_start(path: Path, journal: Mapping[str, Any], group: Path) -> None: + _write_journal(path, journal) + (group / path.stem).touch(mode=0o600, exist_ok=False) + fsync_state_directory(group / path.stem) + fsync_state_directory(group) + + +def _record_start_intent( + path: Path, journal: dict[str, Any], *, + dispatch_checkpoint: object, + reserve_restored_start: Callable[[Mapping[str, Any]], Mapping[str, Any] | None] | None, +) -> dict[str, Any] | None: + with _locked_start_scope(path, journal) as group: + # A process can exit during the service lookup, before it is allowed to deliver. + _checkpoint_start(path, journal, group) + if reserve_restored_start is not None: + reduction = _reduce_governed_capability_journal( + journal, invocation_id=path.stem, phase="authorize_dispatch", dry_run=False, + dispatch={ + "restored_runtime": True, + **_query_restored_start_reservation(journal, reserve_restored_start), + }, + ) + dispatch_checkpoint = reduction.dispatch_checkpoint + checkpoint = _mapping(dispatch_checkpoint, "governed capability dispatch checkpoint") + if checkpoint.get("dispatch_armed") is not True: + raise RuntimeError("TypeScript governed capability dispatch checkpoint shape mismatch") + reservation = None + if reserve_restored_start is not None: + reservation = _mapping(checkpoint.get("restored_start_reservation"), "provider reservation") + validate_public_safe_value(reservation, path="provider_reservation") + journal["restored_start_reservation"] = reservation + journal["dispatch_armed"] = checkpoint["dispatch_armed"] + _write_journal(path, journal) + return reservation def _settlement_identity(transaction_plan: Mapping[str, Any]) -> dict[str, Any]: @@ -198,6 +316,7 @@ def _require_admission( *, expected_identity: Mapping[str, Any], require_should_run: bool, + original_readback: bool = False, ) -> None: if require_should_run and admission.get("should_run") is not True: raise ValueError("governed capability admission requires should_run=true") @@ -209,11 +328,10 @@ def _require_admission( if guard.settlement_identity is None: raise ValueError("quota guard did not return a typed settlement identity") observed = guard.settlement_identity.as_dict() - expected = { - key: str(expected_identity.get(key) or "") - for key in ("goal_id", "agent_id", "todo_id", "turn_instance_id", "effect_id") - } - if any(observed.get(key) != value for key, value in expected.items()): + fields = ("goal_id", "todo_id") if original_readback else ( + "goal_id", "todo_id", "agent_id", "turn_instance_id", "effect_id", + ) + if any(observed.get(key) != expected_identity.get(key) for key in fields): raise ValueError( "quota guard settlement identity does not match the invocation" ) @@ -226,7 +344,8 @@ def _reduce_governed_capability_journal( phase: str, dry_run: bool, admission: Mapping[str, Any] | None = None, -) -> tuple[dict[str, Any] | None, str, dict[str, Any]]: + dispatch: Mapping[str, Any] | None = None, +) -> _LifecycleReduction: """Validate one lifecycle state and project its canonical public receipt.""" transaction_plan = _mapping(journal.get("transaction_plan"), "transaction plan") @@ -253,6 +372,7 @@ def _reduce_governed_capability_journal( "canonical_request_digest": _canonical_digest(request), "admission": dict(admission) if admission is not None else None, "journal": dict(journal), + **({"dispatch": dict(dispatch)} if dispatch is not None else {}), }, "invocation_id": invocation_id, "effect_id": identity.get("effect_id"), @@ -262,7 +382,7 @@ def _reduce_governed_capability_journal( }, ) except EffectRuntimeRejected as exc: - if phase != "inspect" or admission is not None: + if phase == "observe_result" or admission is not None: raise raise ValueError(str(exc)) from exc if ( @@ -303,7 +423,13 @@ def _reduce_governed_capability_journal( ) if receipt.get("schema_version") != GOVERNED_CAPABILITY_RECEIPT_SCHEMA_VERSION: raise RuntimeError("TypeScript governed capability receipt shape mismatch") - return result, journal_status, receipt + return _LifecycleReduction( + provider_result=result, + journal_status=journal_status, + receipt=receipt, + start_disposition=payload.get("start_disposition"), + dispatch_checkpoint=payload.get("dispatch_checkpoint"), + ) def _receipt_with_local_effects( @@ -411,8 +537,10 @@ def start_governed_external_capability( admission: Mapping[str, Any], execute: bool = False, environment: Mapping[str, str] | None = None, + read_start_result: Callable[[Mapping[str, Any]], Mapping[str, Any] | None] | None = None, + reserve_restored_start: Callable[[Mapping[str, Any]], Mapping[str, Any] | None] | None = None, ) -> dict[str, Any]: - """Preview or idempotently start one selected-Todo material operation.""" + """Start once, or recover the result by identity using a trusted read-only provider lookup.""" transaction_plan = build_loopx_turn_transaction_plan( planned=True, @@ -435,11 +563,15 @@ def start_governed_external_capability( operation_profile = _mapping(prepared["operation_profile"], "operation profile") if operation_profile.get("effect_class") != "external_write": raise ValueError("governed capability execution requires external_write") + if read_start_result is not None and reserve_restored_start is not None: + raise ValueError("choose original receipt readback or conditional restored start") _require_admission( - admission, - expected_identity=identity, - require_should_run=not execute, + admission, expected_identity=identity, require_should_run=not execute or read_start_result is not None, + original_readback=read_start_result is not None, ) + restored = _restored_runtime(registry_path, goal_id, run_dir) + if reserve_restored_start is not None and not restored: + raise ValueError("conditional restored start requires a restored runtime") request = _mapping(prepared["request"], "provider request") request["lifecycle"] = { "phase": "start", @@ -470,46 +602,52 @@ def start_governed_external_capability( "kernel_context_digest": _canonical_digest(kernel_context), "completed_phases": [], "provider_result": None, + "dispatch_armed": False, "transition_receipts": [], "writeback": None, "quota_spend": None, "settlement_result": None, } if not execute: - _provider_result, _journal_status, receipt = ( - _reduce_governed_capability_journal( - journal, - invocation_id=invocation_id, - phase="inspect", - dry_run=True, - admission=admission, - ) + if restored and read_start_result is None and reserve_restored_start is None: + raise ValueError("restored runtime requires provider reconciliation before external start") + reduction = _reduce_governed_capability_journal( + journal, + invocation_id=invocation_id, + phase="inspect", + dry_run=True, + admission=admission, ) - return _receipt_with_local_effects(receipt, journal) + return _receipt_with_local_effects(reduction.receipt, journal) path = _journal_path(run_dir, invocation_id) with exclusive_file_lock(path, operation="start_governed_external_capability"): - if path.exists(): + original_present = path.exists() + if original_present: current = _read_journal(path) - current_result, _current_status, receipt = ( - _reduce_governed_capability_journal( - current, - invocation_id=invocation_id, - phase="inspect", - dry_run=False, - ) + current_reduction = _reduce_governed_capability_journal( + current, + invocation_id=invocation_id, + phase="inspect", + dry_run=False, admission=admission if read_start_result is not None else None, ) if ( current.get("request_digest") != request_digest or current.get("effect_id") != identity["effect_id"] ): raise ValueError("governed capability invocation replay does not match") - if current_result is not None: + if ( + read_start_result is not None + and current.get("admitted_target_key") is not None + and current["admitted_target_key"] != admission["selected_todo"].get("target_key") + ): + raise ValueError("current Todo target does not match original external write") + if current_reduction.provider_result is not None: if _has_unsettled_start_transition(current): _require_admission( admission, expected_identity=identity, - require_should_run=True, + require_should_run=True, original_readback=read_start_result is not None, ) _reduce_governed_capability_journal( current, @@ -523,21 +661,52 @@ def start_governed_external_capability( path=path, phase=GovernedTransitionSettlementPhase.PRE_SETTLEMENT, ) - return _receipt_with_local_effects(receipt, current) + return _receipt_with_local_effects(current_reduction.receipt, current) + if read_start_result is None and current_reduction.start_disposition != "allow_retry": + raise ValueError( + "external write outcome unknown; preserve the original invocation " + "and supply provider readback before any new start" + ) journal = current + elif read_start_result is not None: + if not restored: + raise ValueError("no original external write invocation for provider readback") + if _may_propose_team_plan(operation_profile): + raise ValueError("original team plan state basis required for restored readback") + + _require_admission( + admission, + expected_identity=identity, + require_should_run=True, original_readback=read_start_result is not None, + ) + native_dispatch = not restored and read_start_result is None + start_reduction = _reduce_governed_capability_journal( + journal, + invocation_id=invocation_id, + phase="authorize_dispatch" if native_dispatch else "inspect", + dry_run=False, + admission=admission, + dispatch={"restored_runtime": False} if native_dispatch else None, + ) + if read_start_result is not None: + target_key = admission["selected_todo"]["target_key"] + provider_result = read_start_result({ + "invocation_id": invocation_id, + "idempotency_key": identity["effect_id"], + "request_digest": request_digest, + "provider": request["provider"], + "operation": operation, + "goal": request["goal"], + "target_key": target_key, + }) + if provider_result is None: + raise ValueError("external write outcome unknown after provider readback") + if restored: + if (provider_result.get("request_digest") != request_digest + or provider_result.get("target_key") != target_key): + raise ValueError("provider readback does not attest the original request digest and target") + provider_result = _mapping(provider_result.get("result"), "provider readback result") else: - _require_admission( - admission, - expected_identity=identity, - require_should_run=True, - ) - _reduce_governed_capability_journal( - journal, - invocation_id=invocation_id, - phase="inspect", - dry_run=False, - admission=admission, - ) # A team plan the provider proposes is settled against the state # this agent saw before the provider ran, not against whatever the # settlement later finds. The basis is bound once here, stored with @@ -552,33 +721,46 @@ def start_governed_external_capability( goal_id=goal_id, basis_agent_id=agent_id, ) - _write_journal(path, journal) - provider_result = execute_extension_runtime_binding( - binding, - request=request, - environment=environment, - ) + if restored and reserve_restored_start is None: + raise ValueError("restored runtime requires provider reconciliation before external start") + journal["admitted_target_key"] = admission["selected_todo"]["target_key"] + reservation = _record_start_intent( + path, journal, + dispatch_checkpoint=start_reduction.dispatch_checkpoint, + reserve_restored_start=reserve_restored_start, + ) + dispatch_request = request + if reservation is not None: + dispatch_request = {**request, "lifecycle": { + **request["lifecycle"], "restored_start_reservation": reservation, + }} + provider_result = _execute_extension_runtime_binding(binding, request=dispatch_request, environment=environment) journal["provider_result"] = _mapping( provider_result, "external capability result", ) - validated, journal_status, receipt = _reduce_governed_capability_journal( + reduction = _reduce_governed_capability_journal( journal, invocation_id=invocation_id, phase="observe_result", dry_run=False, ) - if validated is None: + if reduction.provider_result is None: raise RuntimeError("TypeScript governed capability result shape mismatch") - journal["provider_result"] = validated - journal["status"] = journal_status - _write_journal(path, journal) + journal["provider_result"] = reduction.provider_result + journal["status"] = reduction.journal_status + if read_start_result is not None and not original_present: + journal["admitted_target_key"] = admission["selected_todo"]["target_key"] + with _locked_start_scope(path, journal) as group: + _checkpoint_start(path, journal, group) + else: + _write_journal(path, journal) _settle_journal_transition_proposals( journal=journal, path=path, phase=GovernedTransitionSettlementPhase.PRE_SETTLEMENT, ) - return _receipt_with_local_effects(receipt, journal) + return _receipt_with_local_effects(reduction.receipt, journal) def _settlement_callback( @@ -608,18 +790,20 @@ def reconcile_governed_external_capability( writeback: MaterialEffect, spend: MaterialEffect, environment: Mapping[str, str] | None = None, + read_running_result: Callable[[Mapping[str, Any]], Mapping[str, Any] | None] | None = None, ) -> dict[str, Any]: """Poll and idempotently settle one asynchronous material invocation.""" path = _journal_path(run_dir, invocation_id) with exclusive_file_lock(path, operation="reconcile_governed_external_capability"): journal = _read_journal(path) - provider_result, _journal_status, receipt = _reduce_governed_capability_journal( + reduction = _reduce_governed_capability_journal( journal, invocation_id=invocation_id, phase="inspect", dry_run=False, ) + provider_result, receipt = reduction.provider_result, reduction.receipt if journal.get("status") == "committed": return _receipt_with_local_effects(receipt, journal) identity = _settlement_identity( @@ -634,29 +818,34 @@ def reconcile_governed_external_capability( "idempotency_key": identity["effect_id"], "follow_up": deepcopy(provider_result.get("follow_up")), } - observed = execute_extension_runtime_binding( - _mapping(journal.get("provider_binding"), "provider binding"), - request=request, - environment=environment, - ) + if read_running_result is not None: + observed = read_running_result(request) + if observed is None: + raise ValueError("provider has no verified result for the running external write") + else: + if _restored_runtime(_journal_registry_path(journal), str(journal["goal_id"]), run_dir): + raise ValueError("restored runtime requires provider readback to reconcile a running external write") + observed = _execute_extension_runtime_binding( + _mapping(journal.get("provider_binding"), "provider binding"), + request=request, environment=environment, + ) journal["provider_result"] = _mapping( observed, "external capability result", ) - provider_result, journal_status, receipt = ( - _reduce_governed_capability_journal( - journal, - invocation_id=invocation_id, - phase="observe_result", - dry_run=False, - ) + reduction = _reduce_governed_capability_journal( + journal, + invocation_id=invocation_id, + phase="observe_result", + dry_run=False, ) + provider_result, receipt = reduction.provider_result, reduction.receipt if provider_result is None: raise RuntimeError( "TypeScript governed capability result shape mismatch" ) journal["provider_result"] = provider_result - journal["status"] = journal_status + journal["status"] = reduction.journal_status _write_journal(path, journal) _settle_journal_transition_proposals( journal=journal, diff --git a/loopx/extensions/runtime.py b/loopx/extensions/runtime.py index e5636d0e45..f398c7334c 100644 --- a/loopx/extensions/runtime.py +++ b/loopx/extensions/runtime.py @@ -281,7 +281,21 @@ def execute_extension_runtime_binding( request: Mapping[str, object], environment: Mapping[str, str] | None = None, ) -> dict[str, object]: - """Execute a resolved binding after its capability authorizes the request.""" + """Dispatch a protocol-specific binding. Profiled operations need their admission owner.""" + provider = request.get("provider") + if ("integration_profile_digest" in binding or "operation" in binding + or (isinstance(provider, Mapping) and "profile_digest" in provider)): + raise ValueError("profiled external operations require capability admission") + return _execute_extension_runtime_binding(binding, request=request, environment=environment) + + +def _execute_extension_runtime_binding( + binding: Mapping[str, object], + *, + request: Mapping[str, object], + environment: Mapping[str, str] | None = None, +) -> dict[str, object]: + """Run the transport after the protocol owner admits this operation.""" argv, timeout_seconds = _runtime_binding_invocation(binding) request_bytes = _serialize_extension_request(request, operation="runtime") raw_prefix = binding.get("environment_path_prefix") diff --git a/loopx/paths.py b/loopx/paths.py index 970fc3662b..e5ddeb4f05 100644 --- a/loopx/paths.py +++ b/loopx/paths.py @@ -18,6 +18,7 @@ DEFAULT_PROJECT_REGISTRY = Path(".loopx") / "registry.json" DEFAULT_PROJECT_GOALS = Path(".loopx") / "goals" LEGACY_PROJECT_GOALS = Path(".codex") / "goals" +RESTORED_RUNTIME_MARKER = ".loopx-restored-inert" GLOBAL_REGISTRY_FILENAME = "registry.global.json" SHELL_DEFAULT_GLOBAL_REGISTRY = '"$HOME/.loopx/registry.global.json"' SHELL_LEGACY_GLOBAL_REGISTRY = '"$HOME/.codex/loopx/registry.global.json"' diff --git a/scripts/ci/external-request-lint.toml b/scripts/ci/external-request-lint.toml new file mode 100644 index 0000000000..2b012d0a3e --- /dev/null +++ b/scripts/ci/external-request-lint.toml @@ -0,0 +1,15 @@ +# Apply from the repository root. Only the two profiled operation owners can +# prepare and dispatch a profiled provider request. The public transport rejects +# profiled bindings; existing protocol-specific adapters use its checked entry. +namespace-packages = ["loopx"] + +[lint] +select = ["TID251"] + +[lint.flake8-tidy-imports.banned-api] +"loopx.extensions.runtime._execute_extension_runtime_binding".msg = "Use the admitted read-only invocation or the journaled external-write lifecycle." +"loopx.extensions.capability_admission.prepare_external_capability_invocation".msg = "A prepared request is not dispatch authority. Use invoke_external_capability or the governed lifecycle." + +[lint.per-file-ignores] +"loopx/extensions/capability_admission.py" = ["TID251"] +"loopx/extensions/governed_capability_execution.py" = ["TID251"] diff --git a/scripts/ci/external-transport-lint.toml b/scripts/ci/external-transport-lint.toml new file mode 100644 index 0000000000..8d4a609306 --- /dev/null +++ b/scripts/ci/external-transport-lint.toml @@ -0,0 +1,55 @@ +# Existing Python transport owners. New service clients must use a reviewed +# adapter or add their owner explicitly in the same change as its recovery policy. +namespace-packages = ["loopx"] +[lint] +select = ["TID251"] + +[lint.flake8-tidy-imports.banned-api] +"urllib.request.urlopen".msg = "Route external requests through a reviewed transport owner." +"urllib.request.urlretrieve".msg = "Route external requests through a reviewed transport owner." +"urllib.request.build_opener".msg = "Route external requests through a reviewed transport owner." +"urllib.request.OpenerDirector".msg = "Route external requests through a reviewed transport owner." +"http.client.HTTPConnection".msg = "Route external requests through a reviewed transport owner." +"http.client.HTTPSConnection".msg = "Route external requests through a reviewed transport owner." +"httpx".msg = "Route external requests through a reviewed transport owner." +"requests".msg = "Route external requests through a reviewed transport owner." +"aiohttp".msg = "Route external requests through a reviewed transport owner." +"urllib3".msg = "Route external requests through a reviewed transport owner." +"loopx.extensions.runtime.execute_extension_runtime_binding".msg = "Route external requests through a reviewed transport owner." + +[lint.per-file-ignores] +"loopx/capabilities/benchmark_toolkit/provider_gateway.py" = ["TID251"] +"loopx/capabilities/content_ops/generation.py" = ["TID251"] +"loopx/capabilities/content_ops/images.py" = ["TID251"] +"loopx/capabilities/content_ops/media.py" = ["TID251"] +"loopx/capabilities/content_ops/surface.py" = ["TID251"] +"loopx/capabilities/decision_context/extension_provider.py" = ["TID251"] +"loopx/capabilities/issue_fix/github_public.py" = ["TID251"] +"loopx/capabilities/native_chat/antigravity_discovery.py" = ["TID251"] +"loopx/capabilities/periodic_report/cli.py" = ["TID251"] +"loopx/chat/providers.py" = ["TID251"] +"loopx/cli_commands/update_artifact.py" = ["TID251"] +"loopx/control_plane/collaboration/peers.py" = ["TID251"] +"loopx/control_plane/goals/botmux_transport.py" = ["TID251"] +"loopx/control_plane/status/goal_source.py" = ["TID251"] +"loopx/control_plane/status/ssh_tunnel.py" = ["TID251"] +"loopx/control_plane/testing/doubao_model_behavior_actor.py" = ["TID251"] +"loopx/dashboard_launcher.py" = ["TID251"] +"loopx/extensions/lark/goal_channel_operation.py" = ["TID251"] +"loopx/extensions/public_github_research.py" = ["TID251"] +"loopx/extensions/public_source_reader.py" = ["TID251"] +"loopx/hosts/managed_service_runtime.py" = ["TID251"] +"loopx/presentation/static_site.py" = ["TID251"] +"loopx/self_update.py" = ["TID251"] +"packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native_host.py" = ["TID251"] +"packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/openai_keys.py" = ["TID251"] +"packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/openai_relay.py" = ["TID251"] +"packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/operator_catalog.py" = ["TID251"] +"packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/operator_runtime.py" = ["TID251"] +"packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/relay_lifecycle.py" = ["TID251"] +"packages/loopx-community-discussion/src/loopx_community_discussion/sources/github.py" = ["TID251"] +"packages/loopx-community-discussion/src/loopx_community_discussion/sources/hn.py" = ["TID251"] +"packages/loopx-jev/src/loopx_jev/http_worker.py" = ["TID251"] +"packages/loopx-media/src/loopx_media/generation.py" = ["TID251"] +"packages/loopx-media/src/loopx_media/images.py" = ["TID251"] +"packages/loopx-repo-health/src/loopx_repo_health/github.py" = ["TID251"] diff --git a/scripts/ci/lint-external-transports.mjs b/scripts/ci/lint-external-transports.mjs new file mode 100644 index 0000000000..999b427970 --- /dev/null +++ b/scripts/ci/lint-external-transports.mjs @@ -0,0 +1,87 @@ +/** Keep production JS/TS network entry points inside declared transport owners. */ +import {execFileSync} from "node:child_process"; +import {existsSync, readFileSync} from "node:fs"; +import {pathToFileURL} from "node:url"; +import ts from "typescript"; + +const owners = new Map([ + ["packages/dsh-loopx-plugin/src/client/dashboard.tsx", "fetch"], + ["loopx/control_plane/coordination/remote_authority_http.ts", "https"], + ["loopx/control_plane/runtime/usage_statistics.ts", "fetch"], + ["loopx/control_plane/runtime/workbench.ts", "http"], + ["loopx/zcode_goal_mode/cli.ts", "http"], +]); +const httpModules = new Set(["http", "https", "http2", "axios", "undici", "node-fetch", "got"]); +const globalObjects = new Set(["globalThis", "global", "window", "self"]); + +function httpModule(node) { + if (!node || !ts.isStringLiteralLike(node)) return undefined; + const name = node.text.replace(/^node:/, "").split("/")[0]; + return httpModules.has(name) ? name : undefined; +} + +function transport(node, hasLocalBinding) { + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + if (node.isTypeOnly || node.importClause?.isTypeOnly) return undefined; + const names = ts.isExportDeclaration(node) ? node.exportClause : node.importClause?.namedBindings; + if (names?.elements?.length && names.elements.every(item => item.isTypeOnly) && !node.importClause?.name) return undefined; + return httpModule(node.moduleSpecifier); + } + if (ts.isExternalModuleReference(node)) return httpModule(node.expression); + if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || + (ts.isIdentifier(node.expression) && node.expression.text === "require"))) { + return httpModule(node.arguments[0]); + } + if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + ts.isIdentifier(node.expression) && globalObjects.has(node.expression.text) && !hasLocalBinding(node.expression)) { + const member = ts.isPropertyAccessExpression(node) ? node.name : node.argumentExpression; + if ((ts.isIdentifier(member) || ts.isStringLiteralLike(member)) && member.text === "fetch") return "fetch"; + } + if (ts.isIdentifier(node) && node.text === "fetch") { + const parent = node.parent; + // Object keys and client.fetch are not references to the global transport. + if (parent.name === node && !ts.isShorthandPropertyAssignment(parent)) return undefined; + if (!hasLocalBinding(node)) return "fetch"; + } + return undefined; +} + +export function lintExternalTransports(file, source) { + const tree = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true); + // Resolve a potential global against declarations in this file, including + // imports and function parameters. Local clients may name a dependency fetch. + let checker; + function hasLocalBinding(node) { + if (!checker) { + const options = {allowJs: true, noLib: true, noResolve: true, target: ts.ScriptTarget.Latest}; + const host = ts.createCompilerHost(options); + host.getSourceFile = name => name === file ? tree : undefined; + checker = ts.createProgram([file], options, host).getTypeChecker(); + } + const symbol = ts.isShorthandPropertyAssignment(node.parent) + ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node); + return Boolean(symbol?.declarations?.length); + } + const violations = []; + function visit(node) { + const api = transport(node, hasLocalBinding); + if (api && owners.get(file) !== api) { + const {line} = tree.getLineAndCharacterOfPosition(node.getStart(tree)); + violations.push(`${file}:${line + 1}: external ${api} requires a declared transport owner`); + } + ts.forEachChild(node, visit); + } + visit(tree); + return violations; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const files = execFileSync("git", ["ls-files", "-co", "--exclude-standard", "-z", "--", "loopx", "packages"], {encoding: "utf8"}).split("\0"); + for (const file of new Set(files)) { + if (!/^(?:loopx\/|packages\/[^/]+\/src\/)/.test(file) || !/\.[cm]?[jt]sx?$/.test(file) || !existsSync(file)) continue; + for (const failure of lintExternalTransports(file, readFileSync(file, "utf8"))) { + console.error(failure); + process.exitCode = 1; + } + } +} diff --git a/scripts/ci/lint-external-transports.test.mjs b/scripts/ci/lint-external-transports.test.mjs new file mode 100644 index 0000000000..9a9c0ce3ab --- /dev/null +++ b/scripts/ci/lint-external-transports.test.mjs @@ -0,0 +1,17 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import {lintExternalTransports} from "./lint-external-transports.mjs"; + +test("direct transport access is restricted to its declared owner and API", () => { + const consumer = "loopx/control_plane/example.ts"; + for (const source of [ + "await fetch(url)", "const send = globalThis.fetch", 'await window["fetch"](url)', + 'import {request as send} from "node:https"', 'await import("undici")', 'require("http")', + ]) assert.ok(lintExternalTransports(consumer, source).length > 0, source); + assert.deepEqual(lintExternalTransports(consumer, "client.fetch(); const callbacks = {fetch: handler}"), []); + assert.deepEqual(lintExternalTransports(consumer, "function lookup(fetch) { return fetch(url); }"), []); + assert.deepEqual(lintExternalTransports(consumer, 'import {type RequestOptions} from "node:https"'), []); + const owner = "loopx/control_plane/runtime/usage_statistics.ts"; + assert.deepEqual(lintExternalTransports(owner, "await fetch(url)"), []); + assert.equal(lintExternalTransports(owner, 'require("node:http")').length, 1); +}); diff --git a/tests/architecture/test_external_request_lint.py b/tests/architecture/test_external_request_lint.py new file mode 100644 index 0000000000..04fb214f3b --- /dev/null +++ b/tests/architecture/test_external_request_lint.py @@ -0,0 +1,31 @@ +"""New consumers use checked entry points even if they rename a raw import.""" + +import json +from pathlib import Path +import subprocess +import sys + +import pytest + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.mark.parametrize(("policy", "source", "rejected"), [ + ("external-request", "from ...extensions.runtime import _execute_extension_runtime_binding as send # noqa: TID251", True), + ("external-request", "from loopx.extensions import runtime as r\nr._execute_extension_runtime_binding(b, request=q)", True), + ("external-request", "from loopx.extensions.capability_admission import prepare_external_capability_invocation", True), + ("external-request", "from loopx.extensions.governed_capability_execution import start_governed_external_capability", False), + ("external-transport", "from urllib.request import urlopen as send", True), + ("external-transport", "import httpx as client", True), + ("external-transport", "from loopx.extensions.runtime import execute_extension_runtime_binding as send", True), + ("external-transport", "from loopx.extensions.capability_admission import invoke_external_capability", False), +]) +def test_external_request_source_boundary(policy, source, rejected): + result = subprocess.run( + [sys.executable, "-m", "ruff", "check", "--no-cache", "--ignore-noqa", + "--config", f"scripts/ci/{policy}-lint.toml", "--output-format", "json", + "--stdin-filename", "loopx/capabilities/new_service/adapter.py", "-"], + cwd=ROOT, input=source, capture_output=True, text=True, check=False, + ) + assert result.returncode == int(rejected), result.stderr or result.stdout + assert [item["code"] for item in json.loads(result.stdout)] == (["TID251"] if rejected else []) diff --git a/tests/control_plane_ts/governed_capability.test.ts b/tests/control_plane_ts/governed_capability.test.ts index a469e8922f..8ff72c9e51 100644 --- a/tests/control_plane_ts/governed_capability.test.ts +++ b/tests/control_plane_ts/governed_capability.test.ts @@ -132,7 +132,8 @@ function lifecycleJournal( function reduceLifecycle( journal: ReturnType, - phase: "inspect" | "observe_result" = "inspect", + phase: "inspect" | "observe_result" | "authorize_dispatch" = "inspect", + dispatch?: object, ) { return validateGovernedCapabilityResult({ ...authority, @@ -144,10 +145,101 @@ function reduceLifecycle( canonical_request_digest: providerRequestDigest, admission: null, journal, + ...(dispatch === undefined ? {} : { dispatch }), }, }); } +test("only an explicitly unarmed start can retry without provider readback", () => { + const starting = lifecycleJournal("starting", null); + const unarmed = { ...starting, dispatch_armed: false }; + const armed = { ...starting, dispatch_armed: true }; + const nativeDispatch = { restored_runtime: false }; + assert.equal(reduceLifecycle(unarmed).start_disposition, "allow_retry"); + assert.deepEqual( + reduceLifecycle(unarmed, "authorize_dispatch", nativeDispatch).dispatch_checkpoint, + { dispatch_armed: true }, + ); + for (const journal of [armed, starting]) { + assert.equal(reduceLifecycle(journal).start_disposition, "unsettled_reconcile_required"); + assert.throws( + () => reduceLifecycle(journal, "authorize_dispatch", nativeDispatch), + /reconcile original invocation/, + ); + } + const malformed = { ...starting, dispatch_armed: "false" }; + assert.throws(() => reduceLifecycle(malformed), /dispatch_armed must be boolean/); +}); + +const restoredStartProof = { + operation_key: `sha256:${"1".repeat(64)}`, + intent_digest: `sha256:${"2".repeat(64)}`, + request_digest: providerRequestDigest, + invocation_id: authority.invocation_id, + challenge: "ab".repeat(16), +}; +const restoredStartReservation = { + ...restoredStartProof, + status: "reserved_after_terminal_no_effect", + reservation_ref: "service-grant-1", +}; + +test("a fresh service reservation authorizes and normalizes a restored dispatch", () => { + const journal = { ...lifecycleJournal("starting", null), dispatch_armed: false }; + const dispatch = { + restored_runtime: true, + proof: restoredStartProof, + reservation: { ...restoredStartReservation, service_metadata: "not part of the grant" }, + }; + const reduction = reduceLifecycle(journal, "authorize_dispatch", dispatch); + assert.deepEqual(reduction.dispatch_checkpoint, { + dispatch_armed: true, + restored_start_reservation: restoredStartReservation, + }); + const checkpoint = { ...journal, dispatch_armed: true, restored_start_reservation: restoredStartReservation }; + assert.equal(reduceLifecycle(checkpoint).start_disposition, "unsettled_reconcile_required"); + assert.throws( + () => reduceLifecycle(checkpoint, "authorize_dispatch", dispatch), + /reconcile original invocation/, + ); +}); + +test("restored dispatch rejects stale or malformed service reservations", () => { + const journal = { ...lifecycleJournal("starting", null), dispatch_armed: false }; + for (const [scenario, reservation, proof, error] of [ + ["no grant", null, restoredStartProof, /lacks a current provider reservation/], + ["wrong status", { ...restoredStartReservation, status: "reserved" }, restoredStartProof, /status or journal identity/], + ["stale challenge", { ...restoredStartReservation, challenge: "cd".repeat(16) }, restoredStartProof, /lacks a current provider reservation/], + ["other operation", { ...restoredStartReservation, operation_key: providerRequestDigest }, restoredStartProof, /lacks a current provider reservation/], + ["other intent", { ...restoredStartReservation, intent_digest: providerRequestDigest }, restoredStartProof, /lacks a current provider reservation/], + ["other request", { ...restoredStartReservation, request_digest: effectReceiptDigest }, { ...restoredStartProof, request_digest: effectReceiptDigest }, /journal identity/], + ["other invocation", { ...restoredStartReservation, invocation_id: "different" }, { ...restoredStartProof, invocation_id: "different" }, /journal identity/], + ["overlong reference", { ...restoredStartReservation, reservation_ref: "x".repeat(257) }, restoredStartProof, /reservation reference/], + ["nonprintable reference", { ...restoredStartReservation, reservation_ref: "grant\t1" }, restoredStartProof, /reservation reference/], + ["blank reference", { ...restoredStartReservation, reservation_ref: " " }, restoredStartProof, /reservation reference/], + ] as const) { + assert.throws( + () => reduceLifecycle(journal, "authorize_dispatch", { restored_runtime: true, proof, reservation }), + error, + scenario, + ); + } +}); + +test("journal inspection rejects incomplete or misbound stored dispatch reservations", () => { + const starting = lifecycleJournal("starting", null); + for (const [reservation, error] of [ + [{ ...restoredStartProof, status: restoredStartReservation.status }, /fields are invalid/], + [{ ...restoredStartReservation, request_digest: effectReceiptDigest }, /journal identity/], + [{ ...restoredStartReservation, invocation_id: "different" }, /journal identity/], + ] as const) { + const journal = { ...starting, dispatch_armed: true, restored_start_reservation: reservation }; + assert.throws(() => reduceLifecycle(journal), error); + } + const unarmed = { ...starting, dispatch_armed: false, restored_start_reservation: restoredStartReservation }; + assert.throws(() => reduceLifecycle(unarmed), /requires an armed dispatch/); +}); + test("material admission binds the exact Todo action to the operation", () => { const admission = { selected_todo: { @@ -478,6 +570,7 @@ test("committed lifecycle replay validates the whole journal in one reduction", const reduction = reduceLifecycle(journal); assert.equal(reduction.journal_status, "committed"); + assert.equal(reduction.start_disposition, "settled_committed"); assert.equal(reduction.public_receipt.status, "committed"); assert.equal(reduction.public_receipt.effects.loopx_state_written, true); assert.equal(reduction.public_receipt.effects.quota_spent, true); diff --git a/tests/extensions/test_governed_capability_execution.py b/tests/extensions/test_governed_capability_execution.py index 2c5211377a..6ce6cefb61 100644 --- a/tests/extensions/test_governed_capability_execution.py +++ b/tests/extensions/test_governed_capability_execution.py @@ -1,10 +1,14 @@ from __future__ import annotations import json +import shutil +import subprocess import stat import sys from collections.abc import Mapping +from concurrent.futures import ThreadPoolExecutor from pathlib import Path +from threading import Barrier import pytest @@ -52,6 +56,7 @@ def test_default_governed_run_dir_follows_single_runtime_route( def _provider(path: Path, *, call_log: Path) -> Path: path.write_text( f"""#!{sys.executable} +import hashlib import json import sys from pathlib import Path @@ -61,6 +66,21 @@ def _provider(path: Path, *, call_log: Path) -> Path: request = json.load(sys.stdin) phase = request["lifecycle"]["phase"] +run_ref = request["invocation_id"] +service = Path({str(call_log.parent)!r}) +if phase == "start" and (service / "reject-before-delivery").exists(): + (service / "reject-before-delivery").unlink() + (service / "closed-without-delivery.json").write_text(json.dumps(request["input"])) + print(json.dumps({{"ok": False}})) + raise SystemExit(0) +permit = request["lifecycle"].pop("restored_start_reservation", None) +canonical = json.dumps(request, ensure_ascii=False, separators=(",", ":"), sort_keys=True) +wire_digest = "sha256:" + hashlib.sha256(canonical.encode()).hexdigest() +if permit is not None: + pending = service / "provider-reservation.json" + if json.loads(pending.read_text()) != permit or permit["request_digest"] != wire_digest: + raise ValueError("service refused stale reservation") + pending.rename(service / "consumed-reservation.json") with Path({str(call_log)!r}).open("a", encoding="utf-8") as output: output.write(phase + "\\n") result = {{ @@ -79,17 +99,17 @@ def _provider(path: Path, *, call_log: Path) -> Path: "schema_version": "loopx_continuous_monitor_proposal_v0", "proposal_id": "fixture_monitor_upsert_1", "kind": "continuous_monitor_upsert", - "monitor_key": "fixture:material-run", + "monitor_key": "fixture:" + run_ref, "text": "Poll the synthetic material run.", "action_kind": "poll_material_delivery", - "target_key": "fixture-run:synthetic-run-1", + "target_key": "fixture-run:" + run_ref, "cadence": "5m", "next_due_at": "2099-01-01T00:05:00+00:00", "expires_at": "2099-01-02T00:00:00+00:00", "required_capabilities": ["network"], }}], "effect_receipt": None, - "follow_up": {{"kind": "poll", "ref": "synthetic-run-1"}}, + "follow_up": {{"kind": "poll", "ref": run_ref}}, }} if phase == "reconcile": result["domain_state_mutations"] = [{{"kind": "synthetic-update"}}] @@ -99,16 +119,20 @@ def _provider(path: Path, *, call_log: Path) -> Path: "invocation_id": request["invocation_id"], "idempotency_key": request["lifecycle"]["idempotency_key"], "status": "committed", - "external_ref": "synthetic-run-1", + "external_ref": run_ref, "evidence_digest": "sha256:synthetic-evidence", }} result["transition_proposals"] = [{{ "schema_version": "loopx_continuous_monitor_proposal_v0", "proposal_id": "fixture_monitor_complete_1", "kind": "continuous_monitor_complete", - "monitor_key": "fixture:material-run", + "monitor_key": "fixture:" + run_ref, "evidence": "Synthetic provider reached its terminal state.", }}] +if phase == "start": + (service / (run_ref + ".digest")).write_text(wire_digest) +# Provider-owned lookup state persists separately from the LoopX journal. +Path({str(call_log.parent)!r}, request["invocation_id"] + ".remote.json").write_text(json.dumps(result)) json.dump(result, sys.stdout) """, encoding="utf-8", @@ -205,7 +229,7 @@ def _installed_material_extension( "repo": str(tmp_path), "state_file": "ACTIVE_GOAL_STATE.md", "coordination": { - "registered_agents": ["fixture-agent"], + "registered_agents": ["fixture-agent", "receiving-agent"], }, } ], @@ -344,7 +368,7 @@ def test_material_start_is_previewable_and_provider_idempotent( role="agent", )["todos"] assert len(monitors) == 1 - assert monitors[0]["capability_binding_ref"] == "fixture:material-run" + assert monitors[0]["capability_binding_ref"] == "fixture:" + started["invocation_id"] assert monitors[0]["status"] == "open" journal = Path(arguments["run_dir"]) / f"{started['invocation_id']}.json" assert stat.S_IMODE(journal.stat().st_mode) == 0o600 @@ -354,6 +378,370 @@ def test_material_start_is_previewable_and_provider_idempotent( ) +def test_lost_external_start_result_cannot_dispatch_again( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + arguments = _start_arguments(tmp_path) + write_journal = governed_execution._write_journal + + def lose_result(path: Path, journal: Mapping[str, object]) -> None: + if journal.get("provider_result") is not None: + raise OSError("result checkpoint unavailable") + write_journal(path, journal) + + monkeypatch.setattr(governed_execution, "_write_journal", lose_result) + with pytest.raises(OSError, match="result checkpoint unavailable"): + start_governed_external_capability(**arguments, execute=True) + monkeypatch.setattr(governed_execution, "_write_journal", write_journal) + + with pytest.raises(ValueError, match="external write outcome unknown"): + start_governed_external_capability(**arguments, execute=True) + assert (tmp_path / "provider-calls.txt").read_text().splitlines() == ["start"] + journal, = Path(arguments["run_dir"]).glob("*.json") + saved = json.loads(journal.read_text()) + assert saved["status"] == "starting" + assert saved["writeback"] is None and saved["quota_spend"] is None + next_turn = _identity(turn_instance_id="later-turn") + with pytest.raises(ValueError, match=saved["invocation_id"]): + start_governed_external_capability( + **{**arguments, "turn_instance_id": next_turn.turn_instance_id, "admission": _admission(next_turn)}, + execute=True, + ) + + external_record = tmp_path / (saved["invocation_id"] + ".remote.json") + remote = json.loads(external_record.read_text()) + with pytest.raises(ValueError, match="unknown after provider readback"): + start_governed_external_capability(**arguments, execute=True, read_start_result=lambda _: None) + with pytest.raises(EffectRuntimeRejected, match="invocation_id"): + start_governed_external_capability( + **arguments, execute=True, + read_start_result=lambda _: {**remote, "invocation_id": "another-operation"}, + ) + assert json.loads(journal.read_text()) == saved + + def read_original(identity): + assert identity["idempotency_key"] == saved["effect_id"] + assert identity["request_digest"] == saved["request_digest"] + assert identity["provider"] == saved["request"]["provider"] + return json.loads((tmp_path / (identity["invocation_id"] + ".remote.json")).read_text()) + + with pytest.raises(ValueError, match="should_run=true"): + start_governed_external_capability( + **{**arguments, "admission": {**arguments["admission"], "should_run": False}}, + execute=True, read_start_result=read_original, + ) + receiver = SettlementIdentity(goal_id=arguments["goal_id"], agent_id="receiving-agent", + todo_id=arguments["todo_id"], turn_instance_id="successor") + current = _admission(receiver) + with pytest.raises(ValueError, match="current Todo target"): + start_governed_external_capability(**{**arguments, "admission": { + **current, "selected_todo": {**current["selected_todo"], "target_key": "fixture-material:other"}, + }}, execute=True, read_start_result=read_original) + recovered = start_governed_external_capability( + **{**arguments, "admission": current}, execute=True, read_start_result=read_original, + ) + assert recovered["status"] == "running" + assert (tmp_path / "provider-calls.txt").read_text().splitlines() == ["start"] + + +@pytest.mark.parametrize("legacy_journal", [False, True]) +def test_handoff_cannot_start_an_unsettled_external_write_on_another_turn( + tmp_path: Path, legacy_journal: bool, +) -> None: + args = _start_arguments(tmp_path) + original = start_governed_external_capability(**args, execute=True) + if legacy_journal: + # Older versions persisted the journal without a cross-Turn reservation. + runs = Path(args["run_dir"]) + shutil.rmtree(runs / ".start-reservations-v1") + (runs / (original["invocation_id"] + ".json.lock.holder.json")).write_text("{}") + next_owner = SettlementIdentity( + goal_id=args["goal_id"], agent_id="receiving-agent", todo_id=args["todo_id"], + turn_instance_id="receiving-agent-turn", + ) + with pytest.raises(ValueError, match=original["invocation_id"]): + start_governed_external_capability( + **{**args, "agent_id": next_owner.agent_id, "turn_instance_id": next_owner.turn_instance_id, + "admission": _admission(next_owner)}, execute=True, + ) + assert (tmp_path / "provider-calls.txt").read_text().splitlines() == ["start"] + + +def test_competing_handoffs_dispatch_at_most_one_provider_start(tmp_path: Path) -> None: + args = _start_arguments(tmp_path) + barrier = Barrier(2) + + def attempt(turn: str) -> str: + identity = _identity(turn_instance_id=turn) + barrier.wait(timeout=10) + try: + response = start_governed_external_capability( + **{**args, "turn_instance_id": turn, "admission": _admission(identity)}, execute=True, + ) + except ValueError as exc: + assert "reconcile original invocation" in str(exc) + return "held" + return response["status"] + + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(attempt, ["concurrent-one", "concurrent-two"])) + assert sorted(results) == ["held", "running"] + assert (tmp_path / "provider-calls.txt").read_text().splitlines() == ["start"] + + +@pytest.mark.parametrize(("binding", "provider_request"), [ + ({"operation": {"effect_class": "external_write"}}, {}), + ({"integration_profile_digest": "stored-profile"}, {}), + ({}, {"provider": {"profile_digest": "stored-profile"}}), +]) +def test_generic_transport_refuses_profiled_operations_before_dispatch(binding, provider_request): + from loopx.extensions.runtime import execute_extension_runtime_binding + + with pytest.raises(ValueError, match="require capability admission"): + execute_extension_runtime_binding(binding, request=provider_request) + + +def test_readback_only_request_cannot_create_a_new_invocation(tmp_path: Path) -> None: + args = _start_arguments(tmp_path) + with pytest.raises(ValueError, match="no original external write invocation"): + start_governed_external_capability(**args, execute=True, read_start_result=lambda _: None) + assert not (tmp_path / "provider-calls.txt").exists() + + +@pytest.mark.parametrize("crash_at", ["before_journal", "before_arm"]) +def test_process_exit_before_dispatch_allows_one_handoff(tmp_path, crash_at): + args = _start_arguments(tmp_path) + child = """ +import json, os, sys +import loopx.extensions.governed_capability_execution as g +write = g._write_journal +def crash(path, journal): + if sys.argv[1] == "before_journal" or journal.get("dispatch_armed") is True: + os._exit(73) + write(path, journal) +g._write_journal = crash +g.start_governed_external_capability(**json.load(sys.stdin), execute=True) +""" + child_result = subprocess.run([sys.executable, "-c", child, crash_at], input=json.dumps(args, default=str), + text=True, timeout=30, check=False) + assert child_result.returncode == 73 + assert not (tmp_path / "provider-calls.txt").exists() + next_owner = _identity(turn_instance_id="handoff") if crash_at == "before_journal" else _identity() + result = start_governed_external_capability( + **{**args, "turn_instance_id": next_owner.turn_instance_id, "admission": _admission(next_owner)}, execute=True, + ) + assert result["status"] == "running" + assert (tmp_path / "provider-calls.txt").read_text().splitlines() == ["start"] + + +def _service_reservation(query): + fields = ("challenge", "operation_key", "intent_digest", "request_digest", "invocation_id") + return {**{field: query[field] for field in fields}, + "status": "reserved_after_terminal_no_effect", "reservation_ref": "service-grant-1"} + + +@pytest.mark.parametrize("receiver", ["original", "successor"]) +@pytest.mark.parametrize("crash_at", ["before_lookup", "grant_reply_lost", "after_delivery"]) +def test_restored_process_exit_preserves_safe_retry_boundary(tmp_path, receiver, crash_at): + args = _start_arguments(tmp_path) + (tmp_path / "runtime" / paths.RESTORED_RUNTIME_MARKER).touch() + child = """ +import json, os, sys +from pathlib import Path +from loopx.extensions import governed_capability_execution as governed +from tests.extensions.test_governed_capability_execution import _service_reservation + +checkpoint, service = sys.argv[1], Path(sys.argv[2]) +def reserve(query): + if checkpoint == "before_lookup": + os._exit(73) + proof = _service_reservation(query) + (service / "provider-reservation.json").write_text(json.dumps(proof)) + if checkpoint == "grant_reply_lost": + os._exit(73) + return proof + +persist = governed._write_journal +def write(path, journal): + if checkpoint == "after_delivery" and journal.get("provider_result") is not None: + os._exit(73) + persist(path, journal) + +governed._write_journal = write +governed.start_governed_external_capability(**json.load(sys.stdin), execute=True, reserve_restored_start=reserve) +""" + exited = subprocess.run([sys.executable, "-c", child, crash_at, str(tmp_path)], + input=json.dumps(args, default=str), text=True, timeout=30, check=False) + assert exited.returncode == 73 + pending = tmp_path / "provider-reservation.json" + calls = tmp_path / "provider-calls.txt" + assert calls.exists() == (crash_at == "after_delivery") + assert pending.exists() == (crash_at == "grant_reply_lost") + journal_path, = Path(args["run_dir"]).glob("capability-*.json") + checkpoint = json.loads(journal_path.read_text()) + assert checkpoint["dispatch_armed"] is (crash_at == "after_delivery") + if crash_at == "after_delivery": + consumed = json.loads((tmp_path / "consumed-reservation.json").read_text()) + assert checkpoint["restored_start_reservation"] == consumed + else: + assert "restored_start_reservation" not in checkpoint + retry = args + if receiver == "successor": + identity = SettlementIdentity(goal_id=args["goal_id"], todo_id=args["todo_id"], + agent_id="receiving-agent", turn_instance_id="successor") + retry = {**args, "agent_id": identity.agent_id, "turn_instance_id": identity.turn_instance_id, + "admission": _admission(identity)} + + if crash_at == "after_delivery": + def forbidden(_query): + pytest.fail("an attempt that may have delivered must use original-result readback") + with pytest.raises(ValueError, match="unknown|unsettled"): + start_governed_external_capability(**retry, execute=True, reserve_restored_start=forbidden) + def read_effect(query): + ref = query["invocation_id"] + return {"request_digest": (tmp_path / f"{ref}.digest").read_text(), "target_key": query["target_key"], + "result": json.loads((tmp_path / f"{ref}.remote.json").read_text())} + received = start_governed_external_capability(**{**args, "admission": retry["admission"]}, + execute=True, read_start_result=read_effect) + else: + if pending.exists(): + # Until the service accounts for its unconsumed grant, no second grant is available. + with pytest.raises(ValueError, match="lacks a current provider reservation"): + start_governed_external_capability(**retry, execute=True, reserve_restored_start=lambda _: None) + assert not calls.exists() + def reserve_again(query): + if pending.exists(): + old = json.loads(pending.read_text()) + assert old["operation_key"] == query["operation_key"] and old["intent_digest"] == query["intent_digest"] + assert old["challenge"] != query["challenge"] + pending.rename(tmp_path / "revoked-unconsumed-grant.json") + proof = _service_reservation(query) + with pending.open("x") as grant: + json.dump(proof, grant) + return proof + received = start_governed_external_capability(**retry, execute=True, reserve_restored_start=reserve_again) + assert received["status"] == "running" + assert calls.read_text().splitlines() == ["start"] + + +def test_restored_grant_lookup_does_not_hold_unrelated_todos(tmp_path): + args = _start_arguments(tmp_path) + (tmp_path / "runtime" / paths.RESTORED_RUNTIME_MARKER).touch() + both_at_service = Barrier(2) + + def unavailable(_query): + both_at_service.wait(timeout=10) + return None + + def attempt(todo_id): + owner = SettlementIdentity(goal_id=args["goal_id"], todo_id=todo_id, agent_id=args["agent_id"], + turn_instance_id=todo_id) + admission = _admission(owner) + admission["selected_todo"]["target_key"] = f"fixture-material:{todo_id}" + with pytest.raises(ValueError, match="lacks a current provider reservation"): + start_governed_external_capability( + **{**args, "todo_id": todo_id, "turn_instance_id": owner.turn_instance_id, "admission": admission}, + execute=True, reserve_restored_start=unavailable, + ) + + with ThreadPoolExecutor(max_workers=2) as pool: + list(pool.map(attempt, ("todo_first", "todo_second"))) + assert not (tmp_path / "provider-calls.txt").exists() + + +@pytest.mark.parametrize("original_delivered", [True, False]) +def test_verified_pre_request_restore_requires_external_delivery_evidence(tmp_path, original_delivered): + from loopx.control_plane.state_recovery_io import verify_state_backup + from loopx.state_backup import build_state_backup_plan, execute_state_backup_plan + + args = _start_arguments(tmp_path) + runtime = tmp_path / "runtime" + args["run_dir"] = runtime / "extensions" / "governed-capability-runs" + backup = execute_state_backup_plan(build_state_backup_plan(project=tmp_path, runtime_root=runtime, + registry_path=args["registry_path"], output_dir=tmp_path / "backup", include_registry_projects=False, + include_skills=False, include_automations=False)) + calls = tmp_path / "provider-calls.txt" + if original_delivered: + original = start_governed_external_capability(**args, execute=True) + else: + (tmp_path / "reject-before-delivery").touch() + with pytest.raises(RuntimeError, match="provider reported failure"): + start_governed_external_capability(**args, execute=True) + # The independent service remains live when the control plane returns to its earlier snapshot. + inert = tmp_path / "inert" + audit = verify_state_backup(archive=Path(backup["archive_path"]), manifest=Path(backup["manifest_path"]), + destination=inert, execute=True) + assert audit["execution_authority_granted"] is False + assert not (runtime / paths.RESTORED_RUNTIME_MARKER).exists() + runtime.rename(tmp_path / "retired-runtime") + shutil.copytree(inert / "data" / "runtime-root", runtime) + receiving = SettlementIdentity(goal_id=args["goal_id"], agent_id="receiving-agent", todo_id=args["todo_id"], + turn_instance_id="restore-turn") + handoff = {**args, "agent_id": receiving.agent_id, "turn_instance_id": receiving.turn_instance_id, + "admission": _admission(receiving), "run_dir": tmp_path / "another-journal-dir"} + for execute in (False, True): + with pytest.raises(ValueError, match="restored runtime requires provider reconciliation"): + start_governed_external_capability(**handoff, execute=execute) + saved_challenge = {} + def unavailable(query): + saved_challenge.update(query) + return None + with pytest.raises(ValueError, match="lacks a current provider reservation"): + start_governed_external_capability(**handoff, reserve_restored_start=unavailable, execute=True) + with pytest.raises(ValueError, match="lacks a current provider reservation"): + start_governed_external_capability(**handoff, reserve_restored_start=lambda _: _service_reservation(saved_challenge), + execute=True) + if original_delivered: + invocation = original["invocation_id"] + stored_result = json.loads((tmp_path / f"{invocation}.remote.json").read_text()) + digest = (tmp_path / f"{invocation}.digest").read_text() + original_args = {**args, "admission": _admission(receiving)} + with pytest.raises(ValueError, match="does not attest"): + start_governed_external_capability(**original_args, execute=True, + read_start_result=lambda _: {"request_digest": "wrong", "result": stored_result}) + recovered = start_governed_external_capability(**original_args, execute=True, + read_start_result=lambda _: {"request_digest": digest, "target_key": "fixture-material:delivery-1", "result": stored_result}) + assert recovered["invocation_id"] == invocation + assert recovered["effect_id"] == original["effect_id"] + with pytest.raises(ValueError, match="requires provider readback"): + reconcile_governed_external_capability(run_dir=args["run_dir"], invocation_id=invocation, + writeback=lambda _: {}, spend=lambda _: {}) + terminal = {**stored_result, "status": "succeeded", "transition_proposals": [], + "effect_receipt": {"schema_version": "loopx_external_effect_receipt_v0", + "invocation_id": invocation, "idempotency_key": original["effect_id"], "status": "committed", + "external_ref": "provider-delivery-1", "evidence_digest": digest}} + settlements = [] + def settle(context): + settlements.append(context["settlement_identity"]["effect_id"]) + return {"ok": True, "appended": True, "settlement_identity": context["settlement_identity"], + "effect_receipt_digest": context["effect_receipt_digest"]} + for _ in range(2): + committed = reconcile_governed_external_capability(run_dir=args["run_dir"], invocation_id=invocation, + writeback=settle, spend=settle, read_running_result=lambda _: terminal) + assert committed["status"] == "committed" + assert settlements == [original["effect_id"], original["effect_id"]] + else: + # A fenced synchronous service issues one exclusive grant, and its actual dispatch consumes it. + def reserve(query): + closed_input = json.loads((tmp_path / "closed-without-delivery.json").read_text()) + if closed_input != query["request"]["input"]: + return None + if calls.exists() or (tmp_path / "consumed-reservation.json").exists(): + return None + permit = _service_reservation(query) + with (tmp_path / "provider-reservation.json").open("x") as file: + json.dump(permit, file) + return permit + recovered = start_governed_external_capability(**handoff, execute=True, reserve_restored_start=reserve) + assert (tmp_path / "consumed-reservation.json").is_file() + # A second cold copy with no local journal still cannot obtain another service grant. + second = {**args, "run_dir": tmp_path / "second-cold-copy"} + with pytest.raises(ValueError, match="lacks a current provider reservation"): + start_governed_external_capability(**second, execute=True, reserve_restored_start=reserve) + assert recovered["status"] == "running" + assert calls.read_text().splitlines() == ["start"] + + def test_legacy_provider_result_adapter_remains_available() -> None: result = { "schema_version": "fixture_material_capability_result_v0", @@ -394,15 +782,12 @@ def test_material_start_recovers_monitor_after_pre_receipt_crash( ) -> None: arguments = _start_arguments(tmp_path) original_write_journal = governed_execution._write_journal - write_count = 0 def crash_before_transition_receipt( path: Path, payload: Mapping[str, object], ) -> None: - nonlocal write_count - write_count += 1 - if write_count == 3: + if payload.get("transition_receipts"): raise RuntimeError("synthetic checkpoint crash") original_write_journal(path, payload) @@ -530,6 +915,24 @@ def spend(context: Mapping[str, object]) -> dict[str, object]: assert monitors[0]["status"] == "done" +def test_new_admitted_turn_can_start_after_previous_operation_settles(tmp_path: Path) -> None: + args = _start_arguments(tmp_path) + original = start_governed_external_capability(**args, execute=True) + committed = reconcile_governed_external_capability( + run_dir=args["run_dir"], invocation_id=original["invocation_id"], + writeback=lambda ctx: {"ok": True, "appended": True, "settlement_identity": ctx["settlement_identity"], + "effect_receipt_digest": ctx["effect_receipt_digest"]}, + spend=lambda ctx: {"ok": True, "appended": True, "settlement_identity": ctx["settlement_identity"]}, + ) + assert committed["status"] == "committed" + another = _identity(turn_instance_id="separately-admitted-turn") + started = start_governed_external_capability( + **{**args, "turn_instance_id": another.turn_instance_id, "admission": _admission(another)}, execute=True, + ) + assert started["invocation_id"] != original["invocation_id"] + assert (tmp_path / "provider-calls.txt").read_text().splitlines() == ["start", "reconcile", "start"] + + def test_material_start_rejects_a_different_selected_turn(tmp_path: Path) -> None: arguments = _start_arguments(tmp_path) arguments["admission"] = _admission( @@ -984,7 +1387,7 @@ def basis() -> str: before = basis() active_state = tmp_path / "ACTIVE_GOAL_STATE.md" - run_provider = governed_execution.execute_extension_runtime_binding + run_provider = governed_execution._execute_extension_runtime_binding def provider_while_state_moves(*args, **kwargs): active_state.write_text( @@ -997,7 +1400,7 @@ def provider_while_state_moves(*args, **kwargs): monkeypatch.setattr( governed_execution, - "execute_extension_runtime_binding", + "_execute_extension_runtime_binding", provider_while_state_moves, ) diff --git a/tests/test_state_recovery.py b/tests/test_state_recovery.py index b3d6718f5f..e3522297ef 100644 --- a/tests/test_state_recovery.py +++ b/tests/test_state_recovery.py @@ -223,7 +223,9 @@ def test_global_backup_inspects_the_canonical_source_not_a_same_alias_shared_sto assert expected["wrong"] not in files roots = backup["registry_discovery"]["goal_runtime_roots"] assert roots["goal-a"] != "runtime-root" - assert (destination / "data" / roots["goal-a"]).is_dir() + from loopx.paths import RESTORED_RUNTIME_MARKER + assert (destination / "data" / roots["goal-a"] / RESTORED_RUNTIME_MARKER).is_file() + assert (destination / "data" / "runtime-root" / RESTORED_RUNTIME_MARKER).is_file() assert not (destination / "registry.global.json").exists()