diff --git a/loopx/agent_registry.py b/loopx/agent_registry.py index da2788c690..428a4fb881 100644 --- a/loopx/agent_registry.py +++ b/loopx/agent_registry.py @@ -93,9 +93,13 @@ def agent_profile_for_goal(goal: dict[str, Any] | None, agent_id: str | None) -> def load_goal_from_registry(registry_path: Path, goal_id: str) -> dict[str, Any] | None: + from .control_plane.hook_runtime.request_scope import current_hook_request_scope from .history import load_registry from .registry import registry_goals + scope = current_hook_request_scope() + if scope is not None: + return scope.load_goal(registry_path, str(goal_id), loader=load_registry) if not registry_path.exists(): return None registry = load_registry(registry_path) diff --git a/loopx/capabilities/explore/turn_context.py b/loopx/capabilities/explore/turn_context.py index 22edc1e1eb..eba6171c18 100644 --- a/loopx/capabilities/explore/turn_context.py +++ b/loopx/capabilities/explore/turn_context.py @@ -15,6 +15,7 @@ TurnStartHookRegistration, TurnStartContextProjector, dispatch_turn_start_hooks, + merge_turn_start_dispatch, ) from ...control_plane.effect_runtime import effect_runtime_request_scope, effect_runtime_result from ...explore_graph import compact_explore_graph_policy @@ -296,14 +297,7 @@ def produce() -> dict[str, Any]: }, ) extra = dispatch_turn_start_hooks((hook,)) - result = dict(dispatch or {}) - for key in ("results", "required_reads", "failures", "contexts"): - if key == "contexts" and not extra.get(key): - continue - result[key] = list(result.get(key) or []) + list(extra.get(key) or []) - for key in ("registered_count", "invoked_count"): - result[key] = int(result.get(key) or 0) + int(extra.get(key) or 0) - return result + return merge_turn_start_dispatch(dispatch, extra, include_contexts=True) def project_settlement_attachment(plan: dict[str, Any], *, registry_path: Path, runtime_root: Path | None = None) -> dict[str, Any]: @@ -333,7 +327,12 @@ def produce() -> dict[str, Any]: projection_slots=("explore_result_attachment",), requested_read_scope=("goal.explore_policy",), producer=produce, ),)) - attachment = dispatch["projections"].get("explore_result_attachment") + projections = dispatch.get("projections") + attachment = ( + projections.get("explore_result_attachment") + if isinstance(projections, Mapping) + else None + ) if attachment is None: return ({**plan, "capability_hook_failures": dispatch["failures"]} if dispatch["failures"] else plan) diff --git a/loopx/capabilities/periodic_report/cadence_runtime.py b/loopx/capabilities/periodic_report/cadence_runtime.py index ba6d723fa5..65881d043c 100644 --- a/loopx/capabilities/periodic_report/cadence_runtime.py +++ b/loopx/capabilities/periodic_report/cadence_runtime.py @@ -7,7 +7,11 @@ from ...agent_registry import registered_agent_ids_for_goal from ...control_plane.capability_hooks import ( - TURN_START_HOOK_RESULT_SCHEMA_VERSION, TurnStartHookRegistration, dispatch_turn_start_hooks, + TURN_START_HOOK_RESULT_SCHEMA_VERSION, + TurnStartHookRegistration, + dispatch_turn_start_hooks, + load_scoped_registry, + merge_turn_start_dispatch, ) from ...history import load_registry from ...registry import find_registry_goal @@ -26,7 +30,10 @@ def periodic_report_cadence_hooks( ) -> tuple[TurnStartHookRegistration, ...]: if not agent_id: return () - goal = find_registry_goal(load_registry(registry_path), goal_id) + goal = find_registry_goal( + load_scoped_registry(registry_path, loader=load_registry), + goal_id, + ) subscription = resolve_active_goal_periodic_report_subscription( goal, read_periodic_report_machine_defaults(runtime_root)) if subscription is None or subscription.get("schedule") is None: @@ -116,14 +123,10 @@ def resolve_current_subscription(): def extend_cadence_turn_start_dispatch(dispatch: dict, **kwargs) -> dict: """Same optional composition for quota and the managed turn driver.""" + extra: dict[str, object] try: extra = dispatch_turn_start_hooks(periodic_report_cadence_hooks(**kwargs)) except (OSError, TypeError, ValueError): extra = {"failures": [{"hook_id": "periodic_report.cadence", "capability_id": "periodic-report", "error_code": "cadence_configuration_unavailable"}]} - result = dict(dispatch) - for key in ("results", "required_reads", "failures"): - result[key] = list(dispatch.get(key) or []) + list(extra.get(key) or []) - for key in ("registered_count", "invoked_count"): - result[key] = int(dispatch.get(key) or 0) + int(extra.get(key) or 0) - return result + return merge_turn_start_dispatch(dispatch, extra, include_contexts=False) diff --git a/loopx/capabilities/turn_start.py b/loopx/capabilities/turn_start.py index e6c8e2f083..d03da9aaf1 100644 --- a/loopx/capabilities/turn_start.py +++ b/loopx/capabilities/turn_start.py @@ -6,7 +6,11 @@ from pathlib import Path from typing import Any -from ..control_plane.capability_hooks import dispatch_turn_start_hooks +from ..control_plane.capability_hooks import ( + capability_hook_request_scope, + dispatch_turn_start_hooks, + merge_turn_start_dispatch, +) from ..control_plane.todos.contract import normalize_required_capabilities @@ -21,23 +25,22 @@ def extend_turn_start_dispatch(dispatch: dict[str, Any], *, registry_path: Path, factories = [("issue-fix", dependencies)] if normalize_required_capabilities(available): factories.append(("agent-capability-memory", capability_memory)) - registrations = [hook for capability, factory in factories if (hook := factory( - registry_path=registry_path, runtime_root=runtime_root, goal_id=goal_id, - agent_id=agent_id, available=available, - **(provider_options or {}).get(capability, {}), - )) is not None] - if not registrations: - return dispatch - extra = dispatch_turn_start_hooks(registrations) - result = dict(dispatch) - for key in ("results", "required_reads", "failures", "contexts"): - if extra.get(key): - result[key] = list(dispatch.get(key) or []) + list(extra[key]) - for key in ("registered_count", "invoked_count"): - result[key] = int(dispatch.get(key) or 0) + int(extra.get(key) or 0) - if extra.get("uncertain_local_effects"): - result["uncertain_local_effects"] = True - return result + with capability_hook_request_scope(): + registrations = [hook for capability, factory in factories if (hook := factory( + registry_path=registry_path, runtime_root=runtime_root, goal_id=goal_id, + agent_id=agent_id, available=available, + **(provider_options or {}).get(capability, {}), + )) is not None] + if not registrations: + return dispatch + extra = dispatch_turn_start_hooks(registrations) + return merge_turn_start_dispatch( + dispatch, + extra, + include_contexts=True, + only_nonempty_extra=True, + include_uncertain=True, + ) def attach_turn_start_effects(payload: dict[str, Any], dispatch: dict[str, Any]) -> None: diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index 1734638130..22aa489382 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -71,85 +71,91 @@ def dispatch_quota_turn_start_hooks( preview = bool(getattr(args, "dry_run", False)) if preview and not args.agent_id: return None, False - dispatch: dict[str, object] = {} - if not preview and lark_turn_start_hook_dispatcher is not None: - dispatch = lark_turn_start_hook_dispatcher( - registry_path=registry_path, - runtime_root_arg=runtime_root_arg, - goal_id=args.goal_id, - agent_id=args.agent_id, - ) - if args.agent_id: - from ..capabilities.manager_context import turn_start_hook - from ..capabilities.semantic_preference.agent_preferences import ( - extend_turn_start_dispatch as extend_preferences, - ) - from ..control_plane.capability_hooks import dispatch_turn_start_hooks - from ..history import load_registry - from ..paths import resolve_runtime_root - - root = resolve_runtime_root( - load_registry(registry_path), - runtime_root_arg, - registry_path=registry_path, - ) - if not preview: - from ..capabilities.turn_start import ( - extend_turn_start_dispatch as extend_registered_capabilities, - ) + from ..control_plane.capability_hooks import ( + capability_hook_request_scope, + dispatch_turn_start_hooks, + load_scoped_registry, + ) - dispatch = extend_registered_capabilities( - dispatch, + dispatch: dict[str, object] = {} + with capability_hook_request_scope(): + if not preview and lark_turn_start_hook_dispatcher is not None: + dispatch = lark_turn_start_hook_dispatcher( registry_path=registry_path, - runtime_root=root, + runtime_root_arg=runtime_root_arg, goal_id=args.goal_id, agent_id=args.agent_id, - available=args.available_capabilities, ) - # A preview still needs the current local Inbox and preferences. These - # hooks observe existing context without recording reads or delivery. - model_read = not getattr(args, "scheduler_observation", False) - context_dispatch = dispatch_turn_start_hooks( - ( - turn_start_hook( - root, - registry_path, - args.goal_id, - args.agent_id, - model_read=model_read, - ), - ) - ) - context_dispatch = extend_preferences( - context_dispatch, - runtime_root=root, - registry_path=registry_path, - goal_id=args.goal_id, - agent_id=args.agent_id, - ) - dispatch = dict(dispatch) - for key in ("results", "required_reads", "failures", "contexts"): - if key == "contexts" and not context_dispatch.get(key): - continue - dispatch[key] = list(dispatch.get(key) or []) + list( - context_dispatch.get(key) or [] - ) - for key in ("registered_count", "invoked_count"): - dispatch[key] = int(dispatch.get(key) or 0) + int( - context_dispatch.get(key) or 0 - ) - if not preview: - from ..capabilities.periodic_report.cadence_runtime import ( - extend_cadence_turn_start_dispatch, + if args.agent_id: + from ..capabilities.manager_context import turn_start_hook + from ..capabilities.semantic_preference.agent_preferences import ( + extend_turn_start_dispatch as extend_preferences, ) + from ..history import load_registry + from ..paths import resolve_runtime_root - dispatch = extend_cadence_turn_start_dispatch( - dispatch, + root = resolve_runtime_root( + load_scoped_registry(registry_path, loader=load_registry), + runtime_root_arg, registry_path=registry_path, + ) + if not preview: + from ..capabilities.turn_start import ( + extend_turn_start_dispatch as extend_registered_capabilities, + ) + + dispatch = extend_registered_capabilities( + dispatch, + registry_path=registry_path, + runtime_root=root, + goal_id=args.goal_id, + agent_id=args.agent_id, + available=args.available_capabilities, + ) + # A preview still needs the current local Inbox and preferences. These + # hooks observe existing context without recording reads or delivery. + model_read = not getattr(args, "scheduler_observation", False) + context_dispatch = dispatch_turn_start_hooks( + ( + turn_start_hook( + root, + registry_path, + args.goal_id, + args.agent_id, + model_read=model_read, + ), + ) + ) + context_dispatch = extend_preferences( + context_dispatch, runtime_root=root, + registry_path=registry_path, goal_id=args.goal_id, agent_id=args.agent_id, ) + dispatch = dict(dispatch) + for key in ("results", "required_reads", "failures", "contexts"): + if key == "contexts" and not context_dispatch.get(key): + continue + dispatch[key] = list(dispatch.get(key) or []) + list( + context_dispatch.get(key) or [] + ) + for key in ("registered_count", "invoked_count"): + dispatch[key] = int(dispatch.get(key) or 0) + int( + context_dispatch.get(key) or 0 + ) + if not preview: + from ..capabilities.periodic_report.cadence_runtime import ( + extend_cadence_turn_start_dispatch, + ) + + dispatch = extend_cadence_turn_start_dispatch( + dispatch, + registry_path=registry_path, + runtime_root=root, + goal_id=args.goal_id, + agent_id=args.agent_id, + ) local_private_state_mutated = bool(dispatch.get("uncertain_local_effects")) or any( isinstance(result, Mapping) and result.get("local_private_state_mutated") is not False diff --git a/loopx/control_plane/agents/capability_memory.py b/loopx/control_plane/agents/capability_memory.py index 649297ffd6..21c9be2264 100644 --- a/loopx/control_plane/agents/capability_memory.py +++ b/loopx/control_plane/agents/capability_memory.py @@ -222,7 +222,7 @@ def extend_turn_start_dispatch( normalized = normalize_required_capabilities(available) if not agent_id or not normalized: return dispatch - from ..capability_hooks import dispatch_turn_start_hooks + from ..capability_hooks import dispatch_turn_start_hooks, merge_turn_start_dispatch extra = dispatch_turn_start_hooks( ( @@ -235,12 +235,7 @@ def extend_turn_start_dispatch( ), ) ) - result = dict(dispatch) - for key in ("results", "required_reads", "failures"): - result[key] = list(dispatch.get(key) or []) + list(extra.get(key) or []) - for key in ("registered_count", "invoked_count"): - result[key] = int(dispatch.get(key) or 0) + int(extra.get(key) or 0) - return result + return merge_turn_start_dispatch(dispatch, extra, include_contexts=False) def heartbeat_evidence_poll_possible( diff --git a/loopx/control_plane/capability_hooks.py b/loopx/control_plane/capability_hooks.py index c51f681871..7bca2f37eb 100644 --- a/loopx/control_plane/capability_hooks.py +++ b/loopx/control_plane/capability_hooks.py @@ -1,605 +1,173 @@ from __future__ import annotations -import hashlib -import json -import re import time -from collections.abc import Callable, Mapping, Sequence -from contextlib import ExitStack -from dataclasses import dataclass +from collections.abc import Mapping, Sequence +from contextlib import AbstractContextManager, ExitStack from pathlib import Path -from typing import Any from ..file_lock import ( - LOCK_POLICIES, - LockAcquisitionPolicy, - LockAcquireTimeoutError, + LOCK_POLICIES as LOCK_POLICIES, + LockAcquisitionPolicy as LockAcquisitionPolicy, + LockAcquireTimeoutError as LockAcquireTimeoutError, exclusive_file_lock, ) from .effect_runtime import ( - EffectRuntimeRejected, - EffectRuntimeRemoteError, - EffectRuntimeStartupError, + EffectRuntimeRejected as EffectRuntimeRejected, + EffectRuntimeRemoteError as EffectRuntimeRemoteError, + EffectRuntimeStartupError as EffectRuntimeStartupError, effect_runtime_projection_result, effect_runtime_result, ) -from .coordination.coordination_state_contract_generated import ( - CAPABILITY_HOOK_INTERACTION_RESULT_SCHEMA, - CAPABILITY_HOOK_POST_WRITEBACK_INPUT_SCHEMA, - CAPABILITY_HOOK_POST_WRITEBACK_RECEIPT_SCHEMA, - CAPABILITY_HOOK_POST_WRITEBACK_REGISTRATION_SCHEMA, - CAPABILITY_HOOK_POST_WRITEBACK_RESULT_SCHEMA, - CAPABILITY_HOOK_REGISTRATION_SCHEMA, - CAPABILITY_HOOK_TURN_START_REGISTRATION_SCHEMA, - CAPABILITY_HOOK_TURN_START_RESULT_SCHEMA, +from .hook_runtime.contracts import ( + CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION as CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION, + INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION as INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION, + INTERACTION_PROJECTION_HOOK_RESULT_SCHEMA_VERSION as INTERACTION_PROJECTION_HOOK_RESULT_SCHEMA_VERSION, + LEGACY_LOCK_SAFE_SEGMENT_RE as _LEGACY_LOCK_SAFE_SEGMENT_RE, + POST_WRITEBACK_DISPATCH_ID_RE as _POST_WRITEBACK_DISPATCH_ID_RE, + POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION as POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_INPUT_SCHEMA_VERSION as POST_WRITEBACK_HOOK_INPUT_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_RECEIPT_SCHEMA_VERSION as POST_WRITEBACK_HOOK_RECEIPT_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION as POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_RESULT_SCHEMA_VERSION as POST_WRITEBACK_HOOK_RESULT_SCHEMA_VERSION, + POST_WRITEBACK_RECEIPT_SNAPSHOT_RE as _POST_WRITEBACK_RECEIPT_SNAPSHOT_RE, + POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE as POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE, + POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES as _POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES, + TURN_START_HOOK_DISPATCH_SCHEMA_VERSION as TURN_START_HOOK_DISPATCH_SCHEMA_VERSION, + TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION as TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION, + TURN_START_HOOK_RESULT_SCHEMA_VERSION as TURN_START_HOOK_RESULT_SCHEMA_VERSION, + InteractionProjectionHookRegistration as InteractionProjectionHookRegistration, + InteractionProjectionProducer as InteractionProjectionProducer, + PostWritebackHookRegistration as PostWritebackHookRegistration, + PostWritebackProducer as PostWritebackProducer, + PostWritebackSourceRejected as PostWritebackSourceRejected, + TurnContextHookRegistration as TurnContextHookRegistration, + TurnStartContextProjector as TurnStartContextProjector, + TurnStartHookRegistration as TurnStartHookRegistration, + TurnStartProducer as TurnStartProducer, + hook_failure as _hook_failure, ) - - -CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION = CAPABILITY_HOOK_REGISTRATION_SCHEMA -INTERACTION_PROJECTION_HOOK_RESULT_SCHEMA_VERSION = ( - CAPABILITY_HOOK_INTERACTION_RESULT_SCHEMA -) -INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION = ( - "loopx_interaction_projection_hook_dispatch_v0" +from .hook_runtime.dispatch import ( + dispatch_interaction_projection_hooks as _dispatch_interaction_projection_hooks_impl, + dispatch_turn_start_hooks as _dispatch_turn_start_hooks_impl, + merge_turn_start_dispatch as merge_turn_start_dispatch, ) -TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION = ( - CAPABILITY_HOOK_TURN_START_REGISTRATION_SCHEMA +from .hook_runtime.post_writeback import ( + bounded_post_writeback_transport_contracts as _bounded_post_writeback_transport_contracts, + bounded_post_writeback_transport_outcomes as _bounded_post_writeback_transport_outcomes, + decode_post_writeback_preflight as _decode_post_writeback_preflight, + dispatch_post_writeback_hooks as _dispatch_post_writeback_hooks_impl, + enter_legacy_post_writeback_guard as _enter_legacy_post_writeback_guard_impl, + legacy_post_writeback_lock_target as _legacy_post_writeback_lock_target, + post_writeback_contract_placeholder as _post_writeback_contract_placeholder, + post_writeback_failure_dispatch as _post_writeback_failure_dispatch, + post_writeback_finalize_params as _post_writeback_finalize_params, + post_writeback_provider_outcome as _post_writeback_provider_outcome, + post_writeback_receipt_snapshot as _post_writeback_receipt_snapshot, + post_writeback_runtime_failure as _post_writeback_runtime_failure, + post_writeback_transport_rejected_outcome as _post_writeback_transport_rejected_outcome, ) -TURN_START_HOOK_RESULT_SCHEMA_VERSION = CAPABILITY_HOOK_TURN_START_RESULT_SCHEMA -TURN_START_HOOK_DISPATCH_SCHEMA_VERSION = "loopx_turn_start_capability_hook_dispatch_v1" -POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION = ( - CAPABILITY_HOOK_POST_WRITEBACK_REGISTRATION_SCHEMA +from .hook_runtime.request_scope import ( + CapabilityHookRequestScope as CapabilityHookRequestScope, + capability_hook_request_scope as capability_hook_request_scope, + current_hook_registry_snapshots as current_hook_registry_snapshots, + current_hook_request_scope as current_hook_request_scope, + invalidate_hook_registry_snapshot as invalidate_hook_registry_snapshot, + load_scoped_registry as load_scoped_registry, ) -POST_WRITEBACK_HOOK_INPUT_SCHEMA_VERSION = CAPABILITY_HOOK_POST_WRITEBACK_INPUT_SCHEMA -POST_WRITEBACK_HOOK_RESULT_SCHEMA_VERSION = CAPABILITY_HOOK_POST_WRITEBACK_RESULT_SCHEMA -POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION = ( - "loopx_post_writeback_capability_hook_dispatch_v0" +from .hook_runtime.turn_context import ( + capability_result_fields as capability_result_fields, + dispatch_turn_context_hooks as _dispatch_turn_context_hooks_impl, + host_context_projection as host_context_projection, + project_turn_context as _project_turn_context_impl, + turn_context_binding_source as _turn_context_binding_source_impl, + turn_context_source as turn_context_source, ) -POST_WRITEBACK_HOOK_RECEIPT_SCHEMA_VERSION = ( - CAPABILITY_HOOK_POST_WRITEBACK_RECEIPT_SCHEMA -) -# Diagnostic code the TypeScript source decoder stamps on every source -# input-construction rejection. The decoder owns the field rules; this -# adapter only maps the typed category back to the legacy composition -# failure boundary and never re-validates the fields itself. -POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE = "post_writeback_source_invalid" -_LEGACY_LOCK_SAFE_SEGMENT_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,199}") -_POST_WRITEBACK_DISPATCH_ID_RE = re.compile(r"pwh_[0-9a-f]{64}") -_POST_WRITEBACK_RECEIPT_SNAPSHOT_RE = re.compile(r"(?:missing|sha256:[0-9a-f]{64})") -_POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES = 1_750_000 - -InteractionProjectionProducer = Callable[[], Mapping[str, Any]] -TurnStartProducer = Callable[[], Mapping[str, Any]] -# Invocation-owned read composition after selection; no persisted policy or -# provider authority is created by supplying this adapter. -TurnStartContextProjector = Callable[ - [Mapping[str, Any], Mapping[str, Any] | None], dict[str, Any] | None -] -PostWritebackProducer = Callable[[Mapping[str, Any]], Mapping[str, Any]] - - -class PostWritebackSourceRejected(ValueError): - """The typed runtime rejected deterministic source construction.""" - - -@dataclass(frozen=True, slots=True) -class TurnContextHookRegistration: - """Configured provider IO after governing selection, before host input. - - Registration bounds IO/results; it grants no provider or task authority. - """ - - hook_id: str - capability_id: str - readback_slots: tuple[str, ...] - producer: Callable[[], Mapping[str, Any]] - max_result_bytes: int = 64 * 1024 - def contract(self) -> dict[str, Any]: - return { - "hook_id": self.hook_id, - "capability_id": self.capability_id, - "readback_slots": list(self.readback_slots), - "max_result_bytes": self.max_result_bytes, - } +def _call_effect_runtime_result(method: str, params: Mapping[str, object]) -> object: + return effect_runtime_result(method, params) -@dataclass(frozen=True, slots=True) -class InteractionProjectionHookRegistration: - """One read-only capability contribution to an interaction contract.""" - hook_id: str - capability_id: str - projection_slots: tuple[str, ...] - requested_read_scope: tuple[str, ...] - producer: InteractionProjectionProducer - max_result_bytes: int = 16 * 1024 +def _call_effect_runtime_projection_result( + method: str, + params: Mapping[str, object], +) -> object: + return effect_runtime_projection_result(method, params) - def contract(self) -> dict[str, Any]: - return { - "schema_version": CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION, - "hook_id": self.hook_id, - "capability_id": self.capability_id, - "phase": "interaction_projection", - "projection_slots": list(self.projection_slots), - "budget": { - "max_invocations_per_dispatch": 1, - "max_result_bytes": self.max_result_bytes, - }, - "failure_policy": "isolate", - "requested_read_scope": list(self.requested_read_scope), - "requested_write_scope": [], - } - -@dataclass(frozen=True, slots=True) -class TurnStartHookRegistration: - """One bounded provider observation before a LoopX turn is selected.""" - - hook_id: str - capability_id: str - requested_read_scope: tuple[str, ...] - requested_write_scope: tuple[str, ...] - producer: TurnStartProducer - max_result_bytes: int = 16 * 1024 - required_read: Mapping[str, Any] | None = None - context_reader: Callable[[], Mapping[str, Any]] | None = None - - def contract(self) -> dict[str, Any]: - return { - "schema_version": TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION, - "hook_id": self.hook_id, - "capability_id": self.capability_id, - "phase": "turn_start", - "budget": { - "max_invocations_per_dispatch": 1, - "max_result_bytes": self.max_result_bytes, - }, - "failure_policy": "isolate", - "requested_read_scope": list(self.requested_read_scope), - "requested_write_scope": list(self.requested_write_scope), - "required_read": ( - dict(self.required_read) if self.required_read is not None else None - ), - } - - -@dataclass(frozen=True, slots=True) -class PostWritebackHookRegistration: - """One effect-free capability observer of a committed primary writeback.""" - - hook_id: str - capability_id: str - event_kinds: tuple[str, ...] - intent_kinds: tuple[str, ...] - requested_read_scope: tuple[str, ...] - producer: PostWritebackProducer - policy_version: str = "v0" - max_input_bytes: int = 64 * 1024 - max_result_bytes: int = 16 * 1024 - - def contract(self) -> dict[str, Any]: - return { - "schema_version": POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION, - "hook_id": self.hook_id, - "capability_id": self.capability_id, - "policy_version": self.policy_version, - "phase": "post_writeback", - "event_kinds": list(self.event_kinds), - "intent_kinds": list(self.intent_kinds), - "budget": { - "max_invocations_per_dispatch": 1, - "max_input_bytes": self.max_input_bytes, - "max_result_bytes": self.max_result_bytes, - }, - "failure_policy": "isolate", - "requested_read_scope": list(self.requested_read_scope), - "requested_write_scope": [], - } +def _call_turn_context_source(payload: Mapping[str, object]) -> Mapping[str, object]: + return turn_context_source(payload) -def turn_context_source(payload: Mapping[str, Any]) -> Mapping[str, Any]: - """Use the host envelope or the native quota identity, without new authority.""" - if "work_contract" in payload: - from .quota.turn_envelope import turn_plan_host_source - from .quota.turn_envelope import complete_turn_host_source +def _acquire_exclusive_file_lock( + path: Path, + *, + operation: str | None = None, + timeout_seconds: float | None = None, +) -> AbstractContextManager[object]: + return exclusive_file_lock( + path, + operation=operation, + timeout_seconds=timeout_seconds, + ) - source = complete_turn_host_source(turn_plan_host_source(payload), operation="plan_work") - assert source is not None - return source - envelope = payload.get("turn_envelope") - if isinstance(envelope, Mapping): - return envelope - if "schema_version" in payload or "contract_binding" in payload: - from .quota.turn_envelope import quota_capability_automation_source - # A declared native contract must pass the same complete-source owner - # as participation. Never reinterpret a damaged version as raw quota. - source = quota_capability_automation_source(payload) - if isinstance(payload.get("heartbeat_receipt"), Mapping): - return {**payload, "agent_id": source.get("agent_id")} - return {"goal_id": source.get("goal_id"), "agent_id": source.get("agent_id")} - agent_id = payload.get("agent_id") - identity = payload.get("agent_identity") - if isinstance(identity, Mapping): - scoped_agent = identity.get("agent_id") - if agent_id and scoped_agent and agent_id != scoped_agent: - raise ValueError("context source has conflicting Agent identities") - agent_id = agent_id or scoped_agent - if isinstance(payload.get("heartbeat_receipt"), Mapping): - # Keep the native source for the typed quota signature owner. Identity - # alone cannot invalidate context when the admitted authority changes; - # Python does not decode the quota boundary here. - return {**payload, "agent_id": agent_id} - return {"goal_id": payload.get("goal_id"), "agent_id": agent_id} +def _read_monotonic() -> float: + return time.monotonic() def _turn_context_binding_source( - payload: Mapping[str, Any], *, from_journal: bool = False, -) -> Mapping[str, Any]: - from .quota.turn_envelope import ( - COMPLETE_TURN_PLAN_SCHEMA_VERSION, - complete_turn_host_source, - turn_plan_host_source, + payload: Mapping[str, object], + *, + from_journal: bool = False, +) -> Mapping[str, object]: + return _turn_context_binding_source_impl( + payload, + from_journal=from_journal, + turn_context_source_fn=_call_turn_context_source, ) - if payload.get("schema_version") == COMPLETE_TURN_PLAN_SCHEMA_VERSION: - source = complete_turn_host_source( - turn_plan_host_source(payload), operation="host_context_binding", - recorded_capability_result=from_journal, - ) - assert source is not None - return source - return turn_context_source(payload) - def dispatch_turn_context_hooks( - payload: dict[str, Any], + payload: dict[str, object], registrations: Sequence[TurnContextHookRegistration], ) -> None: - contributions: list[dict[str, Any]] = [] - failures: list[dict[str, str]] = [] - seen_hooks: set[str] = set() - seen_slots: set[str] = set() - for registration in registrations: - try: - if registration.hook_id in seen_hooks or seen_slots.intersection( - registration.readback_slots - ): - raise ValueError("duplicate context registration") - seen_hooks.add(registration.hook_id) - seen_slots.update(registration.readback_slots) - effect_runtime_result( - "capability_hook.turn_context.validate_registration", - { - "registration": registration.contract(), - }, - ) - if any(key in payload for key in registration.readback_slots): - raise ValueError("context readback slot already contributed") - result = registration.producer() - readback_only = ( - result.get("context_fields") == {} - and result.get("instructions") == [] - and result.get("result_fields") == {} - ) - if readback_only: - binding: dict[str, Any] = {"readback_only": True} - else: - source = _turn_context_binding_source(payload) - binding = {"source": source} - if isinstance(source.get("heartbeat_receipt"), Mapping): - from .quota.turn_envelope import pack_turn_source - - transport = pack_turn_source(source) - if transport is not None: - binding = {"source_transport": transport} - contribution = effect_runtime_result( - "capability_hook.turn_context.validate", - { - "registration": registration.contract(), - "result": result, - **binding, - }, - ) - readback = contribution.pop("readback") - payload.update(readback) - if ( - contribution["context_fields"] - or contribution["instructions"] - or contribution["result_fields"] - ): - contributions.append(contribution) - except Exception: # Optional context failures never gate business work. - failures.append( - {"hook_id": registration.hook_id, "error_code": "context_hook_failed"} - ) - if contributions: - payload["turn_context_contributions"] = contributions - if failures: - payload["turn_context_hook_failures"] = failures + _dispatch_turn_context_hooks_impl( + payload, + registrations, + effect_runtime_result_fn=_call_effect_runtime_result, + turn_context_source_fn=_call_turn_context_source, + ) def project_turn_context( - payload: Mapping[str, Any], *, from_journal: bool = False, -) -> dict[str, Any]: - contributions = payload.get("turn_context_contributions") - if not isinstance(contributions, list) or not contributions: - return {} - readback: dict[str, Any] = {} - for item in contributions: - if not isinstance(item, Mapping): - continue - slots = item.get("readback_slots") - if isinstance(slots, (list, tuple)): - readback.update({key: payload.get(key) for key in slots if isinstance(key, str)}) - try: - projected = effect_runtime_projection_result("capability_hook.turn_context.project", { - "contributions": contributions, - "source": _turn_context_binding_source(payload, from_journal=from_journal), - "readback": readback, - }) - except Exception: # Optional context transport cannot gate the underlying work. - return {} - return projected if isinstance(projected, dict) else {} - - -def host_context_projection(request: Mapping[str, Any]) -> dict[str, Any]: - fields = request.get("capability_context_fields") or () - projection = {key: request[key] for key in fields if key in request} - if ( - projection - or request.get("capability_instructions") - or request.get("capability_result_fields") - ): - projection["capability_instructions"] = list( - request.get("capability_instructions") or () - ) - projection["capability_result_fields"] = dict( - request.get("capability_result_fields") or {} - ) - return projection - - -def capability_result_fields(request: Mapping[str, Any] | None) -> dict[str, Any]: - value = ( - request.get("capability_result_fields") - if isinstance(request, Mapping) - else None + payload: Mapping[str, object], + *, + from_journal: bool = False, +) -> dict[str, object]: + return _project_turn_context_impl( + payload, + from_journal=from_journal, + effect_runtime_projection_result_fn=_call_effect_runtime_projection_result, + turn_context_source_fn=_call_turn_context_source, ) - return dict(value) if isinstance(value, Mapping) else {} def dispatch_interaction_projection_hooks( registrations: Sequence[InteractionProjectionHookRegistration] | None, -) -> dict[str, Any]: - """Validate and combine read-only projections without granting effects.""" - - projections: dict[str, Any] = {} - failures: list[dict[str, str]] = [] - projected_hooks: list[str] = [] - for registration in registrations or (): - try: - effect_runtime_result( - "capability_hook.interaction_projection.validate_registration", - {"registration": registration.contract()}, - ) - except (EffectRuntimeRejected, RuntimeError, TypeError, ValueError): - failures.append( - _hook_failure(registration, error_code="registration_rejected") - ) - continue - try: - result = dict(registration.producer()) - except Exception: # Capability failures are isolated by contract. - failures.append(_hook_failure(registration, error_code="producer_failed")) - continue - try: - normalized = effect_runtime_result( - "capability_hook.interaction_projection.validate", - { - "registration": registration.contract(), - "result": result, - }, - ) - except (EffectRuntimeRejected, RuntimeError, TypeError, ValueError): - failures.append(_hook_failure(registration, error_code="contract_rejected")) - continue - if not isinstance(normalized, Mapping): - failures.append( - _hook_failure(registration, error_code="runtime_result_invalid") - ) - continue - if normalized.get("status") != "projected": - continue - slot = normalized.get("projection_slot") - projection = normalized.get("projection") - if not isinstance(slot, str) or not isinstance(projection, Mapping): - failures.append( - _hook_failure(registration, error_code="runtime_result_invalid") - ) - continue - if slot in projections: - failures.append( - _hook_failure(registration, error_code="projection_slot_conflict") - ) - continue - projections[slot] = dict(projection) - projected_hooks.append(registration.hook_id) - return { - "schema_version": INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION, - "phase": "interaction_projection", - "registered_count": len(registrations or ()), - "projected_hooks": projected_hooks, - "projections": projections, - "failures": failures, - } +) -> dict[str, object]: + return _dispatch_interaction_projection_hooks_impl( + registrations, + effect_runtime_result_fn=_call_effect_runtime_result, + ) def dispatch_turn_start_hooks( registrations: Sequence[TurnStartHookRegistration] | None, -) -> dict[str, Any]: - """Run bounded pre-turn observations without exposing provider payloads.""" - - results: list[dict[str, Any]] = [] - required_reads: list[dict[str, Any]] = [] - failures: list[dict[str, str]] = [] - contexts: list[dict[str, Any]] = [] - seen_hook_ids: set[str] = set() - seen_required_read_commands: set[str] = set() - uncertain_local_effects = False - ordered = sorted(registrations or (), key=lambda item: item.hook_id) - for registration in ordered: - if registration.hook_id in seen_hook_ids: - failures.append(_hook_failure(registration, error_code="duplicate_hook_id")) - continue - seen_hook_ids.add(registration.hook_id) - try: - admitted_registration = effect_runtime_result( - "capability_hook.turn_start.validate_registration", - {"registration": registration.contract()}, - ) - except (EffectRuntimeRejected, RuntimeError, TypeError, ValueError): - failures.append( - _hook_failure(registration, error_code="registration_rejected") - ) - continue - try: - result = dict(registration.producer()) - except Exception: # noqa: BLE001 - capability failures are isolated. - failures.append(_hook_failure(registration, error_code="producer_failed")) - uncertain_local_effects |= bool(registration.requested_write_scope) - continue - try: - normalized = effect_runtime_result( - "capability_hook.turn_start.validate", - { - "registration": registration.contract(), - "result": result, - }, - ) - except (EffectRuntimeRejected, RuntimeError, TypeError, ValueError): - failures.append(_hook_failure(registration, error_code="contract_rejected")) - uncertain_local_effects |= bool(registration.requested_write_scope) - continue - if not isinstance(normalized, Mapping): - failures.append( - _hook_failure(registration, error_code="runtime_result_invalid") - ) - uncertain_local_effects |= bool(registration.requested_write_scope) - continue - results.append(dict(normalized)) - if normalized.get("agent_read_required") is True and isinstance( - admitted_registration, Mapping - ): - required_read = admitted_registration.get("required_read") - if isinstance(required_read, Mapping): - command = str(required_read.get("command") or "").strip() - if command and command not in seen_required_read_commands: - required_reads.append( - { - **dict(required_read), - "source": "turn_start_capability_hook", - "hook_id": registration.hook_id, - "capability_id": registration.capability_id, - } - ) - seen_required_read_commands.add(command) - if registration.context_reader is not None: - # Invoke the registered read adapter, never its displayed - # shell command. Discovery receipts remain content-free. - try: - content = dict(registration.context_reader()) - contexts.append({"command": command, "content": content}) - except Exception: # noqa: BLE001 - preserve an actionable read on failure. - contexts.append({"command": command, "error_code": "context_source_unavailable"}) - return { - "schema_version": TURN_START_HOOK_DISPATCH_SCHEMA_VERSION, - "phase": "turn_start", - "registered_count": len(registrations or ()), - "invoked_count": len(results), - "results": results, - "required_reads": required_reads, - "failures": failures, - **({"uncertain_local_effects": True} if uncertain_local_effects else {}), - **({"contexts": contexts} if contexts else {}), - } - - -def _post_writeback_failure_dispatch( - registrations: Sequence[PostWritebackHookRegistration], - *, - error_code: str, - invoked_count: int = 0, - runtime_failure: Mapping[str, str] | None = None, -) -> dict[str, Any]: - dispatch: dict[str, Any] = { - "schema_version": POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION, - "phase": "post_writeback", - "registered_count": len(registrations), - "invoked_count": invoked_count, - "replayed_hooks": [], - "retried_hooks": [], - "intent_count": 0, - "intents": [], - "failures": [ - _hook_failure(registration, error_code=error_code) - for registration in registrations - ], - "primary_writeback_preserved": True, - "external_writes_performed": False, - } - if runtime_failure is not None: - dispatch["runtime_failure"] = dict(runtime_failure) - return dispatch - - -def _post_writeback_runtime_failure( - error: BaseException, - *, - phase: str, -) -> dict[str, str]: - if isinstance(error, EffectRuntimeRemoteError): - error_kind = error.error_kind - diagnostic_code = error.diagnostic_code - elif isinstance(error, EffectRuntimeStartupError): - error_kind = "startup_failed" - diagnostic_code = error.diagnostic_code - elif isinstance(error, OSError): - error_kind = "local_io_failed" - diagnostic_code = "runtime_transport_io_failed" - else: - error_kind = "local_contract_invalid" - diagnostic_code = "runtime_result_shape_invalid" - return { - "schema_version": "loopx_post_writeback_runtime_failure_v0", - "phase": phase, - "error_kind": error_kind, - "diagnostic_code": diagnostic_code, - } - - -def _legacy_post_writeback_lock_target( - runtime_root: Path, - plan: Mapping[str, Any], -) -> Path: - """Bridge the retired Python journal lock during rolling upgrades.""" - - dispatch_id = str(plan.get("dispatch_id") or "") - hook_input = plan.get("hook_input") - identity = hook_input.get("identity") if isinstance(hook_input, Mapping) else None - raw_goal_id = identity.get("goal_id") if isinstance(identity, Mapping) else None - goal_id = raw_goal_id.strip() if isinstance(raw_goal_id, str) else "" - if not _POST_WRITEBACK_DISPATCH_ID_RE.fullmatch(dispatch_id): - raise ValueError("post-writeback provider dispatch_id is invalid") - if not _LEGACY_LOCK_SAFE_SEGMENT_RE.fullmatch(goal_id): - raise ValueError("post-writeback provider goal_id is invalid") - return ( - runtime_root - / "goals" - / goal_id - / "post_writeback_hooks" - / f"{dispatch_id}.json" +) -> dict[str, object]: + return _dispatch_turn_start_hooks_impl( + registrations, + effect_runtime_result_fn=_call_effect_runtime_result, ) @@ -607,453 +175,103 @@ def _enter_legacy_post_writeback_guard( guards: ExitStack, *, runtime_root: Path, - raw_plan: Mapping[str, Any], + raw_plan: Mapping[str, object], lease_timeout_seconds: float | None, ) -> str | None: - """Acquire one legacy writer guard immediately before its provider.""" - - try: - target = _legacy_post_writeback_lock_target(runtime_root, raw_plan) - except (TypeError, ValueError): - return "lock_failed" - plan_guard = ExitStack() - try: - plan_guard.enter_context( - exclusive_file_lock( - target, - operation="post_writeback_hook_dispatch", - timeout_seconds=lease_timeout_seconds, - ) - ) - except LockAcquireTimeoutError: - plan_guard.close() - return "lock_unavailable" - except OSError: - plan_guard.close() - return "lock_failed" - - expected_snapshot = raw_plan.get("receipt_snapshot") - if not isinstance( - expected_snapshot, str - ) or not _POST_WRITEBACK_RECEIPT_SNAPSHOT_RE.fullmatch(expected_snapshot): - plan_guard.close() - return "lock_failed" - try: - current_snapshot = _post_writeback_receipt_snapshot(target) - except OSError: - plan_guard.close() - return "lock_failed" - if current_snapshot != expected_snapshot: - plan_guard.close() - return "receipt_changed" - - guards.callback(plan_guard.close) - return None - - -def _post_writeback_receipt_snapshot(path: Path) -> str: - try: - encoded = path.read_bytes() - except FileNotFoundError: - return "missing" - return f"sha256:{hashlib.sha256(encoded).hexdigest()}" - - -def _post_writeback_finalize_params( - base_request: Mapping[str, Any], - *, - transaction_id: object, - outcomes: Sequence[Mapping[str, Any]], -) -> dict[str, Any]: - return { - **base_request, - "phase": "finalize", - "transaction_id": transaction_id, - "provider_outcomes": [dict(outcome) for outcome in outcomes], - } - - -def _post_writeback_transport_rejected_outcome( - outcome: Mapping[str, Any], -) -> dict[str, Any]: - return { - "dispatch_id": outcome.get("dispatch_id"), - "hook_id": outcome.get("hook_id"), - "capability_id": outcome.get("capability_id"), - "attempt_count": outcome.get("attempt_count"), - "status": "contract_rejected", - "result": None, - } - - -def _bounded_post_writeback_transport_outcomes( - base_request: Mapping[str, Any], - *, - transaction_id: object, - outcomes: Sequence[Mapping[str, Any]], -) -> list[dict[str, Any]]: - """Admit the smallest JSON-safe results into the real Python wire budget.""" - - bounded: list[dict[str, Any]] = [] - candidates: list[tuple[int, int, dict[str, Any]]] = [] - for index, raw_outcome in enumerate(outcomes): - outcome = dict(raw_outcome) - if outcome.get("status") != "returned": - bounded.append(outcome) - continue - rejected = _post_writeback_transport_rejected_outcome(outcome) - bounded.append(rejected) - try: - rejected_size = len(json.dumps(rejected, separators=(",", ":")).encode()) - outcome_size = len(json.dumps(outcome, separators=(",", ":")).encode()) - except (OverflowError, RecursionError, TypeError, ValueError): - continue - candidates.append((outcome_size - rejected_size, index, outcome)) - - baseline = _post_writeback_finalize_params( - base_request, - transaction_id=transaction_id, - outcomes=bounded, + return _enter_legacy_post_writeback_guard_impl( + guards, + runtime_root=runtime_root, + raw_plan=raw_plan, + lease_timeout_seconds=lease_timeout_seconds, + exclusive_file_lock_fn=_acquire_exclusive_file_lock, ) - admitted_size = len(json.dumps(baseline, separators=(",", ":")).encode()) - if admitted_size > _POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES: - raise ValueError("post-writeback finalize transport baseline is oversized") - - for delta, index, outcome in sorted(candidates): - if admitted_size + delta > _POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES: - continue - bounded[index] = outcome - admitted_size += delta - - finalized = _post_writeback_finalize_params( - base_request, - transaction_id=transaction_id, - outcomes=bounded, - ) - if ( - len(json.dumps(finalized, separators=(",", ":")).encode()) - > _POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES - ): - raise ValueError("post-writeback finalize transport admission drifted") - return bounded - - -def _decode_post_writeback_preflight( - value: object, -) -> tuple[dict[str, Any] | None, list[Mapping[str, Any]]]: - if not isinstance(value, Mapping): - raise ValueError("post-writeback transaction preflight is invalid") - terminal_dispatch = value.get("dispatch") - if isinstance(terminal_dispatch, Mapping): - return dict(terminal_dispatch), [] - provider_plan = value.get("provider_plan") - if not isinstance(provider_plan, list): - raise ValueError("post-writeback provider plan is invalid") - typed_provider_plan: list[Mapping[str, Any]] = [] - for raw_plan in provider_plan: - if not isinstance(raw_plan, Mapping): - raise ValueError("post-writeback provider step is invalid") - typed_provider_plan.append(raw_plan) - return None, typed_provider_plan - - -def _post_writeback_provider_outcome( - raw_plan: Mapping[str, Any], - *, - registration: PostWritebackHookRegistration | None, - unavailable_status: str | None, -) -> tuple[dict[str, Any], bool]: - """Invoke one effect-free provider and isolate its JSON transport boundary.""" - - admitted_input = raw_plan.get("hook_input") - if registration is None or not isinstance(admitted_input, Mapping): - raise ValueError("post-writeback provider step is unbound") - invoked = unavailable_status is None - if unavailable_status is not None: - result = None - status = unavailable_status - else: - try: - produced = dict(registration.producer(dict(admitted_input))) - except Exception: # noqa: BLE001 - provider failures isolate. - result = None - status = "producer_failed" - else: - try: - encoded_result = json.dumps( - produced, - allow_nan=False, - ensure_ascii=False, - separators=(",", ":"), - ).encode("utf-8") - result = json.loads(encoded_result) - except (OverflowError, RecursionError, TypeError, ValueError): - result = None - status = "contract_rejected" - else: - status = "returned" - return ( - { - "dispatch_id": raw_plan.get("dispatch_id"), - "hook_id": raw_plan.get("hook_id"), - "capability_id": raw_plan.get("capability_id"), - "attempt_count": raw_plan.get("attempt_count"), - "status": status, - "result": result, - }, - invoked, - ) - - -def _post_writeback_contract_placeholder( - registration: PostWritebackHookRegistration, -) -> dict[str, object]: - hook_id = registration.hook_id - capability_id = registration.capability_id - return { - "hook_id": ( - hook_id if isinstance(hook_id, str) and len(hook_id) <= 200 else "" - ), - "capability_id": ( - capability_id - if isinstance(capability_id, str) and len(capability_id) <= 200 - else "" - ), - } - - -def _bounded_post_writeback_transport_contracts( - registrations: Sequence[PostWritebackHookRegistration], - *, - shared_request: Mapping[str, Any], -) -> list[dict[str, Any]]: - """Keep one malformed registration from making the shared JSON wire unusable.""" - - bounded: list[dict[str, Any]] = [] - candidates: list[tuple[int, int, dict[str, Any]]] = [] - for index, registration in enumerate(registrations): - placeholder = _post_writeback_contract_placeholder(registration) - bounded.append(placeholder) - try: - encoded = json.dumps( - registration.contract(), - allow_nan=False, - separators=(",", ":"), - ).encode() - contract = json.loads(encoded) - if not isinstance(contract, dict): - continue - placeholder_size = len( - json.dumps(placeholder, separators=(",", ":")).encode() - ) - except ( - AttributeError, - OverflowError, - RecursionError, - TypeError, - ValueError, - ): - continue - candidates.append((len(encoded) - placeholder_size, index, contract)) - - request = {**shared_request, "registrations": bounded} - admitted_size = len(json.dumps(request, separators=(",", ":")).encode()) - if admitted_size > _POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES: - raise ValueError("post-writeback preflight transport baseline is oversized") - for delta, index, contract in sorted(candidates): - if admitted_size + delta > _POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES: - continue - bounded[index] = contract - admitted_size += delta - return bounded def dispatch_post_writeback_hooks( registrations: Sequence[PostWritebackHookRegistration] | None, *, - source: Mapping[str, Any] | None = None, - hook_input: Mapping[str, Any] | None = None, + source: Mapping[str, object] | None = None, + hook_input: Mapping[str, object] | None = None, runtime_root: Path | None = None, lease_timeout_seconds: float | None = None, -) -> dict[str, Any]: - """Run one TS-owned hook transaction around effect-free Python providers. - - The Python adapter exits when providers and the committed-writeback caller - run in TypeScript. Its legacy-writer guard exits earlier only when TypeScript - owns an execution claim spanning provider invocation and receipt commit. - """ - - ordered_registrations = tuple(registrations or ()) - if not ordered_registrations: - return _post_writeback_failure_dispatch( - ordered_registrations, - error_code="registration_or_input_rejected", - ) - if (source is None) == (hook_input is None): - return _post_writeback_failure_dispatch( - ordered_registrations, - error_code="registration_or_input_rejected", - ) - invoked_count = 0 - runtime_phase = "preflight" - try: - source_packet = dict(source) if source is not None else None - legacy_hook_input = dict(hook_input) if hook_input is not None else None - runtime_root_text = str(runtime_root.resolve()) if runtime_root else None - shared_request = { - "schema_version": "loopx_post_writeback_hook_transaction_request_v0", - "runtime_root": runtime_root_text, - "source": source_packet, - "hook_input": legacy_hook_input, - } - contracts = _bounded_post_writeback_transport_contracts( - ordered_registrations, - shared_request={ - **shared_request, - "phase": "preflight", - "transaction_id": None, - "provider_outcomes": [], - }, - ) - base_request = {**shared_request, "registrations": contracts} - providers: dict[tuple[str, str], PostWritebackHookRegistration] = {} - for registration in ordered_registrations: - if not isinstance(registration.hook_id, str) or not isinstance( - registration.capability_id, str - ): - continue - key = (registration.hook_id, registration.capability_id) - providers.setdefault(key, registration) - - preflight_request = { - **base_request, - "phase": "preflight", - "transaction_id": None, - "provider_outcomes": [], - } - preflight = effect_runtime_result( - "capability_hook.post_writeback.transaction", - preflight_request, - ) - terminal_dispatch, typed_provider_plan = _decode_post_writeback_preflight( - preflight - ) - if terminal_dispatch is not None: - return terminal_dispatch - transaction_id = preflight.get("transaction_id") - if not isinstance(transaction_id, str): - raise ValueError("post-writeback transaction_id is invalid") - - sizing_outcomes = [ - { - "dispatch_id": raw_plan.get("dispatch_id"), - "hook_id": raw_plan.get("hook_id"), - "capability_id": raw_plan.get("capability_id"), - "attempt_count": raw_plan.get("attempt_count"), - "status": "contract_rejected", - "result": None, - } - for raw_plan in typed_provider_plan - ] - _bounded_post_writeback_transport_outcomes( - base_request, - transaction_id=transaction_id, - outcomes=sizing_outcomes, - ) - - runtime_phase = "provider" - compatibility_timeout = ( - LOCK_POLICIES[LockAcquisitionPolicy.MUTATION].timeout_seconds - if lease_timeout_seconds is None - else max(0.0, lease_timeout_seconds) - ) - compatibility_deadline = time.monotonic() + compatibility_timeout - with ExitStack() as legacy_writer_guards: - outcomes: list[dict[str, Any]] = [] - for raw_plan in typed_provider_plan: - key = ( - str(raw_plan.get("hook_id") or ""), - str(raw_plan.get("capability_id") or ""), - ) - provider_registration = providers.get(key) - unavailable_status = ( - _enter_legacy_post_writeback_guard( - legacy_writer_guards, - runtime_root=runtime_root, - raw_plan=raw_plan, - lease_timeout_seconds=max( - 0.0, compatibility_deadline - time.monotonic() - ), - ) - if runtime_root is not None - else None - ) - outcome, invoked = _post_writeback_provider_outcome( - raw_plan, - registration=provider_registration, - unavailable_status=unavailable_status, - ) - invoked_count += int(invoked) - outcomes.append(outcome) - bounded_outcomes = _bounded_post_writeback_transport_outcomes( - base_request, - transaction_id=transaction_id, - outcomes=outcomes, - ) - runtime_phase = "finalize" - finalized = effect_runtime_result( - "capability_hook.post_writeback.transaction", - _post_writeback_finalize_params( - base_request, - transaction_id=transaction_id, - outcomes=bounded_outcomes, - ), - ) - if not isinstance(finalized, Mapping) or not isinstance( - finalized.get("dispatch"), Mapping - ): - raise ValueError("post-writeback transaction result is invalid") - return dict(finalized["dispatch"]) - except (EffectRuntimeRejected, OSError, RuntimeError, TypeError, ValueError) as exc: - if ( - isinstance(exc, EffectRuntimeRejected) - and exc.diagnostic_code == POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE - ): - # The TypeScript decoder owns source legality. Its typed - # input-construction rejection crosses this boundary as the - # legacy composition ValueError, so callers keep reporting one - # source_projection_failed failure instead of per-hook - # runtime_result_invalid noise; every other rejection stays a - # runtime failure without string matching or field copies. - raise PostWritebackSourceRejected( - "post-writeback hooks require committed source identity fields" - ) from exc - return _post_writeback_failure_dispatch( - ordered_registrations, - error_code="runtime_result_invalid", - invoked_count=invoked_count, - runtime_failure=_post_writeback_runtime_failure( - exc, - phase=runtime_phase, - ), - ) +) -> dict[str, object]: + """Run one TS-owned hook transaction around effect-free Python providers.""" + + return _dispatch_post_writeback_hooks_impl( + registrations, + source=source, + hook_input=hook_input, + runtime_root=runtime_root, + lease_timeout_seconds=lease_timeout_seconds, + effect_runtime_result_fn=_call_effect_runtime_result, + exclusive_file_lock_fn=_acquire_exclusive_file_lock, + monotonic_fn=_read_monotonic, + ) -def _hook_failure( - registration: ( - InteractionProjectionHookRegistration - | TurnStartHookRegistration - | PostWritebackHookRegistration - ), - *, - error_code: str, - durable_receipt_ref: str | None = None, -) -> dict[str, str]: - failure = { - "hook_id": registration.hook_id, - "capability_id": registration.capability_id, - "error_code": error_code, - } - if durable_receipt_ref is not None: - failure["durable_receipt_ref"] = durable_receipt_ref - return failure +__all__ = [ + "CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION", + "CapabilityHookRequestScope", + "EffectRuntimeRejected", + "EffectRuntimeRemoteError", + "EffectRuntimeStartupError", + "INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION", + "INTERACTION_PROJECTION_HOOK_RESULT_SCHEMA_VERSION", + "InteractionProjectionHookRegistration", + "InteractionProjectionProducer", + "LOCK_POLICIES", + "LockAcquireTimeoutError", + "LockAcquisitionPolicy", + "POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_INPUT_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_RECEIPT_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_RESULT_SCHEMA_VERSION", + "POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE", + "PostWritebackHookRegistration", + "PostWritebackProducer", + "PostWritebackSourceRejected", + "TURN_START_HOOK_DISPATCH_SCHEMA_VERSION", + "TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION", + "TURN_START_HOOK_RESULT_SCHEMA_VERSION", + "TurnContextHookRegistration", + "TurnStartContextProjector", + "TurnStartHookRegistration", + "TurnStartProducer", + "_LEGACY_LOCK_SAFE_SEGMENT_RE", + "_POST_WRITEBACK_DISPATCH_ID_RE", + "_POST_WRITEBACK_RECEIPT_SNAPSHOT_RE", + "_POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES", + "_bounded_post_writeback_transport_contracts", + "_bounded_post_writeback_transport_outcomes", + "_decode_post_writeback_preflight", + "_enter_legacy_post_writeback_guard", + "_hook_failure", + "_legacy_post_writeback_lock_target", + "_post_writeback_contract_placeholder", + "_post_writeback_failure_dispatch", + "_post_writeback_finalize_params", + "_post_writeback_provider_outcome", + "_post_writeback_receipt_snapshot", + "_post_writeback_runtime_failure", + "_post_writeback_transport_rejected_outcome", + "_turn_context_binding_source", + "capability_hook_request_scope", + "capability_result_fields", + "current_hook_registry_snapshots", + "current_hook_request_scope", + "dispatch_interaction_projection_hooks", + "dispatch_post_writeback_hooks", + "dispatch_turn_context_hooks", + "dispatch_turn_start_hooks", + "effect_runtime_projection_result", + "effect_runtime_result", + "exclusive_file_lock", + "host_context_projection", + "invalidate_hook_registry_snapshot", + "load_scoped_registry", + "merge_turn_start_dispatch", + "project_turn_context", + "time", + "turn_context_source", +] diff --git a/loopx/control_plane/hook_runtime/__init__.py b/loopx/control_plane/hook_runtime/__init__.py new file mode 100644 index 0000000000..11fd07ad1f --- /dev/null +++ b/loopx/control_plane/hook_runtime/__init__.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +from .contracts import ( + CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION, + INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION, + INTERACTION_PROJECTION_HOOK_RESULT_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_INPUT_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_RECEIPT_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION, + POST_WRITEBACK_HOOK_RESULT_SCHEMA_VERSION, + POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE, + TURN_START_HOOK_DISPATCH_SCHEMA_VERSION, + TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION, + TURN_START_HOOK_RESULT_SCHEMA_VERSION, + InteractionProjectionHookRegistration, + InteractionProjectionProducer, + PostWritebackHookRegistration, + PostWritebackProducer, + PostWritebackSourceRejected, + TurnContextHookRegistration, + TurnStartContextProjector, + TurnStartHookRegistration, + TurnStartProducer, + hook_failure, +) +from .dispatch import ( + dispatch_interaction_projection_hooks, + dispatch_turn_start_hooks, +) +from .post_writeback import ( + bounded_post_writeback_transport_contracts, + bounded_post_writeback_transport_outcomes, + decode_post_writeback_preflight, + dispatch_post_writeback_hooks, + enter_legacy_post_writeback_guard, + legacy_post_writeback_lock_target, + post_writeback_contract_placeholder, + post_writeback_failure_dispatch, + post_writeback_finalize_params, + post_writeback_provider_outcome, + post_writeback_receipt_snapshot, + post_writeback_runtime_failure, + post_writeback_transport_rejected_outcome, +) +from .request_scope import ( + CapabilityHookRequestScope, + capability_hook_request_scope, + current_hook_registry_snapshots, + current_hook_request_scope, + invalidate_hook_registry_snapshot, + load_scoped_registry, +) +from .turn_context import ( + capability_result_fields, + dispatch_turn_context_hooks, + host_context_projection, + project_turn_context, + turn_context_binding_source, + turn_context_source, +) + +__all__ = [ + "CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION", + "CapabilityHookRequestScope", + "INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION", + "INTERACTION_PROJECTION_HOOK_RESULT_SCHEMA_VERSION", + "InteractionProjectionHookRegistration", + "InteractionProjectionProducer", + "POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_INPUT_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_RECEIPT_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_RESULT_SCHEMA_VERSION", + "POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE", + "PostWritebackHookRegistration", + "PostWritebackProducer", + "PostWritebackSourceRejected", + "TURN_START_HOOK_DISPATCH_SCHEMA_VERSION", + "TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION", + "TURN_START_HOOK_RESULT_SCHEMA_VERSION", + "TurnContextHookRegistration", + "TurnStartContextProjector", + "TurnStartHookRegistration", + "TurnStartProducer", + "bounded_post_writeback_transport_contracts", + "bounded_post_writeback_transport_outcomes", + "capability_hook_request_scope", + "capability_result_fields", + "current_hook_registry_snapshots", + "current_hook_request_scope", + "decode_post_writeback_preflight", + "dispatch_interaction_projection_hooks", + "dispatch_post_writeback_hooks", + "dispatch_turn_context_hooks", + "dispatch_turn_start_hooks", + "enter_legacy_post_writeback_guard", + "hook_failure", + "host_context_projection", + "invalidate_hook_registry_snapshot", + "legacy_post_writeback_lock_target", + "load_scoped_registry", + "post_writeback_contract_placeholder", + "post_writeback_failure_dispatch", + "post_writeback_finalize_params", + "post_writeback_provider_outcome", + "post_writeback_receipt_snapshot", + "post_writeback_runtime_failure", + "post_writeback_transport_rejected_outcome", + "project_turn_context", + "turn_context_binding_source", + "turn_context_source", +] diff --git a/loopx/control_plane/hook_runtime/contracts.py b/loopx/control_plane/hook_runtime/contracts.py new file mode 100644 index 0000000000..7eba377ffe --- /dev/null +++ b/loopx/control_plane/hook_runtime/contracts.py @@ -0,0 +1,254 @@ +from __future__ import annotations + +import re +from collections.abc import Callable, Mapping +from contextlib import AbstractContextManager +from dataclasses import dataclass +from pathlib import Path +from typing import Protocol, TypeAlias + +from ..coordination.coordination_state_contract_generated import ( + CAPABILITY_HOOK_INTERACTION_RESULT_SCHEMA, + CAPABILITY_HOOK_POST_WRITEBACK_INPUT_SCHEMA, + CAPABILITY_HOOK_POST_WRITEBACK_RECEIPT_SCHEMA, + CAPABILITY_HOOK_POST_WRITEBACK_REGISTRATION_SCHEMA, + CAPABILITY_HOOK_POST_WRITEBACK_RESULT_SCHEMA, + CAPABILITY_HOOK_REGISTRATION_SCHEMA, + CAPABILITY_HOOK_TURN_START_REGISTRATION_SCHEMA, + CAPABILITY_HOOK_TURN_START_RESULT_SCHEMA, +) + +CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION = CAPABILITY_HOOK_REGISTRATION_SCHEMA +INTERACTION_PROJECTION_HOOK_RESULT_SCHEMA_VERSION = ( + CAPABILITY_HOOK_INTERACTION_RESULT_SCHEMA +) +INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION = ( + "loopx_interaction_projection_hook_dispatch_v0" +) +TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION = ( + CAPABILITY_HOOK_TURN_START_REGISTRATION_SCHEMA +) +TURN_START_HOOK_RESULT_SCHEMA_VERSION = CAPABILITY_HOOK_TURN_START_RESULT_SCHEMA +TURN_START_HOOK_DISPATCH_SCHEMA_VERSION = "loopx_turn_start_capability_hook_dispatch_v1" +POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION = ( + CAPABILITY_HOOK_POST_WRITEBACK_REGISTRATION_SCHEMA +) +POST_WRITEBACK_HOOK_INPUT_SCHEMA_VERSION = CAPABILITY_HOOK_POST_WRITEBACK_INPUT_SCHEMA +POST_WRITEBACK_HOOK_RESULT_SCHEMA_VERSION = CAPABILITY_HOOK_POST_WRITEBACK_RESULT_SCHEMA +POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION = ( + "loopx_post_writeback_capability_hook_dispatch_v0" +) +POST_WRITEBACK_HOOK_RECEIPT_SCHEMA_VERSION = ( + CAPABILITY_HOOK_POST_WRITEBACK_RECEIPT_SCHEMA +) +# Diagnostic code the TypeScript source decoder stamps on every source +# input-construction rejection. The decoder owns the field rules; this +# adapter only maps the typed category back to the legacy composition +# failure boundary and never re-validates the fields itself. +POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE = "post_writeback_source_invalid" +LEGACY_LOCK_SAFE_SEGMENT_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,199}") +POST_WRITEBACK_DISPATCH_ID_RE = re.compile(r"pwh_[0-9a-f]{64}") +POST_WRITEBACK_RECEIPT_SNAPSHOT_RE = re.compile(r"(?:missing|sha256:[0-9a-f]{64})") +POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES = 1_750_000 + +HookPayload: TypeAlias = Mapping[str, object] +HookRecord: TypeAlias = dict[str, object] +InteractionProjectionProducer = Callable[[], Mapping[str, object]] +TurnStartProducer = Callable[[], Mapping[str, object]] +# Invocation-owned read composition after selection; no persisted policy or +# provider authority is created by supplying this adapter. +TurnStartContextProjector = Callable[ + [Mapping[str, object], Mapping[str, object] | None], dict[str, object] | None +] +PostWritebackProducer = Callable[[Mapping[str, object]], Mapping[str, object]] + + +class EffectRuntimeResultFn(Protocol): + """Callable surface matching `effect_runtime_result(method, params)`.""" + + def __call__(self, method: str, params: Mapping[str, object]) -> object: ... + + +class EffectRuntimeProjectionFn(Protocol): + """Callable surface matching `effect_runtime_projection_result(method, params)`.""" + + def __call__(self, method: str, params: Mapping[str, object]) -> object: ... + + +class TurnContextSourceFn(Protocol): + """Callable surface resolving a hook payload's source metadata.""" + + def __call__(self, payload: Mapping[str, object]) -> Mapping[str, object]: ... + + +class ExclusiveFileLockFn(Protocol): + """Callable surface matching `exclusive_file_lock` for legacy write guards.""" + + def __call__( + self, + path: Path, + *, + operation: str | None = None, + timeout_seconds: float | None = None, + ) -> AbstractContextManager[object]: ... + + +class MonotonicFn(Protocol): + """Monotonic clock callback injected for deterministic deadline tests.""" + + def __call__(self) -> float: ... + + +class PostWritebackSourceRejected(ValueError): + """The typed runtime rejected deterministic source construction.""" + + +@dataclass(frozen=True, slots=True) +class TurnContextHookRegistration: + """Configured provider IO after governing selection, before host input. + + Registration bounds IO/results; it grants no provider or task authority. + """ + + hook_id: str + capability_id: str + readback_slots: tuple[str, ...] + producer: Callable[[], Mapping[str, object]] + max_result_bytes: int = 64 * 1024 + + def contract(self) -> dict[str, object]: + return { + "hook_id": self.hook_id, + "capability_id": self.capability_id, + "readback_slots": list(self.readback_slots), + "max_result_bytes": self.max_result_bytes, + } + + +@dataclass(frozen=True, slots=True) +class InteractionProjectionHookRegistration: + """One read-only capability contribution to an interaction contract.""" + + hook_id: str + capability_id: str + projection_slots: tuple[str, ...] + requested_read_scope: tuple[str, ...] + producer: InteractionProjectionProducer + max_result_bytes: int = 16 * 1024 + + def contract(self) -> dict[str, object]: + return { + "schema_version": CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION, + "hook_id": self.hook_id, + "capability_id": self.capability_id, + "phase": "interaction_projection", + "projection_slots": list(self.projection_slots), + "budget": { + "max_invocations_per_dispatch": 1, + "max_result_bytes": self.max_result_bytes, + }, + "failure_policy": "isolate", + "requested_read_scope": list(self.requested_read_scope), + "requested_write_scope": [], + } + + +@dataclass(frozen=True, slots=True) +class TurnStartHookRegistration: + """One bounded provider observation before a LoopX turn is selected.""" + + hook_id: str + capability_id: str + requested_read_scope: tuple[str, ...] + requested_write_scope: tuple[str, ...] + producer: TurnStartProducer + max_result_bytes: int = 16 * 1024 + required_read: Mapping[str, object] | None = None + context_reader: Callable[[], Mapping[str, object]] | None = None + + def contract(self) -> dict[str, object]: + return { + "schema_version": TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION, + "hook_id": self.hook_id, + "capability_id": self.capability_id, + "phase": "turn_start", + "budget": { + "max_invocations_per_dispatch": 1, + "max_result_bytes": self.max_result_bytes, + }, + "failure_policy": "isolate", + "requested_read_scope": list(self.requested_read_scope), + "requested_write_scope": list(self.requested_write_scope), + "required_read": ( + dict(self.required_read) if self.required_read is not None else None + ), + } + + +@dataclass(frozen=True, slots=True) +class PostWritebackHookRegistration: + """One effect-free capability observer of a committed primary writeback.""" + + hook_id: str + capability_id: str + event_kinds: tuple[str, ...] + intent_kinds: tuple[str, ...] + requested_read_scope: tuple[str, ...] + producer: PostWritebackProducer + policy_version: str = "v0" + max_input_bytes: int = 64 * 1024 + max_result_bytes: int = 16 * 1024 + + def contract(self) -> dict[str, object]: + return { + "schema_version": POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION, + "hook_id": self.hook_id, + "capability_id": self.capability_id, + "policy_version": self.policy_version, + "phase": "post_writeback", + "event_kinds": list(self.event_kinds), + "intent_kinds": list(self.intent_kinds), + "budget": { + "max_invocations_per_dispatch": 1, + "max_input_bytes": self.max_input_bytes, + "max_result_bytes": self.max_result_bytes, + }, + "failure_policy": "isolate", + "requested_read_scope": list(self.requested_read_scope), + "requested_write_scope": [], + } + + +def as_string_dict(value: object, *, error_message: str) -> dict[str, object]: + """Narrow a runtime mapping payload to a concrete `dict[str, object]`.""" + + if not isinstance(value, Mapping): + raise ValueError(error_message) + record: dict[str, object] = {} + for key, item in value.items(): + if not isinstance(key, str): + raise ValueError(error_message) + record[key] = item + return record + + +def hook_failure( + registration: ( + InteractionProjectionHookRegistration + | TurnStartHookRegistration + | PostWritebackHookRegistration + ), + *, + error_code: str, + durable_receipt_ref: str | None = None, +) -> dict[str, str]: + """Build one normalized failure row for hook dispatch diagnostics.""" + + failure = { + "hook_id": registration.hook_id, + "capability_id": registration.capability_id, + "error_code": error_code, + } + if durable_receipt_ref is not None: + failure["durable_receipt_ref"] = durable_receipt_ref + return failure diff --git a/loopx/control_plane/hook_runtime/dispatch.py b/loopx/control_plane/hook_runtime/dispatch.py new file mode 100644 index 0000000000..06cc8c74e4 --- /dev/null +++ b/loopx/control_plane/hook_runtime/dispatch.py @@ -0,0 +1,285 @@ +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence + +from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result +from .contracts import ( + INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION, + TURN_START_HOOK_DISPATCH_SCHEMA_VERSION, + EffectRuntimeResultFn, + InteractionProjectionHookRegistration, + TurnStartHookRegistration, + as_string_dict, + hook_failure, +) +from .request_scope import capability_hook_request_scope + + +def _evaluate_interaction_projection_hook( + registration: InteractionProjectionHookRegistration, + *, + invoke: EffectRuntimeResultFn, + projections: dict[str, object], + failures: list[dict[str, str]], + projected_hooks: list[str], +) -> None: + try: + invoke( + "capability_hook.interaction_projection.validate_registration", + {"registration": registration.contract()}, + ) + except (EffectRuntimeRejected, RuntimeError, TypeError, ValueError): + failures.append(hook_failure(registration, error_code="registration_rejected")) + return + try: + result = dict(registration.producer()) + except Exception: # Capability failures are isolated by contract. + failures.append(hook_failure(registration, error_code="producer_failed")) + return + try: + normalized = invoke( + "capability_hook.interaction_projection.validate", + { + "registration": registration.contract(), + "result": result, + }, + ) + except (EffectRuntimeRejected, RuntimeError, TypeError, ValueError): + failures.append(hook_failure(registration, error_code="contract_rejected")) + return + if not isinstance(normalized, Mapping): + failures.append(hook_failure(registration, error_code="runtime_result_invalid")) + return + if normalized.get("status") != "projected": + return + slot = normalized.get("projection_slot") + projection = normalized.get("projection") + if not isinstance(slot, str) or not isinstance(projection, Mapping): + failures.append(hook_failure(registration, error_code="runtime_result_invalid")) + return + if slot in projections: + failures.append( + hook_failure(registration, error_code="projection_slot_conflict") + ) + return + projections[slot] = as_string_dict( + projection, + error_message="interaction projection slot payload must have string keys", + ) + projected_hooks.append(registration.hook_id) + + +def dispatch_interaction_projection_hooks( + registrations: Sequence[InteractionProjectionHookRegistration] | None, + *, + effect_runtime_result_fn: EffectRuntimeResultFn | None = None, +) -> dict[str, object]: + """Validate and combine read-only projections without granting effects.""" + + invoke = effect_runtime_result_fn or effect_runtime_result + projections: dict[str, object] = {} + failures: list[dict[str, str]] = [] + projected_hooks: list[str] = [] + ordered_registrations = registrations or () + with capability_hook_request_scope(): + for registration in ordered_registrations: + _evaluate_interaction_projection_hook( + registration, + invoke=invoke, + projections=projections, + failures=failures, + projected_hooks=projected_hooks, + ) + return { + "schema_version": INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION, + "phase": "interaction_projection", + "registered_count": len(ordered_registrations), + "projected_hooks": projected_hooks, + "projections": projections, + "failures": failures, + } + + +def _collect_turn_start_required_read( + registration: TurnStartHookRegistration, + admitted_registration: object, + normalized: Mapping[str, object], + *, + seen_commands: set[str], + required_reads: list[dict[str, object]], + contexts: list[dict[str, object]], +) -> None: + if normalized.get("agent_read_required") is not True or not isinstance( + admitted_registration, Mapping + ): + return + required_read = admitted_registration.get("required_read") + if not isinstance(required_read, Mapping): + return + command = str(required_read.get("command") or "").strip() + if not command or command in seen_commands: + return + required_reads.append( + { + **{str(k): v for k, v in required_read.items()}, + "source": "turn_start_capability_hook", + "hook_id": registration.hook_id, + "capability_id": registration.capability_id, + } + ) + seen_commands.add(command) + if registration.context_reader is None: + return + # Invoke the registered read adapter, never its displayed shell command. + # Discovery receipts remain content-free. + try: + content = dict(registration.context_reader()) + contexts.append({"command": command, "content": content}) + except Exception: # noqa: BLE001 - preserve an actionable read on failure. + contexts.append({"command": command, "error_code": "context_source_unavailable"}) + + +def _evaluate_turn_start_hook( + registration: TurnStartHookRegistration, + *, + invoke: EffectRuntimeResultFn, + seen_hook_ids: set[str], + seen_required_read_commands: set[str], + results: list[dict[str, object]], + required_reads: list[dict[str, object]], + failures: list[dict[str, str]], + contexts: list[dict[str, object]], +) -> bool: + if registration.hook_id in seen_hook_ids: + failures.append(hook_failure(registration, error_code="duplicate_hook_id")) + return False + seen_hook_ids.add(registration.hook_id) + try: + admitted_registration = invoke( + "capability_hook.turn_start.validate_registration", + {"registration": registration.contract()}, + ) + except (EffectRuntimeRejected, RuntimeError, TypeError, ValueError): + failures.append(hook_failure(registration, error_code="registration_rejected")) + return False + try: + result = dict(registration.producer()) + except Exception: # noqa: BLE001 - capability failures are isolated. + failures.append(hook_failure(registration, error_code="producer_failed")) + return bool(registration.requested_write_scope) + try: + normalized = invoke( + "capability_hook.turn_start.validate", + { + "registration": registration.contract(), + "result": result, + }, + ) + except (EffectRuntimeRejected, RuntimeError, TypeError, ValueError): + failures.append(hook_failure(registration, error_code="contract_rejected")) + return bool(registration.requested_write_scope) + if not isinstance(normalized, Mapping): + failures.append( + hook_failure(registration, error_code="runtime_result_invalid") + ) + return bool(registration.requested_write_scope) + results.append( + as_string_dict( + normalized, + error_message="turn start validation returned invalid key types", + ) + ) + _collect_turn_start_required_read( + registration, + admitted_registration, + normalized, + seen_commands=seen_required_read_commands, + required_reads=required_reads, + contexts=contexts, + ) + return False + + +def dispatch_turn_start_hooks( + registrations: Sequence[TurnStartHookRegistration] | None, + *, + effect_runtime_result_fn: EffectRuntimeResultFn | None = None, +) -> dict[str, object]: + """Run bounded pre-turn observations without exposing provider payloads.""" + + invoke = effect_runtime_result_fn or effect_runtime_result + results: list[dict[str, object]] = [] + required_reads: list[dict[str, object]] = [] + failures: list[dict[str, str]] = [] + contexts: list[dict[str, object]] = [] + seen_hook_ids: set[str] = set() + seen_required_read_commands: set[str] = set() + uncertain_local_effects = False + registered = registrations or () + ordered = sorted(registered, key=lambda item: item.hook_id) + with capability_hook_request_scope(): + for registration in ordered: + uncertain_local_effects |= _evaluate_turn_start_hook( + registration, + invoke=invoke, + seen_hook_ids=seen_hook_ids, + seen_required_read_commands=seen_required_read_commands, + results=results, + required_reads=required_reads, + failures=failures, + contexts=contexts, + ) + dispatch: dict[str, object] = { + "schema_version": TURN_START_HOOK_DISPATCH_SCHEMA_VERSION, + "phase": "turn_start", + "registered_count": len(registered), + "invoked_count": len(results), + "results": results, + "required_reads": required_reads, + "failures": failures, + } + if uncertain_local_effects: + dispatch["uncertain_local_effects"] = True + if contexts: + dispatch["contexts"] = contexts + return dispatch + + +def _object_list(value: object) -> list[object]: + if isinstance(value, list): + return list(value) + if isinstance(value, Iterable) and not isinstance(value, (str, bytes, Mapping)): + return list(value) + return [] + + +def _count_int(value: object) -> int: + if isinstance(value, int): + return int(value) + if isinstance(value, (float, str, bytes)): + return int(value) + return 0 + + +def merge_turn_start_dispatch( + dispatch: Mapping[str, object] | None, + extra: Mapping[str, object], + *, + include_contexts: bool = True, + only_nonempty_extra: bool = False, + include_uncertain: bool = False, +) -> dict[str, object]: + """Merge an additional turn-start dispatch packet without dynamic `Any` loops.""" + + result = dict(dispatch or {}) + for key in ("results", "required_reads", "failures", "contexts"): + if key == "contexts" and (not include_contexts or not extra.get(key)): + continue + if only_nonempty_extra and not extra.get(key): + continue + result[key] = _object_list(result.get(key)) + _object_list(extra.get(key)) + for key in ("registered_count", "invoked_count"): + result[key] = _count_int(result.get(key)) + _count_int(extra.get(key)) + if include_uncertain and extra.get("uncertain_local_effects"): + result["uncertain_local_effects"] = True + return result diff --git a/loopx/control_plane/hook_runtime/post_writeback.py b/loopx/control_plane/hook_runtime/post_writeback.py new file mode 100644 index 0000000000..67374cb75d --- /dev/null +++ b/loopx/control_plane/hook_runtime/post_writeback.py @@ -0,0 +1,628 @@ +from __future__ import annotations + +import hashlib +import json +import time +from collections.abc import Mapping, Sequence +from contextlib import ExitStack +from pathlib import Path + +from ...file_lock import ( + LOCK_POLICIES, + LockAcquisitionPolicy, + LockAcquireTimeoutError, + exclusive_file_lock, +) +from ..effect_runtime import ( + EffectRuntimeRejected, + EffectRuntimeRemoteError, + EffectRuntimeStartupError, + effect_runtime_result, +) +from .contracts import ( + LEGACY_LOCK_SAFE_SEGMENT_RE, + POST_WRITEBACK_DISPATCH_ID_RE, + POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION, + POST_WRITEBACK_RECEIPT_SNAPSHOT_RE, + POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE, + POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES, + EffectRuntimeResultFn, + ExclusiveFileLockFn, + MonotonicFn, + PostWritebackHookRegistration, + PostWritebackSourceRejected, + as_string_dict, + hook_failure, +) +from .request_scope import capability_hook_request_scope + + +def post_writeback_failure_dispatch( + registrations: Sequence[PostWritebackHookRegistration], + *, + error_code: str, + invoked_count: int = 0, + runtime_failure: Mapping[str, str] | None = None, +) -> dict[str, object]: + """Construct the closed failure envelope when transaction dispatch fails.""" + + dispatch: dict[str, object] = { + "schema_version": POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION, + "phase": "post_writeback", + "registered_count": len(registrations), + "invoked_count": invoked_count, + "replayed_hooks": [], + "retried_hooks": [], + "intent_count": 0, + "intents": [], + "failures": [ + hook_failure(registration, error_code=error_code) + for registration in registrations + ], + "primary_writeback_preserved": True, + "external_writes_performed": False, + } + if runtime_failure is not None: + dispatch["runtime_failure"] = dict(runtime_failure) + return dispatch + + +def post_writeback_runtime_failure( + error: BaseException, + *, + phase: str, +) -> dict[str, str]: + """Classify a post-writeback runtime failure by transport/IO phase.""" + + if isinstance(error, EffectRuntimeRemoteError): + error_kind = error.error_kind + diagnostic_code = error.diagnostic_code + elif isinstance(error, EffectRuntimeStartupError): + error_kind = "startup_failed" + diagnostic_code = error.diagnostic_code + elif isinstance(error, OSError): + error_kind = "local_io_failed" + diagnostic_code = "runtime_transport_io_failed" + else: + error_kind = "local_contract_invalid" + diagnostic_code = "runtime_result_shape_invalid" + return { + "schema_version": "loopx_post_writeback_runtime_failure_v0", + "phase": phase, + "error_kind": error_kind, + "diagnostic_code": diagnostic_code, + } + + +def legacy_post_writeback_lock_target( + runtime_root: Path, + plan: Mapping[str, object], +) -> Path: + """Bridge the retired Python journal lock during rolling upgrades.""" + + dispatch_id = str(plan.get("dispatch_id") or "") + hook_input = plan.get("hook_input") + identity = hook_input.get("identity") if isinstance(hook_input, Mapping) else None + raw_goal_id = identity.get("goal_id") if isinstance(identity, Mapping) else None + goal_id = raw_goal_id.strip() if isinstance(raw_goal_id, str) else "" + if not POST_WRITEBACK_DISPATCH_ID_RE.fullmatch(dispatch_id): + raise ValueError("post-writeback provider dispatch_id is invalid") + if not LEGACY_LOCK_SAFE_SEGMENT_RE.fullmatch(goal_id): + raise ValueError("post-writeback provider goal_id is invalid") + return ( + runtime_root + / "goals" + / goal_id + / "post_writeback_hooks" + / f"{dispatch_id}.json" + ) + + +def post_writeback_receipt_snapshot(path: Path) -> str: + """Return the content-addressed digest of an existing receipt or `'missing'`.""" + + try: + encoded = path.read_bytes() + except FileNotFoundError: + return "missing" + return f"sha256:{hashlib.sha256(encoded).hexdigest()}" + + +def enter_legacy_post_writeback_guard( + guards: ExitStack, + *, + runtime_root: Path, + raw_plan: Mapping[str, object], + lease_timeout_seconds: float | None, + exclusive_file_lock_fn: ExclusiveFileLockFn | None = None, +) -> str | None: + """Acquire one legacy writer guard immediately before its provider.""" + + lock_fn = exclusive_file_lock_fn or exclusive_file_lock + try: + target = legacy_post_writeback_lock_target(runtime_root, raw_plan) + except (TypeError, ValueError): + return "lock_failed" + plan_guard = ExitStack() + try: + plan_guard.enter_context( + lock_fn( + target, + operation="post_writeback_hook_dispatch", + timeout_seconds=lease_timeout_seconds, + ) + ) + except LockAcquireTimeoutError: + plan_guard.close() + return "lock_unavailable" + except OSError: + plan_guard.close() + return "lock_failed" + + expected_snapshot = raw_plan.get("receipt_snapshot") + if not isinstance( + expected_snapshot, str + ) or not POST_WRITEBACK_RECEIPT_SNAPSHOT_RE.fullmatch(expected_snapshot): + plan_guard.close() + return "lock_failed" + try: + current_snapshot = post_writeback_receipt_snapshot(target) + except OSError: + plan_guard.close() + return "lock_failed" + if current_snapshot != expected_snapshot: + plan_guard.close() + return "receipt_changed" + + guards.callback(plan_guard.close) + return None + + +def post_writeback_finalize_params( + base_request: Mapping[str, object], + *, + transaction_id: object, + outcomes: Sequence[Mapping[str, object]], +) -> dict[str, object]: + """Assemble the finalize-phase RPC payload for post-writeback hooks.""" + + return { + **base_request, + "phase": "finalize", + "transaction_id": transaction_id, + "provider_outcomes": [dict(outcome) for outcome in outcomes], + } + + +def post_writeback_transport_rejected_outcome( + outcome: Mapping[str, object], +) -> dict[str, object]: + """Strip an oversized or unserializable result down to a rejected stub.""" + + return { + "dispatch_id": outcome.get("dispatch_id"), + "hook_id": outcome.get("hook_id"), + "capability_id": outcome.get("capability_id"), + "attempt_count": outcome.get("attempt_count"), + "status": "contract_rejected", + "result": None, + } + + +def bounded_post_writeback_transport_outcomes( + base_request: Mapping[str, object], + *, + transaction_id: object, + outcomes: Sequence[Mapping[str, object]], +) -> list[dict[str, object]]: + """Admit the smallest JSON-safe results into the real Python wire budget.""" + + bounded: list[dict[str, object]] = [] + candidates: list[tuple[int, int, dict[str, object]]] = [] + for index, raw_outcome in enumerate(outcomes): + outcome = dict(raw_outcome) + if outcome.get("status") != "returned": + bounded.append(outcome) + continue + rejected = post_writeback_transport_rejected_outcome(outcome) + bounded.append(rejected) + try: + rejected_size = len(json.dumps(rejected, separators=(",", ":")).encode()) + outcome_size = len(json.dumps(outcome, separators=(",", ":")).encode()) + except (OverflowError, RecursionError, TypeError, ValueError): + continue + candidates.append((outcome_size - rejected_size, index, outcome)) + + baseline = post_writeback_finalize_params( + base_request, + transaction_id=transaction_id, + outcomes=bounded, + ) + admitted_size = len(json.dumps(baseline, separators=(",", ":")).encode()) + if admitted_size > POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES: + raise ValueError("post-writeback finalize transport baseline is oversized") + + for delta, index, outcome in sorted(candidates): + if admitted_size + delta > POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES: + continue + bounded[index] = outcome + admitted_size += delta + + finalized = post_writeback_finalize_params( + base_request, + transaction_id=transaction_id, + outcomes=bounded, + ) + if ( + len(json.dumps(finalized, separators=(",", ":")).encode()) + > POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES + ): + raise ValueError("post-writeback finalize transport admission drifted") + return bounded + + +def decode_post_writeback_preflight( + value: object, +) -> tuple[dict[str, object] | None, list[Mapping[str, object]]]: + """Decode either a terminal dispatch or a provider execution plan.""" + + if not isinstance(value, Mapping): + raise ValueError("post-writeback transaction preflight is invalid") + terminal_dispatch = value.get("dispatch") + if isinstance(terminal_dispatch, Mapping): + return ( + as_string_dict( + terminal_dispatch, + error_message="post-writeback terminal dispatch is invalid", + ), + [], + ) + provider_plan = value.get("provider_plan") + if not isinstance(provider_plan, list): + raise ValueError("post-writeback provider plan is invalid") + typed_provider_plan: list[Mapping[str, object]] = [] + for raw_plan in provider_plan: + if not isinstance(raw_plan, Mapping): + raise ValueError("post-writeback provider step is invalid") + typed_provider_plan.append(raw_plan) + return None, typed_provider_plan + + +def post_writeback_provider_outcome( + raw_plan: Mapping[str, object], + *, + registration: PostWritebackHookRegistration | None, + unavailable_status: str | None, +) -> tuple[dict[str, object], bool]: + """Invoke one effect-free provider and isolate its JSON transport boundary.""" + + admitted_input = raw_plan.get("hook_input") + if registration is None or not isinstance(admitted_input, Mapping): + raise ValueError("post-writeback provider step is unbound") + invoked = unavailable_status is None + if unavailable_status is not None: + result: object = None + status = unavailable_status + else: + try: + produced = dict( + registration.producer( + as_string_dict( + admitted_input, + error_message="post-writeback hook input is invalid", + ) + ) + ) + except Exception: # noqa: BLE001 - provider failures isolate. + result = None + status = "producer_failed" + else: + try: + encoded_result = json.dumps( + produced, + allow_nan=False, + ensure_ascii=False, + separators=(",", ":"), + ).encode("utf-8") + result = json.loads(encoded_result) + except (OverflowError, RecursionError, TypeError, ValueError): + result = None + status = "contract_rejected" + else: + status = "returned" + return ( + { + "dispatch_id": raw_plan.get("dispatch_id"), + "hook_id": raw_plan.get("hook_id"), + "capability_id": raw_plan.get("capability_id"), + "attempt_count": raw_plan.get("attempt_count"), + "status": status, + "result": result, + }, + invoked, + ) + + +def post_writeback_contract_placeholder( + registration: PostWritebackHookRegistration, +) -> dict[str, object]: + """Build a bounded placeholder contract for oversized/unserializable hooks.""" + + hook_id = registration.hook_id + capability_id = registration.capability_id + return { + "hook_id": ( + hook_id if isinstance(hook_id, str) and len(hook_id) <= 200 else "" + ), + "capability_id": ( + capability_id + if isinstance(capability_id, str) and len(capability_id) <= 200 + else "" + ), + } + + +def bounded_post_writeback_transport_contracts( + registrations: Sequence[PostWritebackHookRegistration], + *, + shared_request: Mapping[str, object], +) -> list[dict[str, object]]: + """Keep one malformed registration from making the shared JSON wire unusable.""" + + bounded: list[dict[str, object]] = [] + candidates: list[tuple[int, int, dict[str, object]]] = [] + for index, registration in enumerate(registrations): + placeholder = post_writeback_contract_placeholder(registration) + bounded.append(placeholder) + try: + encoded = json.dumps( + registration.contract(), + allow_nan=False, + separators=(",", ":"), + ).encode() + contract = json.loads(encoded) + if not isinstance(contract, dict): + continue + placeholder_size = len( + json.dumps(placeholder, separators=(",", ":")).encode() + ) + except ( + AttributeError, + OverflowError, + RecursionError, + TypeError, + ValueError, + ): + continue + candidates.append((len(encoded) - placeholder_size, index, contract)) + + request = {**shared_request, "registrations": bounded} + admitted_size = len(json.dumps(request, separators=(",", ":")).encode()) + if admitted_size > POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES: + raise ValueError("post-writeback preflight transport baseline is oversized") + for delta, index, contract in sorted(candidates): + if admitted_size + delta > POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES: + continue + bounded[index] = contract + admitted_size += delta + return bounded + + +def _build_post_writeback_base_request( + ordered_registrations: Sequence[PostWritebackHookRegistration], + *, + source: Mapping[str, object] | None, + hook_input: Mapping[str, object] | None, + runtime_root: Path | None, +) -> tuple[dict[str, object], dict[tuple[str, str], PostWritebackHookRegistration]]: + source_packet = dict(source) if source is not None else None + legacy_hook_input = dict(hook_input) if hook_input is not None else None + runtime_root_text = str(runtime_root.resolve()) if runtime_root else None + shared_request: dict[str, object] = { + "schema_version": "loopx_post_writeback_hook_transaction_request_v0", + "runtime_root": runtime_root_text, + "source": source_packet, + "hook_input": legacy_hook_input, + } + contracts = bounded_post_writeback_transport_contracts( + ordered_registrations, + shared_request={ + **shared_request, + "phase": "preflight", + "transaction_id": None, + "provider_outcomes": [], + }, + ) + providers: dict[tuple[str, str], PostWritebackHookRegistration] = {} + for registration in ordered_registrations: + if not isinstance(registration.hook_id, str) or not isinstance( + registration.capability_id, str + ): + continue + providers.setdefault((registration.hook_id, registration.capability_id), registration) + return {**shared_request, "registrations": contracts}, providers + + +def _run_post_writeback_plan_steps( + typed_provider_plan: Sequence[Mapping[str, object]], + *, + legacy_writer_guards: ExitStack, + providers: Mapping[tuple[str, str], PostWritebackHookRegistration], + runtime_root: Path | None, + lease_timeout_seconds: float | None, + exclusive_file_lock_fn: ExclusiveFileLockFn | None, + monotonic_fn: MonotonicFn, +) -> tuple[list[dict[str, object]], int]: + compatibility_timeout = ( + LOCK_POLICIES[LockAcquisitionPolicy.MUTATION].timeout_seconds + if lease_timeout_seconds is None + else max(0.0, lease_timeout_seconds) + ) + compatibility_deadline = monotonic_fn() + compatibility_timeout + invoked_count = 0 + outcomes: list[dict[str, object]] = [] + for raw_plan in typed_provider_plan: + key = ( + str(raw_plan.get("hook_id") or ""), + str(raw_plan.get("capability_id") or ""), + ) + provider_registration = providers.get(key) + unavailable_status = ( + enter_legacy_post_writeback_guard( + legacy_writer_guards, + runtime_root=runtime_root, + raw_plan=raw_plan, + lease_timeout_seconds=max( + 0.0, compatibility_deadline - monotonic_fn() + ), + exclusive_file_lock_fn=exclusive_file_lock_fn, + ) + if runtime_root is not None + else None + ) + outcome, invoked = post_writeback_provider_outcome( + raw_plan, + registration=provider_registration, + unavailable_status=unavailable_status, + ) + invoked_count += int(invoked) + outcomes.append(outcome) + return outcomes, invoked_count + + +def dispatch_post_writeback_hooks( + registrations: Sequence[PostWritebackHookRegistration] | None, + *, + source: Mapping[str, object] | None = None, + hook_input: Mapping[str, object] | None = None, + runtime_root: Path | None = None, + lease_timeout_seconds: float | None = None, + effect_runtime_result_fn: EffectRuntimeResultFn | None = None, + exclusive_file_lock_fn: ExclusiveFileLockFn | None = None, + monotonic_fn: MonotonicFn | None = None, +) -> dict[str, object]: + """Run one TS-owned hook transaction around effect-free Python providers. + + The Python adapter exits when providers and the committed-writeback caller + run in TypeScript. Its legacy-writer guard exits earlier only when TypeScript + owns an execution claim spanning provider invocation and receipt commit. + """ + + ordered_registrations = tuple(registrations or ()) + if not ordered_registrations or (source is None) == (hook_input is None): + return post_writeback_failure_dispatch( + ordered_registrations, + error_code="registration_or_input_rejected", + ) + invoke = effect_runtime_result_fn or effect_runtime_result + clock = monotonic_fn or time.monotonic + invoked_count = 0 + runtime_phase = "preflight" + with capability_hook_request_scope(): + try: + base_request, providers = _build_post_writeback_base_request( + ordered_registrations, + source=source, + hook_input=hook_input, + runtime_root=runtime_root, + ) + preflight_request: dict[str, object] = { + **base_request, + "phase": "preflight", + "transaction_id": None, + "provider_outcomes": [], + } + preflight = invoke( + "capability_hook.post_writeback.transaction", + preflight_request, + ) + if not isinstance(preflight, Mapping): + raise ValueError("post-writeback transaction preflight is invalid") + terminal_dispatch, typed_provider_plan = decode_post_writeback_preflight( + preflight + ) + if terminal_dispatch is not None: + return terminal_dispatch + transaction_id = preflight.get("transaction_id") + if not isinstance(transaction_id, str): + raise ValueError("post-writeback transaction_id is invalid") + + sizing_outcomes = [ + { + "dispatch_id": raw_plan.get("dispatch_id"), + "hook_id": raw_plan.get("hook_id"), + "capability_id": raw_plan.get("capability_id"), + "attempt_count": raw_plan.get("attempt_count"), + "status": "contract_rejected", + "result": None, + } + for raw_plan in typed_provider_plan + ] + bounded_post_writeback_transport_outcomes( + base_request, + transaction_id=transaction_id, + outcomes=sizing_outcomes, + ) + + runtime_phase = "provider" + with ExitStack() as legacy_writer_guards: + outcomes, invoked_count = _run_post_writeback_plan_steps( + typed_provider_plan, + legacy_writer_guards=legacy_writer_guards, + providers=providers, + runtime_root=runtime_root, + lease_timeout_seconds=lease_timeout_seconds, + exclusive_file_lock_fn=exclusive_file_lock_fn, + monotonic_fn=clock, + ) + bounded_outcomes = bounded_post_writeback_transport_outcomes( + base_request, + transaction_id=transaction_id, + outcomes=outcomes, + ) + runtime_phase = "finalize" + finalized = invoke( + "capability_hook.post_writeback.transaction", + post_writeback_finalize_params( + base_request, + transaction_id=transaction_id, + outcomes=bounded_outcomes, + ), + ) + if not isinstance(finalized, Mapping) or not isinstance( + finalized.get("dispatch"), Mapping + ): + raise ValueError("post-writeback transaction result is invalid") + return as_string_dict( + finalized["dispatch"], + error_message="post-writeback transaction result is invalid", + ) + except ( + EffectRuntimeRejected, + OSError, + RuntimeError, + TypeError, + ValueError, + ) as exc: + if ( + isinstance(exc, EffectRuntimeRejected) + and exc.diagnostic_code == POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE + ): + # The TypeScript decoder owns source legality. Its typed + # input-construction rejection crosses this boundary as the + # legacy composition ValueError, so callers keep reporting one + # source_projection_failed failure instead of per-hook + # runtime_result_invalid noise; every other rejection stays a + # runtime failure without string matching or field copies. + raise PostWritebackSourceRejected( + "post-writeback hooks require committed source identity fields" + ) from exc + return post_writeback_failure_dispatch( + ordered_registrations, + error_code="runtime_result_invalid", + invoked_count=invoked_count, + runtime_failure=post_writeback_runtime_failure( + exc, + phase=runtime_phase, + ), + ) diff --git a/loopx/control_plane/hook_runtime/request_scope.py b/loopx/control_plane/hook_runtime/request_scope.py new file mode 100644 index 0000000000..47a0ee1e5c --- /dev/null +++ b/loopx/control_plane/hook_runtime/request_scope.py @@ -0,0 +1,292 @@ +from __future__ import annotations + +import copy +import inspect +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass, field +from pathlib import Path +from typing import Protocol, TypeVar, cast, overload + + +_DefaultT = TypeVar("_DefaultT") + + +class _ObservedSnapshotDict(dict[Path, bytes | None]): + """`dict` view that stages snapshot writes and tracks accessed keys.""" + + def __init__(self, initial: dict[Path, bytes | None]) -> None: + super().__init__(initial) + self.observed_keys: set[Path] = set() + + def _mark(self, key: object) -> None: + if isinstance(key, Path): + self.observed_keys.add(key) + + def __contains__(self, key: object) -> bool: + self._mark(key) + return super().__contains__(key) + + def __getitem__(self, key: Path) -> bytes | None: + self._mark(key) + return super().__getitem__(key) + + def __setitem__(self, key: Path, value: bytes | None) -> None: + self._mark(key) + super().__setitem__(key, value) + + @overload + def get(self, key: Path, default: None = None, /) -> bytes | None: ... + + @overload + def get(self, key: Path, default: _DefaultT, /) -> bytes | None | _DefaultT: ... + + def get( + self, key: Path, default: _DefaultT | None = None, / + ) -> bytes | None | _DefaultT: + self._mark(key) + if super().__contains__(key): + return super().__getitem__(key) + return default + + def setdefault( + self, key: Path, default: bytes | None = None, / + ) -> bytes | None: + self._mark(key) + if super().__contains__(key): + return super().__getitem__(key) + super().__setitem__(key, default) + return default + + +class RegistryLoader(Protocol): + """Typed registry loader interface for request-scoped hook evaluation.""" + + def __call__(self, path: Path) -> dict[str, object]: ... + + +class SnapshotRegistryLoader(Protocol): + """Registry loader accepting an optional `source_snapshots` dict.""" + + def __call__( + self, + path: Path, + *, + source_snapshots: dict[Path, bytes | None] | None = None, + ) -> dict[str, object]: ... + + +def _safe_absolute(path: Path) -> Path | None: + try: + return path.expanduser().absolute() + except (OSError, RuntimeError): + return None + + +def _safe_resolve(path: Path) -> Path | None: + try: + return path.expanduser().resolve() + except (OSError, RuntimeError): + return None + + +def _supports_source_snapshots(loader: RegistryLoader) -> bool: + try: + return "source_snapshots" in inspect.signature(loader).parameters + except (TypeError, ValueError): + return False + + +def _invoke_registry_loader( + loader: RegistryLoader, + path: Path, + *, + source_snapshots: dict[Path, bytes | None], +) -> dict[str, object]: + if _supports_source_snapshots(loader): + snapshot_loader = cast(SnapshotRegistryLoader, loader) + return dict(snapshot_loader(path, source_snapshots=source_snapshots)) + return dict(loader(path)) + + +def _extract_goals_by_id( + payload: dict[str, object], +) -> dict[str, dict[str, object]]: + goals = payload.get("goals") + if not isinstance(goals, list): + return {} + indexed: dict[str, dict[str, object]] = {} + for goal in goals: + if isinstance(goal, dict) and goal.get("id"): + goal_id = str(goal["id"]) + if goal_id not in indexed: + indexed[goal_id] = copy.deepcopy(goal) + return indexed + + +@dataclass(slots=True) +class CapabilityHookRequestScope: + """Single-request registry snapshot cache bound to one hook dispatch pass.""" + + registry_snapshots: dict[Path, bytes | None] = field(default_factory=dict) + _decoded_registries: dict[tuple[Path, str], dict[str, object]] = field( + default_factory=dict + ) + _goals_by_path: dict[tuple[Path, str], dict[str, dict[str, object]]] = field( + default_factory=dict + ) + _alias_to_targets: dict[Path, set[Path]] = field(default_factory=dict) + + def _record_targets(self, route: Path, *candidates: Path | None) -> None: + targets = self._alias_to_targets.setdefault(route, set()) + for candidate in candidates: + if candidate is not None: + targets.add(candidate) + + def load_registry( + self, + path: Path, + *, + loader: RegistryLoader, + ) -> dict[str, object]: + """Return a fresh copy of `path` using this request's cached snapshot.""" + + expanded = path.expanduser() + route = _safe_absolute(expanded) or expanded + cache_key = (route, expanded.name) + if cache_key in self._decoded_registries: + return copy.deepcopy(self._decoded_registries[cache_key]) + resolved_before = _safe_resolve(expanded) + before_keys = set(self.registry_snapshots) + observed = _ObservedSnapshotDict(self.registry_snapshots) + payload = _invoke_registry_loader( + loader, + path, + source_snapshots=observed, + ) + if len(observed) != len(self.registry_snapshots) or observed != self.registry_snapshots: + self.registry_snapshots.clear() + self.registry_snapshots.update(observed) + resolved_after = _safe_resolve(expanded) + touched_keys = (observed.observed_keys | (set(observed) - before_keys)) - {route} + self._record_targets(route, resolved_before, resolved_after, *touched_keys) + self._decoded_registries[cache_key] = copy.deepcopy(payload) + self._goals_by_path[cache_key] = _extract_goals_by_id(payload) + return payload + + def load_goal( + self, + path: Path, + goal_id: str, + *, + loader: RegistryLoader, + ) -> dict[str, object] | None: + """Return an isolated Goal copy from this request's cached snapshot.""" + + expanded = path.expanduser() + route = _safe_absolute(expanded) or expanded + cache_key = (route, expanded.name) + if cache_key not in self._decoded_registries: + if route not in self.registry_snapshots and not expanded.exists(): + self.registry_snapshots.setdefault(route, None) + self._record_targets(route, _safe_resolve(expanded)) + self._decoded_registries[cache_key] = {} + self._goals_by_path[cache_key] = {} + return None + self.load_registry(path, loader=loader) + goal = self._goals_by_path.get(cache_key, {}).get(str(goal_id)) + return copy.deepcopy(goal) if goal is not None else None + + def invalidate(self, path: Path) -> None: + """Drop cached state and all alias snapshots resolving to `path`.""" + + expanded = path.expanduser() + route = _safe_absolute(expanded) or expanded + resolved = _safe_resolve(expanded) + targets = {route} + if resolved is not None: + targets.add(resolved) + known_targets = self._alias_to_targets.get(route) + if known_targets is not None: + targets.update(known_targets) + matching_aliases = { + alias + for alias, mapped_targets in self._alias_to_targets.items() + if alias in targets or bool(mapped_targets & targets) + } + targets.update(matching_aliases) + for snap_key in list(self.registry_snapshots): + if snap_key in targets: + continue + snap_resolved = _safe_resolve(snap_key) + snap_absolute = _safe_absolute(snap_key) + if (snap_resolved is not None and snap_resolved in targets) or ( + snap_absolute is not None and snap_absolute in targets + ): + targets.add(snap_key) + for key in targets: + self.registry_snapshots.pop(key, None) + self._alias_to_targets.pop(key, None) + for cache_key in list(self._decoded_registries): + if cache_key[0] in targets: + self._decoded_registries.pop(cache_key, None) + for cache_key in list(self._goals_by_path): + if cache_key[0] in targets: + self._goals_by_path.pop(cache_key, None) + + +_ACTIVE_HOOK_REQUEST_SCOPE: ContextVar[CapabilityHookRequestScope | None] = ContextVar( + "loopx_capability_hook_request_scope", + default=None, +) + + +def current_hook_request_scope() -> CapabilityHookRequestScope | None: + """Return the active hook request scope, or `None` outside hook dispatch.""" + + return _ACTIVE_HOOK_REQUEST_SCOPE.get() + + +def current_hook_registry_snapshots() -> dict[Path, bytes | None] | None: + """Return the active request's `source_snapshots` dict, if any.""" + + scope = _ACTIVE_HOOK_REQUEST_SCOPE.get() + return scope.registry_snapshots if scope is not None else None + + +def invalidate_hook_registry_snapshot(path: Path) -> None: + """Invalidate `path` inside the currently active hook request scope, if any.""" + + scope = _ACTIVE_HOOK_REQUEST_SCOPE.get() + if scope is not None: + scope.invalidate(path) + + +def load_scoped_registry( + path: Path, + *, + loader: RegistryLoader, +) -> dict[str, object]: + """Load `path` via the active hook request scope when one is entered.""" + + scope = _ACTIVE_HOOK_REQUEST_SCOPE.get() + if scope is None: + return dict(loader(path)) + return scope.load_registry(path, loader=loader) + + +@contextmanager +def capability_hook_request_scope() -> Iterator[CapabilityHookRequestScope]: + """Scope registry snapshot reuse to a single hook dispatch pass.""" + + existing = _ACTIVE_HOOK_REQUEST_SCOPE.get() + if existing is not None: + yield existing + return + scope = CapabilityHookRequestScope() + token = _ACTIVE_HOOK_REQUEST_SCOPE.set(scope) + try: + yield scope + finally: + _ACTIVE_HOOK_REQUEST_SCOPE.reset(token) diff --git a/loopx/control_plane/hook_runtime/turn_context.py b/loopx/control_plane/hook_runtime/turn_context.py new file mode 100644 index 0000000000..3ed4e96bf3 --- /dev/null +++ b/loopx/control_plane/hook_runtime/turn_context.py @@ -0,0 +1,253 @@ +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence + +from ..effect_runtime import effect_runtime_projection_result, effect_runtime_result +from .contracts import ( + EffectRuntimeProjectionFn, + EffectRuntimeResultFn, + TurnContextHookRegistration, + TurnContextSourceFn, + as_string_dict, +) +from .request_scope import capability_hook_request_scope + + +def turn_context_source(payload: Mapping[str, object]) -> Mapping[str, object]: + """Use the host envelope or the native quota identity, without new authority.""" + + if "work_contract" in payload: + from ..quota.turn_envelope import complete_turn_host_source, turn_plan_host_source + + source = complete_turn_host_source( + turn_plan_host_source(payload), + operation="plan_work", + ) + assert source is not None + return source + envelope = payload.get("turn_envelope") + if isinstance(envelope, Mapping): + return envelope + if "schema_version" in payload or "contract_binding" in payload: + from ..quota.turn_envelope import quota_capability_automation_source + + # A declared native contract must pass the same complete-source owner + # as participation. Never reinterpret a damaged version as raw quota. + source = quota_capability_automation_source(payload) + if isinstance(payload.get("heartbeat_receipt"), Mapping): + return {**payload, "agent_id": source.get("agent_id")} + return {"goal_id": source.get("goal_id"), "agent_id": source.get("agent_id")} + agent_id = payload.get("agent_id") + identity = payload.get("agent_identity") + if isinstance(identity, Mapping): + scoped_agent = identity.get("agent_id") + if agent_id and scoped_agent and agent_id != scoped_agent: + raise ValueError("context source has conflicting Agent identities") + agent_id = agent_id or scoped_agent + if isinstance(payload.get("heartbeat_receipt"), Mapping): + # Keep the native source for the typed quota signature owner. Identity + # alone cannot invalidate context when the admitted authority changes; + # Python does not decode the quota boundary here. + return {**payload, "agent_id": agent_id} + return {"goal_id": payload.get("goal_id"), "agent_id": agent_id} + + +def turn_context_binding_source( + payload: Mapping[str, object], + *, + from_journal: bool = False, + turn_context_source_fn: TurnContextSourceFn | None = None, +) -> Mapping[str, object]: + """Resolve the source record used to bind and project turn context.""" + + from ..quota.turn_envelope import ( + COMPLETE_TURN_PLAN_SCHEMA_VERSION, + complete_turn_host_source, + turn_plan_host_source, + ) + + if payload.get("schema_version") == COMPLETE_TURN_PLAN_SCHEMA_VERSION: + source = complete_turn_host_source( + turn_plan_host_source(payload), + operation="host_context_binding", + recorded_capability_result=from_journal, + ) + assert source is not None + return source + resolver = turn_context_source_fn or turn_context_source + return resolver(payload) + + +def dispatch_turn_context_hooks( + payload: dict[str, object], + registrations: Sequence[TurnContextHookRegistration], + *, + effect_runtime_result_fn: EffectRuntimeResultFn | None = None, + turn_context_source_fn: TurnContextSourceFn | None = None, +) -> None: + """Invoke and validate registered turn-context hooks without gating work.""" + + invoke = effect_runtime_result_fn or effect_runtime_result + contributions: list[dict[str, object]] = [] + failures: list[dict[str, str]] = [] + seen_hooks: set[str] = set() + seen_slots: set[str] = set() + with capability_hook_request_scope(): + for registration in registrations: + try: + if registration.hook_id in seen_hooks or seen_slots.intersection( + registration.readback_slots + ): + raise ValueError("duplicate context registration") + seen_hooks.add(registration.hook_id) + seen_slots.update(registration.readback_slots) + invoke( + "capability_hook.turn_context.validate_registration", + {"registration": registration.contract()}, + ) + if any(key in payload for key in registration.readback_slots): + raise ValueError("context readback slot already contributed") + result = registration.producer() + readback_only = ( + result.get("context_fields") == {} + and result.get("instructions") == [] + and result.get("result_fields") == {} + ) + if readback_only: + binding: dict[str, object] = {"readback_only": True} + else: + source = turn_context_binding_source( + payload, + turn_context_source_fn=turn_context_source_fn, + ) + binding = {"source": source} + if isinstance(source.get("heartbeat_receipt"), Mapping): + from ..quota.turn_envelope import pack_turn_source + + transport = pack_turn_source(source) + if transport is not None: + binding = {"source_transport": transport} + raw_contribution = invoke( + "capability_hook.turn_context.validate", + { + "registration": registration.contract(), + "result": result, + **binding, + }, + ) + contribution = as_string_dict( + raw_contribution, + error_message="turn context validation returned invalid result", + ) + readback = as_string_dict( + contribution.pop("readback"), + error_message="turn context validation returned invalid readback", + ) + payload.update(readback) + if ( + contribution.get("context_fields") + or contribution.get("instructions") + or contribution.get("result_fields") + ): + contributions.append(contribution) + except Exception: # Optional context failures never gate business work. + failures.append( + { + "hook_id": registration.hook_id, + "error_code": "context_hook_failed", + } + ) + if contributions: + payload["turn_context_contributions"] = contributions + if failures: + payload["turn_context_hook_failures"] = failures + + +def project_turn_context( + payload: Mapping[str, object], + *, + from_journal: bool = False, + effect_runtime_projection_result_fn: EffectRuntimeProjectionFn | None = None, + turn_context_source_fn: TurnContextSourceFn | None = None, +) -> dict[str, object]: + """Project contributed turn context via the TS projection owner.""" + + contributions = payload.get("turn_context_contributions") + if not isinstance(contributions, list) or not contributions: + return {} + readback: dict[str, object] = {} + for item in contributions: + if not isinstance(item, Mapping): + continue + slots = item.get("readback_slots") + if isinstance(slots, (list, tuple)): + readback.update( + {key: payload.get(key) for key in slots if isinstance(key, str)} + ) + project_invoke = ( + effect_runtime_projection_result_fn or effect_runtime_projection_result + ) + try: + projected = project_invoke( + "capability_hook.turn_context.project", + { + "contributions": contributions, + "source": turn_context_binding_source( + payload, + from_journal=from_journal, + turn_context_source_fn=turn_context_source_fn, + ), + "readback": readback, + }, + ) + except Exception: # Optional context transport cannot gate the underlying work. + return {} + if not isinstance(projected, Mapping): + return {} + return {str(key): value for key, value in projected.items()} + + +def host_context_projection(request: Mapping[str, object]) -> dict[str, object]: + """Extract capability host context fields, instructions, and result schema.""" + + raw_fields = request.get("capability_context_fields") + fields: Iterable[object] = ( + raw_fields + if isinstance(raw_fields, Iterable) + and not isinstance(raw_fields, (str, bytes, Mapping)) + else () + ) + projection: dict[str, object] = { + key: request[key] for key in fields if isinstance(key, str) and key in request + } + raw_instructions = request.get("capability_instructions") + raw_result_fields = request.get("capability_result_fields") + if projection or raw_instructions or raw_result_fields: + instructions_list = ( + list(raw_instructions) + if isinstance(raw_instructions, Iterable) + and not isinstance(raw_instructions, (str, bytes, Mapping)) + else [] + ) + projection["capability_instructions"] = instructions_list + projection["capability_result_fields"] = ( + dict(raw_result_fields) + if isinstance(raw_result_fields, Mapping) + else {} + ) + return projection + + +def capability_result_fields( + request: Mapping[str, object] | None, +) -> dict[str, object]: + """Return declared capability result fields from a host request packet.""" + + value = ( + request.get("capability_result_fields") + if isinstance(request, Mapping) + else None + ) + if not isinstance(value, Mapping): + return {} + return {str(key): item for key, item in value.items()} diff --git a/loopx/control_plane/projects/registry_codec.py b/loopx/control_plane/projects/registry_codec.py index 3070c3261c..379e789d45 100644 --- a/loopx/control_plane/projects/registry_codec.py +++ b/loopx/control_plane/projects/registry_codec.py @@ -305,6 +305,12 @@ def _encode_document( ).encode("utf-8") +def _invalidate_registry_snapshot(path: Path) -> None: + from ..hook_runtime.request_scope import invalidate_hook_registry_snapshot + + invalidate_hook_registry_snapshot(path) + + def _atomic_write_bytes(path: Path, payload: bytes, *, mode: int | None) -> None: path.parent.mkdir(parents=True, exist_ok=True) descriptor, temporary = tempfile.mkstemp( @@ -321,6 +327,7 @@ def _atomic_write_bytes(path: Path, payload: bytes, *, mode: int | None) -> None if mode is not None: os.chmod(temporary_path, mode) os.replace(temporary_path, path) + _invalidate_registry_snapshot(path) finally: temporary_path.unlink(missing_ok=True) @@ -455,9 +462,11 @@ def remove(self) -> bool: if self._finished: raise RuntimeError("project registry transaction is already finished") if not self._path.exists(): + _invalidate_registry_snapshot(self._path) self._finished = True return False self._path.unlink() + _invalidate_registry_snapshot(self._path) if self._path.exists(): raise ProjectRegistryMutationError( "project registry removal readback failed" @@ -478,6 +487,7 @@ def restore(self) -> None: ) else: self._path.unlink(missing_ok=True) + _invalidate_registry_snapshot(self._path) if self._path.exists(): raise ProjectRegistryRestoreError( "new project registry could not be removed during restore" diff --git a/loopx/control_plane/runtime/goal_project_route.py b/loopx/control_plane/runtime/goal_project_route.py index c61858e241..f1a4ef2dd2 100644 --- a/loopx/control_plane/runtime/goal_project_route.py +++ b/loopx/control_plane/runtime/goal_project_route.py @@ -3,6 +3,7 @@ from pathlib import Path from typing import Any +from ..hook_runtime.request_scope import load_scoped_registry from ...history import load_registry from ...paths import registry_project_root from ...registry import registry_goals @@ -30,7 +31,7 @@ def resolve_goal_project_route( source_registry = Path(str(route["source_registry"])).expanduser().resolve() def load_goal(path: Path) -> tuple[dict[str, Any], dict[str, Any] | None]: - payload = load_registry(path) + payload = load_scoped_registry(path, loader=load_registry) matched = next( ( item diff --git a/loopx/control_plane/runtime/runtime_projection_route.py b/loopx/control_plane/runtime/runtime_projection_route.py index 27de22d283..02bca5b3f5 100644 --- a/loopx/control_plane/runtime/runtime_projection_route.py +++ b/loopx/control_plane/runtime/runtime_projection_route.py @@ -13,6 +13,10 @@ goal_activation_state, normalize_goal_activation_state, ) +from ..hook_runtime.request_scope import ( + current_hook_request_scope, + load_scoped_registry, +) from ..projects.registry_codec import load_registry from ... import paths from ...paths import global_registry_path, resolve_runtime_root @@ -109,8 +113,20 @@ def resolve_goal_source_runtime_route( """ invoked_registry = registry_path.expanduser().resolve() - registry_payload = registry if registry is not None else load_registry( - invoked_registry, source_snapshots=source_snapshots, + scope = current_hook_request_scope() if source_snapshots is None else None + active_snapshots = ( + source_snapshots + if source_snapshots is not None + else (scope.registry_snapshots if scope is not None else None) + ) + registry_payload = ( + registry + if registry is not None + else ( + load_scoped_registry(invoked_registry, loader=load_registry) + if scope is not None + else load_registry(invoked_registry, source_snapshots=active_snapshots) + ) ) if runtime_root_override: runtime_root = Path(runtime_root_override).expanduser().resolve() @@ -176,7 +192,11 @@ def resolve_goal_source_runtime_route( f"goal {goal_id!r} source_registry is missing; refusing to use the shared runtime as source" ) try: - source_payload = load_registry(source_registry, source_snapshots=source_snapshots) + source_payload = ( + load_scoped_registry(source_registry, loader=load_registry) + if scope is not None + else load_registry(source_registry, source_snapshots=active_snapshots) + ) except (OSError, ValueError, json.JSONDecodeError) as exc: raise ValueError( f"goal {goal_id!r} source_registry is unreadable; refusing to use the shared runtime as source" diff --git a/loopx/control_plane/todos/list_readback.py b/loopx/control_plane/todos/list_readback.py index ef24927a9c..3aa1a5226b 100644 --- a/loopx/control_plane/todos/list_readback.py +++ b/loopx/control_plane/todos/list_readback.py @@ -8,6 +8,10 @@ from pathlib import Path from typing import Any, Literal +from ..hook_runtime.request_scope import ( + current_hook_registry_snapshots, + load_scoped_registry, +) from ..projects.registry_codec import load_registry from ..runtime.runtime_projection_route import resolve_goal_source_runtime_route from ..goals.state_resolution import resolve_goal_state @@ -56,8 +60,15 @@ def list_goal_todos( raise ValueError("agent_id must be a public-safe agent token such as codex-main-control") if limit is not None and limit < 1: raise ValueError("todo list --limit must be at least 1") - source_snapshots: dict[Path, bytes | None] = {} - registry = load_registry(registry_path, source_snapshots=source_snapshots) + scoped_snapshots = current_hook_registry_snapshots() + source_snapshots: dict[Path, bytes | None] | None = ( + None if scoped_snapshots is not None else {} + ) + registry = ( + load_scoped_registry(registry_path, loader=load_registry) + if scoped_snapshots is not None + else load_registry(registry_path, source_snapshots=source_snapshots) + ) route = resolve_goal_source_runtime_route( registry_path=registry_path, goal_id=goal_id, runtime_root_override=runtime_root_arg, registry=registry, @@ -65,7 +76,11 @@ def list_goal_todos( ) source_registry = Path(route["source_registry"]) if route["routed_to_source_registry"]: - registry = load_registry(source_registry, source_snapshots=source_snapshots) + registry = ( + load_scoped_registry(source_registry, loader=load_registry) + if scoped_snapshots is not None + else load_registry(source_registry, source_snapshots=source_snapshots) + ) goal, resolved_project, resolved_state_file = resolve_goal_state( registry=registry, goal_id=goal_id, diff --git a/loopx/heartbeat_prequota.py b/loopx/heartbeat_prequota.py index 7cabdf9cf2..335de95fec 100644 --- a/loopx/heartbeat_prequota.py +++ b/loopx/heartbeat_prequota.py @@ -7,6 +7,10 @@ reconcile_acknowledged_issue_fix_pr_reviews, ) from .capabilities.turn_start import extend_turn_start_dispatch +from .control_plane.capability_hooks import ( + capability_hook_request_scope, + load_scoped_registry, +) from .control_plane.effect_runtime import ( EffectRuntimeRemoteError, EffectRuntimeStartupError, @@ -83,9 +87,11 @@ def run_heartbeat_pre_quota( agent_id: str, fetch_timeout_seconds: int = 10, ) -> dict[str, Any]: - with effect_runtime_request_scope(): + with effect_runtime_request_scope(), capability_hook_request_scope(): runtime = resolve_runtime_root( - load_registry(registry_path), runtime_root_arg, registry_path=registry_path + load_scoped_registry(registry_path, loader=load_registry), + runtime_root_arg, + registry_path=registry_path, ) shared_todo_cache: dict[str, Any] = { "todos": None, diff --git a/tests/control_plane/test_capability_hook_request_scope.py b/tests/control_plane/test_capability_hook_request_scope.py new file mode 100644 index 0000000000..3fa8883e67 --- /dev/null +++ b/tests/control_plane/test_capability_hook_request_scope.py @@ -0,0 +1,434 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +import loopx.agent_registry as agent_registry +import loopx.control_plane.projects.registry_codec as registry_codec +from loopx.control_plane.capability_hooks import ( + capability_hook_request_scope, + current_hook_request_scope, + load_scoped_registry, +) + + +@pytest.mark.parametrize("use_symlink_alias", [False, True]) +def test_transaction_create_update_remove_invalidates_request_scope( + tmp_path: Path, + use_symlink_alias: bool, +) -> None: + real_reg = tmp_path / "real" / "registry.json" + read_path = tmp_path / "alias" / "registry.json" if use_symlink_alias else real_reg + if use_symlink_alias: + read_path.parent.mkdir() + read_path.symlink_to(real_reg) + + with capability_hook_request_scope(): + with registry_codec.project_registry_transaction( + real_reg, + operation="test_create", + create=lambda: {"goals": [{"id": "g1", "title": "v1"}]}, + ) as tx: + assert tx.commit({"goals": [{"id": "g1", "title": "v1"}]}) is True + + goal_v1 = agent_registry.load_goal_from_registry(read_path, "g1") + assert goal_v1 is not None and goal_v1["title"] == "v1" + if use_symlink_alias: + direct_v1 = agent_registry.load_goal_from_registry(real_reg, "g1") + assert direct_v1 is not None and direct_v1["title"] == "v1" + + with registry_codec.project_registry_transaction( + real_reg, + operation="test_update", + ) as tx: + payload = tx.payload_copy() + payload["goals"][0]["title"] = "v2" + assert tx.commit(payload) is True + + goal_v2 = agent_registry.load_goal_from_registry(read_path, "g1") + assert goal_v2 is not None and goal_v2["title"] == "v2" + if use_symlink_alias: + direct_v2 = agent_registry.load_goal_from_registry(real_reg, "g1") + assert direct_v2 is not None and direct_v2["title"] == "v2" + + with registry_codec.project_registry_transaction( + real_reg, + operation="test_remove", + ) as tx: + assert tx.remove() is True + + assert not real_reg.exists() + assert agent_registry.load_goal_from_registry(read_path, "g1") is None + assert load_scoped_registry(read_path, loader=registry_codec.load_registry) == {} + if use_symlink_alias: + assert agent_registry.load_goal_from_registry(real_reg, "g1") is None + assert load_scoped_registry(real_reg, loader=registry_codec.load_registry) == {} + + assert current_hook_request_scope() is None + assert agent_registry.load_goal_from_registry(read_path, "g1") is None + assert agent_registry.load_goal_from_registry(real_reg, "g1") is None + + +def test_transaction_remove_missing_path_clears_stale_snapshot_before_returning_false( + tmp_path: Path, +) -> None: + missing_reg = tmp_path / "missing" / "registry.json" + missing_reg.parent.mkdir() + + with capability_hook_request_scope() as scope: + scope.registry_snapshots[missing_reg.absolute()] = json.dumps( + {"goals": [{"id": "g-stale", "title": "stale"}]} + ).encode("utf-8") + stale_goal = agent_registry.load_goal_from_registry(missing_reg, "g-stale") + assert stale_goal is not None and stale_goal["title"] == "stale" + + missing_reg.write_text("{}", encoding="utf-8") + with registry_codec.project_registry_transaction( + missing_reg, + operation="test_remove_missing", + ) as tx: + missing_reg.unlink() + assert tx.remove() is False + + assert agent_registry.load_goal_from_registry(missing_reg, "g-stale") is None + assert load_scoped_registry(missing_reg, loader=registry_codec.load_registry) == {} + + +def test_transaction_restore_on_new_registry_invalidates_request_scope( + tmp_path: Path, +) -> None: + new_reg = tmp_path / "new" / "registry.json" + alias = tmp_path / "alias" / "registry.json" + alias.parent.mkdir() + alias.symlink_to(new_reg) + + with capability_hook_request_scope(): + with registry_codec.project_registry_transaction( + new_reg, + operation="test_create_then_restore", + create=lambda: {"goals": [{"id": "g-new", "title": "brand-new"}]}, + ) as tx: + assert tx.commit({"goals": [{"id": "g-new", "title": "brand-new"}]}) is True + created_direct = agent_registry.load_goal_from_registry(new_reg, "g-new") + created_alias = agent_registry.load_goal_from_registry(alias, "g-new") + assert created_direct is not None and created_direct["title"] == "brand-new" + assert created_alias is not None and created_alias["title"] == "brand-new" + + tx.restore() + + assert not new_reg.exists() + assert agent_registry.load_goal_from_registry(new_reg, "g-new") is None + assert agent_registry.load_goal_from_registry(alias, "g-new") is None + assert load_scoped_registry(new_reg, loader=registry_codec.load_registry) == {} + assert load_scoped_registry(alias, loader=registry_codec.load_registry) == {} + + assert current_hook_request_scope() is None + assert agent_registry.load_goal_from_registry(new_reg, "g-new") is None + assert agent_registry.load_goal_from_registry(alias, "g-new") is None + + +def test_warm_canonical_source_tracks_alias_invalidation_without_unrelated_eviction( + tmp_path: Path, +) -> None: + reg_b = tmp_path / "b" / "registry.json" + reg_c = tmp_path / "c" / "registry.json" + alias = tmp_path / "alias" / "registry.json" + for path, gid, title in ( + (reg_b, "g1", "b-v1"), + (reg_c, "g-c", "c-v1"), + ): + path.parent.mkdir() + path.write_text(json.dumps({"goals": [{"id": gid, "title": title}]}), encoding="utf-8") + alias.parent.mkdir() + alias.symlink_to(reg_b) + + with capability_hook_request_scope() as scope: + warm_b = agent_registry.load_goal_from_registry(reg_b, "g1") + assert warm_b is not None and warm_b["title"] == "b-v1" + alias_v1 = agent_registry.load_goal_from_registry(alias, "g1") + assert alias_v1 is not None and alias_v1["title"] == "b-v1" + + # Committing an unrelated registry C must not evict alias -> B. + with registry_codec.project_registry_transaction(reg_c, operation="test_unrelated_c") as tx: + payload_c = tx.payload_copy() + payload_c["goals"][0]["title"] = "c-v2" + assert tx.commit(payload_c) is True + assert alias.absolute() in scope.registry_snapshots + assert (alias.absolute(), "registry.json") in scope._decoded_registries + still_b = agent_registry.load_goal_from_registry(alias, "g1") + assert still_b is not None and still_b["title"] == "b-v1" + + # Committing B after B was already warm must invalidate alias -> B immediately. + with registry_codec.project_registry_transaction(reg_b, operation="test_commit_warm_b") as tx: + payload_b = tx.payload_copy() + payload_b["goals"][0]["title"] = "b-v2" + assert tx.commit(payload_b) is True + assert alias.absolute() not in scope.registry_snapshots + alias_v2 = agent_registry.load_goal_from_registry(alias, "g1") + assert alias_v2 is not None and alias_v2["title"] == "b-v2" + loaded_v2 = load_scoped_registry(alias, loader=registry_codec.load_registry) + goals_v2 = loaded_v2["goals"] + assert isinstance(goals_v2, list) and isinstance(goals_v2[0], dict) + assert goals_v2[0]["title"] == "b-v2" + + outside_v2 = agent_registry.load_goal_from_registry(alias, "g1") + assert outside_v2 is not None and outside_v2["title"] == "b-v2" + + +def test_warm_canonical_source_captures_aba_race_invalidation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + reg_a = tmp_path / "a" / "registry.json" + reg_b = tmp_path / "b" / "registry.json" + alias = tmp_path / "alias" / "registry.json" + for path, title in ((reg_a, "a-v1"), (reg_b, "b-v1")): + path.parent.mkdir() + path.write_text(json.dumps({"goals": [{"id": "g1", "title": title}]}), encoding="utf-8") + alias.parent.mkdir() + alias.symlink_to(reg_a) + + orig_resolve = Path.resolve + alias_resolve_calls = 0 + + def _aba_race_resolve(self: Path, strict: bool = False) -> Path: + nonlocal alias_resolve_calls + target = orig_resolve(self, strict=strict) + if self.parent.name == "alias" and self.name == "registry.json": + alias_resolve_calls += 1 + if alias_resolve_calls == 1: + alias.unlink() + alias.symlink_to(reg_b) + elif alias_resolve_calls == 2: + alias.unlink() + alias.symlink_to(reg_a) + return target + + with capability_hook_request_scope() as scope: + warm_b = agent_registry.load_goal_from_registry(reg_b, "g1") + assert warm_b is not None and warm_b["title"] == "b-v1" + + monkeypatch.setattr(Path, "resolve", _aba_race_resolve) + alias_aba = agent_registry.load_goal_from_registry(alias, "g1") + assert alias_aba is not None and alias_aba["title"] == "b-v1" + monkeypatch.undo() + + reg_a_direct = agent_registry.load_goal_from_registry(reg_a, "g1") + assert reg_a_direct is not None and reg_a_direct["title"] == "a-v1" + + # Committing B must still evict the ABA-hit alias snapshot observed from warm B. + with registry_codec.project_registry_transaction(reg_b, operation="test_commit_b_after_aba") as tx: + payload_b = tx.payload_copy() + payload_b["goals"][0]["title"] = "b-v2" + assert tx.commit(payload_b) is True + assert alias.absolute() not in scope.registry_snapshots + refreshed_alias = agent_registry.load_goal_from_registry(alias, "g1") + assert refreshed_alias is not None and refreshed_alias["title"] == "a-v1" + + +def test_list_goal_todos_scoped_routing_captures_aba_source_invalidation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import loopx.control_plane.runtime.runtime_projection_route as runtime_projection_route + from loopx.control_plane.todos.list_readback import list_goal_todos + from tests.control_plane.canonical_authority_fixture import ( + initialize_canonical_source_fixture, + ) + + root = tmp_path.resolve() + project = root / "project" + runtime_root = root / "runtime" + runtime_root.mkdir() + state_path = project / "ACTIVE_GOAL_STATE.md" + state_path.parent.mkdir(parents=True) + state_path.write_text( + "---\nstatus: active\n---\n\n" + "# Scoped Readback Fixture\n\n" + "## Agent Todo\n\n" + "- [ ] Verify source routing\n" + " \n", + encoding="utf-8", + ) + initialize_canonical_source_fixture( + runtime_root, "g1", state_path=state_path, provider="file" + ) + + reg_a = root / "source_a" / "registry.json" + reg_b = root / "source_b" / "registry.json" + reg_g = root / "global" / "registry.json" + + def _goal_entry(title: str, *, source_registry: Path | None = None) -> dict[str, object]: + goal: dict[str, object] = { + "id": "g1", + "title": title, + "status": "active", + "repo": str(project), + "state_file": state_path.name, + "coordination": {"registered_agents": ["agent-a"]}, + } + if source_registry is not None: + goal["source_registry"] = str(source_registry) + return goal + + def _write_registry( + target: Path, + goal: dict[str, object], + *, + registry_role: str | None = None, + ) -> None: + payload: dict[str, object] = { + "schema_version": 1, + "common_runtime_root": str(runtime_root), + "goals": [goal], + } + if registry_role is not None: + payload["registry_role"] = registry_role + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(payload), encoding="utf-8") + + _write_registry(reg_a, _goal_entry("A-original")) + _write_registry(reg_b, _goal_entry("B-before")) + _write_registry( + reg_g, + _goal_entry("Global-mirror", source_registry=reg_a), + registry_role="global-local", + ) + reg_a_bytes = reg_a.read_bytes() + + with capability_hook_request_scope() as scope: + warm_b = agent_registry.load_goal_from_registry(reg_b, "g1") + assert warm_b is not None and warm_b["title"] == "B-before" + + orig_load = registry_codec.load_registry + swapped = False + + def _aba_load( + path: Path, + *, + source_snapshots: dict[Path, bytes | None] | None = None, + ) -> dict[str, object]: + nonlocal swapped + if not swapped and path.absolute() == reg_a.absolute(): + swapped = True + reg_a.unlink() + reg_a.symlink_to(reg_b) + try: + return dict(orig_load(path, source_snapshots=source_snapshots)) + finally: + reg_a.unlink() + reg_a.write_bytes(reg_a_bytes) + return dict(orig_load(path, source_snapshots=source_snapshots)) + + monkeypatch.setattr(runtime_projection_route, "load_registry", _aba_load) + scoped_todos = list_goal_todos( + registry_path=reg_g, + goal_id="g1", + ) + monkeypatch.undo() + assert swapped is True + assert not reg_a.is_symlink() and reg_a.read_bytes() == reg_a_bytes + assert scoped_todos["todo_count"] == 1 + scoped_todo_ids = [item["todo_id"] for item in scoped_todos["todos"]] + assert len(scoped_todo_ids) == 1 + assert reg_b.absolute() in scope._alias_to_targets.get(reg_a.absolute(), set()) + + with registry_codec.project_registry_transaction( + reg_b, operation="test_commit_b_after_list_readback" + ) as tx: + payload_b = tx.payload_copy() + payload_b["goals"][0]["title"] = "B-after" + assert tx.commit(payload_b) is True + + assert reg_b.absolute() not in scope.registry_snapshots + assert reg_a.absolute() not in scope.registry_snapshots + refreshed_a = agent_registry.load_goal_from_registry(reg_a, "g1") + refreshed_b = agent_registry.load_goal_from_registry(reg_b, "g1") + assert refreshed_a is not None and refreshed_a["title"] == "A-original" + assert refreshed_b is not None and refreshed_b["title"] == "B-after" + + non_scoped = list_goal_todos( + registry_path=reg_g, + goal_id="g1", + ) + assert non_scoped["todo_count"] == 1 + assert [item["todo_id"] for item in non_scoped["todos"]] == scoped_todo_ids + + +def test_failed_global_decode_alias_does_not_leave_untracked_snapshot_poisoning( + tmp_path: Path, +) -> None: + root = tmp_path.resolve() + real_global = root / "real-global.json" + real_global.write_text( + json.dumps({"schema_version": 1, "goals": [{"id": "g1", "title": "A-original"}]}), + encoding="utf-8", + ) + project_reg = root / "project-reg.json" + project_reg.write_bytes( + registry_codec._encode_document( + {"schema_version": 1, "goals": [{"id": "g1", "title": "B-before"}]}, + format=registry_codec._ProjectRegistryFormat.STRICT_ENVELOPE_V1, + minimum_writer_protocol=registry_codec.CURRENT_WRITER_PROTOCOL, + ) + ) + assert project_reg.read_text(encoding="utf-8").lstrip().startswith("[") + + global_alias = root / "registry.global.json" + global_alias.symlink_to(project_reg) + + # Baseline (unscoped): first read raises, restoring alias recovers A-original cleanly. + with pytest.raises( + registry_codec.ProjectRegistryError, + match="global registry root must be a JSON object", + ): + agent_registry.load_goal_from_registry(global_alias, "g1") + + with capability_hook_request_scope() as scope: + warm_project = agent_registry.load_goal_from_registry(project_reg, "g1") + assert warm_project is not None and warm_project["title"] == "B-before" + + with pytest.raises( + registry_codec.ProjectRegistryError, + match="global registry root must be a JSON object", + ): + agent_registry.load_goal_from_registry(global_alias, "g1") + + # Failed decode must not leave untracked raw alias bytes in scope.registry_snapshots. + assert global_alias.absolute() not in scope.registry_snapshots + assert project_reg.absolute() in scope.registry_snapshots + + global_alias.unlink() + global_alias.symlink_to(real_global) + with registry_codec.project_registry_transaction( + project_reg, operation="test_commit_project_after_failed_global_decode" + ) as tx: + payload = tx.payload_copy() + payload["goals"][0]["title"] = "B-after" + assert tx.commit(payload) is True + + recovered_global = agent_registry.load_goal_from_registry(global_alias, "g1") + refreshed_project = agent_registry.load_goal_from_registry(project_reg, "g1") + assert recovered_global is not None and recovered_global["title"] == "A-original" + assert refreshed_project is not None and refreshed_project["title"] == "B-after" + + # Cold project registry + failed global decode also recovers after restore without a commit. + global_alias.unlink() + global_alias.symlink_to(project_reg) + with capability_hook_request_scope() as scope: + with pytest.raises( + registry_codec.ProjectRegistryError, + match="global registry root must be a JSON object", + ): + agent_registry.load_goal_from_registry(global_alias, "g1") + assert global_alias.absolute() not in scope.registry_snapshots + assert project_reg.absolute() not in scope.registry_snapshots + global_alias.unlink() + global_alias.symlink_to(real_global) + recovered_cold = agent_registry.load_goal_from_registry(global_alias, "g1") + assert recovered_cold is not None and recovered_cold["title"] == "A-original" + + unscoped_recovered = agent_registry.load_goal_from_registry(global_alias, "g1") + assert unscoped_recovered is not None and unscoped_recovered["title"] == "A-original" diff --git a/tests/control_plane/test_capability_hooks_equivalence.py b/tests/control_plane/test_capability_hooks_equivalence.py new file mode 100644 index 0000000000..5be34420b2 --- /dev/null +++ b/tests/control_plane/test_capability_hooks_equivalence.py @@ -0,0 +1,787 @@ +from __future__ import annotations + +import argparse +import inspect +import json +import subprocess +import sys +import types +from collections.abc import Mapping +from contextlib import ExitStack +from pathlib import Path +from types import SimpleNamespace + +import pytest + +import loopx.agent_registry as agent_registry +import loopx.cli_commands.quota as quota_module +import loopx.control_plane.capability_hooks as capability_hooks +import loopx.control_plane.projects.registry_codec as registry_codec +from loopx.canary.maintainability_ratchet import ( + collect_oversized_decision_functions, + module_metrics, +) +from loopx.cli_commands.lark_inbox import dispatch_goal_lark_turn_start_hooks +from loopx.cli_commands.quota_should_run import dispatch_quota_turn_start_hooks +from loopx.control_plane.capability_hooks import ( + PostWritebackHookRegistration, + TURN_START_HOOK_RESULT_SCHEMA_VERSION, + TurnContextHookRegistration, + TurnStartHookRegistration, + capability_hook_request_scope, + current_hook_request_scope, + dispatch_interaction_projection_hooks, + dispatch_post_writeback_hooks, + dispatch_turn_context_hooks, + dispatch_turn_start_hooks, + invalidate_hook_registry_snapshot, + load_scoped_registry, + turn_context_source, +) +from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID, + GOAL_ID, + _write_fixture, +) + +REPO_ROOT = Path(__file__).resolve().parents[2] + +EXPECTED_EXPORTS = ( + "CAPABILITY_HOOK_REGISTRATION_SCHEMA_VERSION", + "CapabilityHookRequestScope", + "EffectRuntimeRejected", + "EffectRuntimeRemoteError", + "EffectRuntimeStartupError", + "INTERACTION_PROJECTION_HOOK_DISPATCH_SCHEMA_VERSION", + "INTERACTION_PROJECTION_HOOK_RESULT_SCHEMA_VERSION", + "InteractionProjectionHookRegistration", + "InteractionProjectionProducer", + "LOCK_POLICIES", + "LockAcquireTimeoutError", + "LockAcquisitionPolicy", + "POST_WRITEBACK_HOOK_DISPATCH_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_INPUT_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_RECEIPT_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_REGISTRATION_SCHEMA_VERSION", + "POST_WRITEBACK_HOOK_RESULT_SCHEMA_VERSION", + "POST_WRITEBACK_SOURCE_REJECTION_DIAGNOSTIC_CODE", + "PostWritebackHookRegistration", + "PostWritebackProducer", + "PostWritebackSourceRejected", + "TURN_START_HOOK_DISPATCH_SCHEMA_VERSION", + "TURN_START_HOOK_REGISTRATION_SCHEMA_VERSION", + "TURN_START_HOOK_RESULT_SCHEMA_VERSION", + "TurnContextHookRegistration", + "TurnStartContextProjector", + "TurnStartHookRegistration", + "TurnStartProducer", + "_LEGACY_LOCK_SAFE_SEGMENT_RE", + "_POST_WRITEBACK_DISPATCH_ID_RE", + "_POST_WRITEBACK_RECEIPT_SNAPSHOT_RE", + "_POST_WRITEBACK_TRANSACTION_PARAMS_MAX_BYTES", + "_bounded_post_writeback_transport_contracts", + "_bounded_post_writeback_transport_outcomes", + "_decode_post_writeback_preflight", + "_enter_legacy_post_writeback_guard", + "_hook_failure", + "_legacy_post_writeback_lock_target", + "_post_writeback_contract_placeholder", + "_post_writeback_failure_dispatch", + "_post_writeback_finalize_params", + "_post_writeback_provider_outcome", + "_post_writeback_receipt_snapshot", + "_post_writeback_runtime_failure", + "_post_writeback_transport_rejected_outcome", + "_turn_context_binding_source", + "capability_hook_request_scope", + "capability_result_fields", + "current_hook_registry_snapshots", + "current_hook_request_scope", + "dispatch_interaction_projection_hooks", + "dispatch_post_writeback_hooks", + "dispatch_turn_context_hooks", + "dispatch_turn_start_hooks", + "effect_runtime_projection_result", + "effect_runtime_result", + "exclusive_file_lock", + "host_context_projection", + "invalidate_hook_registry_snapshot", + "load_scoped_registry", + "merge_turn_start_dispatch", + "project_turn_context", + "time", + "turn_context_source", +) + + +def _load_origin_main_capability_hooks() -> types.ModuleType | None: + probe = subprocess.run( + ["git", "show", "origin/main:loopx/control_plane/capability_hooks.py"], + cwd=REPO_ROOT, + capture_output=True, + text=True, + check=False, + ) + if probe.returncode != 0 or not probe.stdout.strip(): + return None + module = types.ModuleType("loopx.control_plane._origin_main_capability_hooks") + module.__package__ = "loopx.control_plane" + module.__file__ = str(REPO_ROOT / "loopx/control_plane/capability_hooks.py") + sys.modules[module.__name__] = module + try: + exec(compile(probe.stdout, module.__file__, "exec"), module.__dict__) + except Exception: + sys.modules.pop(module.__name__, None) + raise + return module + + +def test_exports_signatures_and_zero_any_ratchet() -> None: + for symbol in EXPECTED_EXPORTS: + assert hasattr(capability_hooks, symbol), f"missing export {symbol}" + + target_paths = [ + REPO_ROOT / "loopx/control_plane/capability_hooks.py", + REPO_ROOT / "loopx/control_plane/hook_runtime/__init__.py", + REPO_ROOT / "loopx/control_plane/hook_runtime/request_scope.py", + REPO_ROOT / "loopx/control_plane/hook_runtime/contracts.py", + REPO_ROOT / "loopx/control_plane/hook_runtime/turn_context.py", + REPO_ROOT / "loopx/control_plane/hook_runtime/dispatch.py", + REPO_ROOT / "loopx/control_plane/hook_runtime/post_writeback.py", + Path(__file__).resolve(), + ] + forbidden_ignore = "type" + ": ignore" + forbidden_nofollow = "O_" + "NOFOLLOW" + for path in target_paths: + text = path.read_text(encoding="utf-8") + metrics = module_metrics(path) + assert metrics["lines"] < 800, f"{path} exceeds 800 LOC: {metrics['lines']}" + assert metrics["any_count"] == 0, f"{path} contains Any: {metrics['any_count']}" + assert metrics["dict_any_count"] == 0, f"{path} contains dict[..., Any]" + assert forbidden_ignore not in text, f"{path} contains {forbidden_ignore}" + assert forbidden_nofollow not in text, f"{path} contains {forbidden_nofollow}" + + assert collect_oversized_decision_functions(REPO_ROOT) == [] + + # Default parameter invariants stay intact when callers pass None or omit kwargs. + from loopx.control_plane.runtime.runtime_projection_route import ( + resolve_goal_source_runtime_route, + ) + + sig_dispatch = inspect.signature(dispatch_post_writeback_hooks) + for name in ("source", "hook_input", "runtime_root", "lease_timeout_seconds"): + assert sig_dispatch.parameters[name].default is None + sig_route = inspect.signature(resolve_goal_source_runtime_route) + for name in ("runtime_root_override", "registry", "source_snapshots"): + assert sig_route.parameters[name].default is None + assert current_hook_request_scope() is None + + +def test_paired_origin_main_vs_head_hook_behavior( + tmp_path: Path, +) -> None: + baseline = _load_origin_main_capability_hooks() + if baseline is None: + pytest.skip("origin/main ref unavailable in checkout") + try: + for name in ( + "turn_context_source", + "dispatch_turn_context_hooks", + "project_turn_context", + "host_context_projection", + "capability_result_fields", + "dispatch_interaction_projection_hooks", + "dispatch_turn_start_hooks", + "dispatch_post_writeback_hooks", + ): + baseline_fn = getattr(baseline, name) + head_fn = getattr(capability_hooks, name) + assert callable(baseline_fn) and callable(head_fn) + assert list(inspect.signature(head_fn).parameters.keys()) == list( + inspect.signature(baseline_fn).parameters.keys() + ), f"parameter drift on {name}" + + # 1. Turn-context positive, readback-only, duplicate, failure, and conflict checks. + assert baseline.turn_context_source({"goal_id": "g1", "agent_id": "a1"}) == ( + turn_context_source({"goal_id": "g1", "agent_id": "a1"}) + ) + for impl in (baseline, capability_hooks): + with pytest.raises(ValueError, match="conflicting Agent identities"): + impl.turn_context_source( + { + "goal_id": "g1", + "agent_id": "a1", + "agent_identity": {"agent_id": "a2"}, + } + ) + + def _run_turn_context( + mod: object, + ) -> tuple[dict[str, object], dict[str, object], dict[str, object]]: + reg = getattr(mod, "TurnContextHookRegistration") + payload: dict[str, object] = {"goal_id": "g1", "agent_id": "a1"} + hooks = ( + reg( + hook_id="fixture.readback", + capability_id="fixture", + readback_slots=("fixture_slot",), + producer=lambda: { + "readback": {"fixture_slot": {"ok": True}}, + "context_fields": {}, + "instructions": [], + "result_fields": {}, + }, + ), + reg( + hook_id="fixture.readback", + capability_id="fixture", + readback_slots=("fixture_slot_dup",), + producer=lambda: {"readback": {}}, + ), + reg( + hook_id="fixture.broken", + capability_id="fixture", + readback_slots=("fixture_broken",), + producer=lambda: (_ for _ in ()).throw(RuntimeError("boom")), + ), + ) + getattr(mod, "dispatch_turn_context_hooks")(payload, hooks) + projected = getattr(mod, "project_turn_context")(payload) + host_proj = getattr(mod, "host_context_projection")( + { + "capability_context_fields": ("extra_field",), + "extra_field": "kept", + "capability_instructions": ("do X",), + "capability_result_fields": {"r": {"type": "string"}}, + } + ) + assert getattr(mod, "capability_result_fields")(host_proj) == { + "r": {"type": "string"} + } + return payload, projected, host_proj + + assert _run_turn_context(baseline) == _run_turn_context(capability_hooks) + + # 2. Interaction projection parity (slot conflict + broken producer). + def _run_interaction(mod: object) -> dict[str, object]: + reg = getattr(mod, "InteractionProjectionHookRegistration") + hooks = ( + reg( + hook_id="proj.ok", + capability_id="fixture", + projection_slots=("slot_a",), + requested_read_scope=(), + producer=lambda: {"status": "not_applicable"}, + ), + reg( + hook_id="proj.fail", + capability_id="fixture", + projection_slots=("slot_b",), + requested_read_scope=(), + producer=lambda: (_ for _ in ()).throw(RuntimeError("boom")), + ), + ) + res = getattr(mod, "dispatch_interaction_projection_hooks")(hooks) + assert isinstance(res, dict) + return dict(res) + + assert _run_interaction(baseline) == _run_interaction(capability_hooks) + + # 3. Turn-start dispatch parity (ordering, duplicate id, uncertain write effect, context reader). + def _turn_start_packet(status: str = "observed") -> dict[str, object]: + return { + "schema_version": TURN_START_HOOK_RESULT_SCHEMA_VERSION, + "hook_id": "z.fixture", + "capability_id": "fixture", + "phase": "turn_start", + "status": status, + "observation_count": 1, + "agent_read_required": True, + "external_reads_performed": False, + "external_writes_performed": False, + "local_private_state_mutated": False, + "private_content_returned": False, + "provider_payload_returned": False, + "error_code": None, + } + + def _run_turn_start(mod: object) -> dict[str, object]: + reg = getattr(mod, "TurnStartHookRegistration") + hooks = ( + reg( + hook_id="z.fixture", + capability_id="fixture", + requested_read_scope=("goal",), + requested_write_scope=(), + producer=lambda: _turn_start_packet(), + required_read={ + "kind": "fixture", + "command": "loopx fixture read", + "reason": "verify parity", + "ordering": "before_work", + }, + context_reader=lambda: (_ for _ in ()).throw(OSError("offline")), + ), + reg( + hook_id="a.broken_write", + capability_id="fixture", + requested_read_scope=(), + requested_write_scope=("local_state",), + producer=lambda: (_ for _ in ()).throw(ValueError("bad producer")), + ), + reg( + hook_id="z.fixture", + capability_id="fixture", + requested_read_scope=(), + requested_write_scope=(), + producer=lambda: _turn_start_packet(), + ), + ) + res = getattr(mod, "dispatch_turn_start_hooks")(hooks) + assert isinstance(res, dict) + return dict(res) + + assert _run_turn_start(baseline) == _run_turn_start(capability_hooks) + + # 4. Post-writeback error & lock-guard parity. + empty_hook = PostWritebackHookRegistration( + hook_id="pw.fixture", + capability_id="fixture", + event_kinds=("todo_complete",), + intent_kinds=(), + requested_read_scope=(), + producer=lambda _inp: {"status": "empty"}, + ) + assert baseline.dispatch_post_writeback_hooks([]) == ( + dispatch_post_writeback_hooks([]) + ) + assert baseline.dispatch_post_writeback_hooks( + [empty_hook], source={}, hook_input={} + ) == dispatch_post_writeback_hooks([empty_hook], source={}, hook_input={}) + + for impl in (baseline, capability_hooks): + with pytest.raises(impl.PostWritebackSourceRejected): + impl.dispatch_post_writeback_hooks([empty_hook], source={"goal_id": ""}) + + # Legacy receipt guard check with synthetic lock directories. + raw_plan: dict[str, object] = { + "dispatch_id": "pwh_" + ("a" * 64), + "receipt_snapshot": "missing", + "hook_input": {"identity": {"goal_id": "goal-1"}}, + } + with ExitStack() as s_old: + old_err = baseline._enter_legacy_post_writeback_guard( + s_old, + runtime_root=tmp_path / "old", + raw_plan=raw_plan, + lease_timeout_seconds=0.1, + ) + with ExitStack() as s_new: + new_err = capability_hooks._enter_legacy_post_writeback_guard( + s_new, + runtime_root=tmp_path / "new", + raw_plan=raw_plan, + lease_timeout_seconds=0.1, + ) + assert old_err == new_err + assert new_err is None + finally: + sys.modules.pop(baseline.__name__, None) + + +def test_turn_start_hook_monkeypatch_seams_remain_wired( + monkeypatch: pytest.MonkeyPatch, +) -> None: + calls: list[str] = [] + real_rpc = capability_hooks.effect_runtime_result + real_source = capability_hooks.turn_context_source + + def tracked_rpc(method: str, params: Mapping[str, object]) -> object: + calls.append(method) + return real_rpc(method, params) + + monkeypatch.setattr(capability_hooks, "effect_runtime_result", tracked_rpc) + monkeypatch.setattr( + capability_hooks, + "turn_context_source", + lambda payload: real_source(payload), + ) + monkeypatch.setattr( + capability_hooks, + "time", + SimpleNamespace(monotonic=lambda: 42.0), + ) + + payload: dict[str, object] = {"goal_id": "g-hook", "agent_id": "a-hook"} + dispatch_turn_context_hooks( + payload, + ( + TurnContextHookRegistration( + hook_id="hook.seam", + capability_id="fixture", + readback_slots=("slot_x",), + producer=lambda: { + "readback": {"slot_x": {}}, + "context_fields": {}, + "instructions": [], + "result_fields": {}, + }, + ), + ), + ) + assert calls == [ + "capability_hook.turn_context.validate_registration", + "capability_hook.turn_context.validate", + ] + assert ( + dispatch_interaction_projection_hooks(())["registered_count"] == 0 + ) + assert dispatch_turn_start_hooks(())["registered_count"] == 0 + assert ( + dispatch_post_writeback_hooks( + (), + source=None, + hook_input=None, + )["failures"] + == [] + ) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_quota_turn_start_hooks_avoid_redundant_registry_reads_and_stale_cache( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + _, runtime, registry = _write_fixture( + tmp_path, + required_capability="network", + provider=provider, + ) + + counts = {"load_registry": 0, "reg_read_bytes": 0} + orig_load_reg = registry_codec.load_registry + orig_read_bytes = Path.read_bytes + + def counted_load_reg( + path: Path, + *, + source_snapshots: dict[Path, bytes | None] | None = None, + ) -> dict[str, object]: + counts["load_registry"] += 1 + return orig_load_reg(path, source_snapshots=source_snapshots) + + def counted_read_bytes(self: Path) -> bytes: + if self.resolve() == registry.resolve(): + counts["reg_read_bytes"] += 1 + return orig_read_bytes(self) + + monkeypatch.setattr(registry_codec, "load_registry", counted_load_reg) + import loopx.agent_registry as ar + import loopx.cli_commands.quota_should_run as qsr + import loopx.control_plane.runtime.goal_project_route as gpr + import loopx.control_plane.runtime.runtime_projection_route as rpr + import loopx.control_plane.todos.list_readback as lr + import loopx.history as lh + + for mod in (qsr, gpr, rpr, lr, ar, lh): + if hasattr(mod, "load_registry"): + monkeypatch.setattr(mod, "load_registry", counted_load_reg) + monkeypatch.setattr(Path, "read_bytes", counted_read_bytes) + + # Exercise agent-preferences and external_evidence_poll scopes so all hook paths stay wired. + (runtime / "agent-preferences").mkdir(parents=True, exist_ok=True) + monkeypatch.delenv("LOOPX_DISABLE_EXTERNAL_NETWORK", raising=False) + args = argparse.Namespace( + quota_command="should-run", + dry_run=False, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + scheduler_observation=False, + available_capabilities=["network", "external_evidence_poll"], + ) + dispatch, mutated = dispatch_quota_turn_start_hooks( + args, + quota_module=quota_module, + registry_path=registry, + runtime_root_arg=str(runtime), + lark_turn_start_hook_dispatcher=dispatch_goal_lark_turn_start_hooks, + ) + assert mutated is True + assert dispatch is not None + assert int(str(dispatch["registered_count"])) >= 3 + assert int(str(dispatch["invoked_count"])) == int(str(dispatch["registered_count"])) + assert current_hook_request_scope() is None + # Single-pass request scope eliminates per-hook registry re-reads (baseline was 11 load_registry / 12 read_bytes). + assert counts["load_registry"] == 1 + assert counts["reg_read_bytes"] <= 2 + + # Subsequent request must observe disk mutations immediately (no cross-request stale cache). + updated = json.loads(registry.read_text(encoding="utf-8")) + updated["goals"][0]["coordination"]["registered_agents"].append("agent-fresh") + registry.write_text(json.dumps(updated), encoding="utf-8") + + observed_agents_across_hooks: list[list[str]] = [] + + def _capture_goal_hook() -> dict[str, object]: + agents = agent_registry.registered_agent_ids_from_registry(registry, GOAL_ID) + observed_agents_across_hooks.append(agents) + return { + "schema_version": TURN_START_HOOK_RESULT_SCHEMA_VERSION, + "hook_id": f"probe.{len(observed_agents_across_hooks)}", + "capability_id": "fixture", + "phase": "turn_start", + "status": "empty", + "observation_count": 0, + "agent_read_required": False, + "external_reads_performed": False, + "external_writes_performed": False, + "local_private_state_mutated": False, + "private_content_returned": False, + "provider_payload_returned": False, + "error_code": None, + } + + counts["load_registry"] = 0 + counts["reg_read_bytes"] = 0 + probe_hooks = tuple( + TurnStartHookRegistration( + hook_id=f"probe.{idx}", + capability_id="fixture", + requested_read_scope=("goal",), + requested_write_scope=(), + producer=_capture_goal_hook, + ) + for idx in range(1, 5) + ) + res = dispatch_turn_start_hooks(probe_hooks) + assert res["invoked_count"] == 4 + assert all("agent-fresh" in agents for agents in observed_agents_across_hooks) + assert counts["load_registry"] == 1 + assert counts["reg_read_bytes"] == 1 + assert current_hook_request_scope() is None + + # Direct standalone calls outside any dispatch scope never retain stale state across writes. + updated2 = json.loads(registry.read_text(encoding="utf-8")) + updated2["goals"][0]["coordination"]["registered_agents"].append("agent-direct") + registry.write_text(json.dumps(updated2), encoding="utf-8") + assert "agent-direct" in agent_registry.registered_agent_ids_from_registry( + registry, GOAL_ID + ) + + # Explicit invalidation clears cached snapshot inside an open scope too. + with capability_hook_request_scope(): + first_agents = agent_registry.registered_agent_ids_from_registry( + registry, GOAL_ID + ) + assert "agent-invalidated" not in first_agents + updated3 = json.loads(registry.read_text(encoding="utf-8")) + updated3["goals"][0]["coordination"]["registered_agents"].append( + "agent-invalidated" + ) + registry.write_text(json.dumps(updated3), encoding="utf-8") + invalidate_hook_registry_snapshot(registry) + second_agents = agent_registry.registered_agent_ids_from_registry( + registry, GOAL_ID + ) + assert "agent-invalidated" in second_agents + refreshed = load_scoped_registry(registry, loader=orig_load_reg) + assert isinstance(refreshed.get("goals"), list) + + +def _goal_ids(payload: Mapping[str, object]) -> list[object]: + goals = payload.get("goals") + assert isinstance(goals, list) + return [g["id"] for g in goals if isinstance(g, Mapping)] + + +def test_request_scope_preserves_path_format_semantics_across_symlinks( + tmp_path: Path, +) -> None: + project_reg = tmp_path / "registry.json" + envelope_bytes = registry_codec._encode_document( + {"goals": [{"id": "g1", "title": "Project Goal"}]}, + format=registry_codec._ProjectRegistryFormat.STRICT_ENVELOPE_V1, + minimum_writer_protocol=registry_codec.CURRENT_WRITER_PROTOCOL, + ) + project_reg.write_bytes(envelope_bytes) + global_alias = tmp_path / "registry.global.json" + global_alias.symlink_to(project_reg) + + with pytest.raises(registry_codec.ProjectRegistryError, match="global registry root must be a JSON object"): + registry_codec.load_registry(global_alias) + + with capability_hook_request_scope(): + project_loaded = load_scoped_registry(project_reg, loader=registry_codec.load_registry) + assert _goal_ids(project_loaded) == ["g1"] + project_goal = agent_registry.load_goal_from_registry(project_reg, "g1") + assert project_goal is not None and project_goal["id"] == "g1" + + with pytest.raises(registry_codec.ProjectRegistryError, match="global registry root must be a JSON object"): + load_scoped_registry(global_alias, loader=registry_codec.load_registry) + + with pytest.raises(registry_codec.ProjectRegistryError, match="global registry root must be a JSON object"): + agent_registry.load_goal_from_registry(global_alias, "g1") + + still_project_goal = agent_registry.load_goal_from_registry(project_reg, "g1") + assert still_project_goal is not None and still_project_goal["id"] == "g1" + + +def test_request_scope_atomic_write_invalidates_alias_snapshots_and_goal_index( + tmp_path: Path, +) -> None: + real_reg = tmp_path / "registry.json" + alias_reg = tmp_path / "alias.json" + alias_direct = tmp_path / "alias_direct.json" + v1_bytes = json.dumps( + {"goals": [{"id": "g-old", "title": "Old Goal"}]} + ).encode("utf-8") + v2_bytes = json.dumps( + {"goals": [{"id": "g-new", "title": "New Goal"}]} + ).encode("utf-8") + registry_codec._atomic_write_bytes(real_reg, v1_bytes, mode=None) + alias_reg.symlink_to(real_reg) + alias_direct.symlink_to(real_reg) + + with capability_hook_request_scope() as scope: + first = load_scoped_registry(alias_reg, loader=registry_codec.load_registry) + assert _goal_ids(first) == ["g-old"] + old_goal = agent_registry.load_goal_from_registry(alias_reg, "g-old") + assert old_goal is not None and old_goal["id"] == "g-old" + direct_v1 = registry_codec.load_registry( + alias_direct, source_snapshots=scope.registry_snapshots + ) + assert _goal_ids(direct_v1) == ["g-old"] + + registry_codec._atomic_write_bytes(real_reg, v2_bytes, mode=None) + + alias_v2 = load_scoped_registry(alias_reg, loader=registry_codec.load_registry) + real_v2 = load_scoped_registry(real_reg, loader=registry_codec.load_registry) + direct_v2 = registry_codec.load_registry( + alias_direct, source_snapshots=scope.registry_snapshots + ) + assert _goal_ids(alias_v2) == ["g-new"] + assert _goal_ids(real_v2) == ["g-new"] + assert _goal_ids(direct_v2) == ["g-new"] + assert agent_registry.load_goal_from_registry(alias_reg, "g-old") is None + assert agent_registry.load_goal_from_registry(real_reg, "g-old") is None + new_alias_goal = agent_registry.load_goal_from_registry(alias_reg, "g-new") + new_real_goal = agent_registry.load_goal_from_registry(real_reg, "g-new") + assert new_alias_goal is not None and new_alias_goal["id"] == "g-new" + assert new_real_goal is not None and new_real_goal["id"] == "g-new" + + +def test_request_scope_repointed_symlink_does_not_poison_canonical_target(tmp_path: Path) -> None: + t1, t2, t3 = (tmp_path / "t1" / "registry.json", tmp_path / "t2" / "registry.json", tmp_path / "t3" / "registry.json") + alias, witness_alias = tmp_path / "alias_dir" / "registry.json", tmp_path / "witness_dir" / "registry.json" + for p, gid in ((t1, "g-t1"), (t2, "g-t2"), (t3, "g-t3")): + p.parent.mkdir() + p.write_text(json.dumps({"goals": [{"id": gid}]}), encoding="utf-8") + alias.parent.mkdir() + witness_alias.parent.mkdir() + alias.symlink_to(t1) + witness_alias.symlink_to(t1) + + with capability_hook_request_scope() as scope: + assert _goal_ids(load_scoped_registry(alias, loader=registry_codec.load_registry)) == ["g-t1"] + assert _goal_ids(registry_codec.load_registry(witness_alias, source_snapshots=scope.registry_snapshots)) == ["g-t1"] + + alias.unlink() + alias.symlink_to(t2) + witness_alias.unlink() + witness_alias.symlink_to(t3) + + assert _goal_ids(load_scoped_registry(alias, loader=registry_codec.load_registry)) == ["g-t1"] + assert _goal_ids(load_scoped_registry(witness_alias, loader=registry_codec.load_registry)) == ["g-t1"] + assert _goal_ids(load_scoped_registry(t2, loader=registry_codec.load_registry)) == ["g-t2"] + t2_goal = agent_registry.load_goal_from_registry(t2, "g-t2") + assert t2_goal is not None and t2_goal["id"] == "g-t2" + assert _goal_ids(load_scoped_registry(t3, loader=registry_codec.load_registry)) == ["g-t3"] + t3_goal = agent_registry.load_goal_from_registry(t3, "g-t3") + assert t3_goal is not None and t3_goal["id"] == "g-t3" + + +def test_request_scope_aba_symlink_roundtrip_does_not_poison_canonical_target( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + reg_a, reg_b = tmp_path / "a" / "registry.json", tmp_path / "b" / "registry.json" + alias = tmp_path / "alias" / "registry.json" + for p, title in ((reg_a, "TITLE_FROM_A"), (reg_b, "TITLE_FROM_B")): + p.parent.mkdir() + p.write_text(json.dumps({"goals": [{"id": "g1", "title": title}]}), encoding="utf-8") + alias.parent.mkdir() + alias.symlink_to(reg_a) + + orig_resolve = Path.resolve + alias_resolve_calls = 0 + + def _aba_race_resolve(self: Path, strict: bool = False) -> Path: + nonlocal alias_resolve_calls + target = orig_resolve(self, strict=strict) + if self.parent.name == "alias" and self.name == "registry.json": + alias_resolve_calls += 1 + if alias_resolve_calls == 1: + alias.unlink() + alias.symlink_to(reg_b) + elif alias_resolve_calls == 2: + alias.unlink() + alias.symlink_to(reg_a) + return target + + monkeypatch.setattr(Path, "resolve", _aba_race_resolve) + with capability_hook_request_scope(): + alias_goal = agent_registry.load_goal_from_registry(alias, "g1") + assert alias_goal is not None and alias_goal["title"] == "TITLE_FROM_B" + reg_a_goal = agent_registry.load_goal_from_registry(reg_a, "g1") + assert reg_a_goal is not None and reg_a_goal["title"] == "TITLE_FROM_A" + reg_a_loaded = load_scoped_registry(reg_a, loader=registry_codec.load_registry) + goals = reg_a_loaded["goals"] + assert isinstance(goals, list) and isinstance(goals[0], dict) + assert goals[0]["title"] == "TITLE_FROM_A" + + +def test_request_scope_invalidate_ignores_unresolvable_symlink_loop_alias( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + loop_a = tmp_path / "loop_a.json" + loop_b = tmp_path / "loop_b.json" + other = tmp_path / "other.json" + target = tmp_path / "target.json" + other.write_text(json.dumps({"goals": [{"id": "g-other"}]}), encoding="utf-8") + target.write_text(json.dumps({"goals": [{"id": "g-target", "title": "v1"}]}), encoding="utf-8") + loop_a.symlink_to(other) + + original_resolve = Path.resolve + + def _resolve_with_312_loop(self: Path, strict: bool = False) -> Path: + if self.name == "loop_a.json": + raise RuntimeError(f"Symlink loop from {self!r}") + return original_resolve(self, strict=strict) + + with capability_hook_request_scope(): + assert _goal_ids(load_scoped_registry(loop_a, loader=registry_codec.load_registry)) == ["g-other"] + assert _goal_ids(load_scoped_registry(target, loader=registry_codec.load_registry)) == ["g-target"] + + loop_a.unlink() + loop_a.symlink_to(loop_b) + loop_b.symlink_to(loop_a) + + with registry_codec.project_registry_transaction(target, operation="test_loop_unwrapped") as tx: + payload = tx.payload_copy() + payload["goals"][0]["title"] = "v2" + assert tx.commit(payload) is True + + monkeypatch.setattr(Path, "resolve", _resolve_with_312_loop) + with registry_codec.project_registry_transaction(target, operation="test_loop_runtime_error") as tx: + payload = tx.payload_copy() + payload["goals"][0]["title"] = "v3" + assert tx.commit(payload) is True + invalidate_hook_registry_snapshot(loop_a) + + refreshed = load_scoped_registry(target, loader=registry_codec.load_registry) + goals = refreshed["goals"] + assert isinstance(goals, list) and isinstance(goals[0], dict) + assert goals[0]["title"] == "v3" + goal_obj = agent_registry.load_goal_from_registry(target, "g-target") + assert goal_obj is not None and goal_obj["title"] == "v3"