diff --git a/loopx/capabilities/issue_fix/pr_gate_reconcile.py b/loopx/capabilities/issue_fix/pr_gate_reconcile.py index 6d4e585c4d..e8177cb621 100644 --- a/loopx/capabilities/issue_fix/pr_gate_reconcile.py +++ b/loopx/capabilities/issue_fix/pr_gate_reconcile.py @@ -1,7 +1,8 @@ from __future__ import annotations +from collections.abc import Callable, Mapping, Sequence from pathlib import Path -from typing import Any, Mapping +from typing import Any from ...history import load_registry from ...paths import resolve_runtime_root @@ -193,6 +194,8 @@ def reconcile_issue_fix_pr_review( fetch_timeout_seconds: int = 10, execute: bool = False, generated_at: str | None = None, + prefetched_todos: Sequence[Mapping[str, Any]] | None = None, + on_todo_mutation: Callable[[], None] | None = None, ) -> dict[str, Any]: context = resolve_issue_fix_pr_review_context( registry_path=registry_path, @@ -202,6 +205,7 @@ def reconcile_issue_fix_pr_review( project=project, url=url, ack_receipt=ack_receipt, + prefetched_todos=prefetched_todos, ) context_status = str(context.get("status") or "ack_receipt_invalid") if context_status == "current" and ack_receipt is None: @@ -256,6 +260,7 @@ def reconcile_issue_fix_pr_review( project=project, url=url, ack_receipt=ack_receipt, + prefetched_todos=None if fetch_metadata else prefetched_todos, ) ack_status = str(current.get("status") or "ack_receipt_invalid") ack_valid = ack_status == "matched" @@ -335,6 +340,8 @@ def reconcile_issue_fix_pr_review( project=project, ) receipt["write_performed"] = bool(completion.get("changed")) + if receipt["write_performed"] and on_todo_mutation is not None: + on_todo_mutation() receipt["todo_completion"] = { "completed": completion.get("completed"), "status": completion.get("status"), @@ -364,6 +371,8 @@ def reconcile_acknowledged_issue_fix_pr_reviews( fetch_timeout_seconds: int = 10, execute: bool = False, generated_at: str | None = None, + todo_loader: Callable[[], Sequence[Mapping[str, Any]]] | None = None, + on_todo_mutation: Callable[[], None] | None = None, ) -> dict[str, Any]: """Reconcile current review todos from their persisted acknowledgement bindings.""" @@ -377,6 +386,14 @@ def reconcile_acknowledged_issue_fix_pr_reviews( goal_id=goal_id, agent_id=agent_id, ) + prefetched_todos: Sequence[Mapping[str, Any]] | None = None + if receipts and todo_loader is not None and any( + isinstance(receipt.get("binding"), Mapping) + and str(receipt["binding"].get("todo_id") or "").strip() + and str(receipt["binding"].get("permalink") or "").strip() + for receipt in receipts + ): + prefetched_todos = todo_loader() results: list[dict[str, Any]] = [] for ack_receipt in receipts: binding = ack_receipt.get("binding") @@ -419,6 +436,8 @@ def reconcile_acknowledged_issue_fix_pr_reviews( fetch_timeout_seconds=fetch_timeout_seconds, execute=execute, generated_at=generated_at, + prefetched_todos=prefetched_todos, + on_todo_mutation=on_todo_mutation, ) except ValueError: result = { diff --git a/loopx/capabilities/issue_fix/pr_review_ack.py b/loopx/capabilities/issue_fix/pr_review_ack.py index 35f504bf2d..0d1189b979 100644 --- a/loopx/capabilities/issue_fix/pr_review_ack.py +++ b/loopx/capabilities/issue_fix/pr_review_ack.py @@ -2,7 +2,7 @@ import hashlib import json -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from pathlib import Path from typing import Any @@ -16,6 +16,7 @@ from ...rollout_event_log import ( append_rollout_event_once, build_rollout_event, + iter_reverse_rollout_events_by_kind, load_rollout_events, rollout_event_log_path, ) @@ -66,15 +67,27 @@ def _require_exact_review_todo( todo_id: str, agent_id: str, project: Path | None, + prefetched_todos: Sequence[Mapping[str, Any]] | None = None, ) -> dict[str, Any]: - todo_payload = list_goal_todos( - registry_path=registry_path, - goal_id=goal_id, - role="user", - todo_id=todo_id, - project=project, - ) - todo = todo_payload.get("todo") + todo: dict[str, Any] | None = None + if prefetched_todos is not None: + for candidate in prefetched_todos: + if ( + candidate.get("todo_id") == todo_id + and candidate.get("role") in (None, "user") + ): + todo = dict(candidate) + break + if todo is None: + todo_payload = list_goal_todos( + registry_path=registry_path, + goal_id=goal_id, + role="user", + todo_id=todo_id, + project=project, + ) + raw_todo = todo_payload.get("todo") + todo = raw_todo if isinstance(raw_todo, dict) else None if not isinstance(todo, dict): raise ValueError(f"user todo {todo_id!r} was not found") if todo_item_task_class(todo) != TODO_TASK_CLASS_USER_ACTION: @@ -115,6 +128,7 @@ def resolve_issue_fix_pr_review_context( project: Path | None, url: str, ack_receipt: Mapping[str, Any] | None = None, + prefetched_todos: Sequence[Mapping[str, Any]] | None = None, ) -> dict[str, Any]: try: todo = _require_exact_review_todo( @@ -123,6 +137,7 @@ def resolve_issue_fix_pr_review_context( todo_id=todo_id, agent_id=agent_id, project=project, + prefetched_todos=prefetched_todos, ) except ValueError as exc: return { @@ -364,12 +379,11 @@ def load_issue_fix_pr_review_ack_receipts( ) -> list[dict[str, Any]]: receipts: list[dict[str, Any]] = [] seen_todos: set[str] = set() - events = load_rollout_events(rollout_event_log_path(runtime_root, goal_id)) - for event in reversed(events): - if ( - event.get("event_kind") != PR_REVIEW_ACK_EVENT_KIND - or str(event.get("agent_id") or "") != agent_id - ): + for event in iter_reverse_rollout_events_by_kind( + rollout_event_log_path(runtime_root, goal_id), + event_kind=PR_REVIEW_ACK_EVENT_KIND, + ): + if str(event.get("agent_id") or "") != agent_id: continue todo_id = str(event.get("todo_id") or "") if not todo_id or todo_id in seen_todos: diff --git a/loopx/capabilities/issue_fix/pr_wait_hook.py b/loopx/capabilities/issue_fix/pr_wait_hook.py index 5eb7569006..ee92928448 100644 --- a/loopx/capabilities/issue_fix/pr_wait_hook.py +++ b/loopx/capabilities/issue_fix/pr_wait_hook.py @@ -55,7 +55,8 @@ def _availability(registry_path: Path, runtime_root: Path, goal_id: str, def turn_start_hook(*, registry_path: Path, runtime_root: Path, goal_id: str, agent_id: str, available: Any, - fetch_timeout_seconds: int = 10) -> TurnStartHookRegistration | None: + fetch_timeout_seconds: int = 10, + shared_agent_todos_loader: Any = None) -> TurnStartHookRegistration | None: # The existing typed owner resolves declarations, remembered host observations # and revocation. A Todo requirement is never a capability grant. try: @@ -95,7 +96,8 @@ def produce() -> dict[str, Any]: readback = reconcile_pr_wait_dependencies(registry_path=registry_path, runtime_root_arg=str(runtime_root), goal_id=goal_id, agent_id=agent_id, - fetch_timeout_seconds=fetch_timeout_seconds) + fetch_timeout_seconds=fetch_timeout_seconds, + shared_agent_todos_loader=shared_agent_todos_loader) count = readback["external_read_count"] written = count > 0 status = "partial" if readback.get("degraded") else "observed" if count else "empty" diff --git a/loopx/capabilities/issue_fix/pr_wait_reconcile.py b/loopx/capabilities/issue_fix/pr_wait_reconcile.py index e259e3b893..a8fd8ffdfe 100644 --- a/loopx/capabilities/issue_fix/pr_wait_reconcile.py +++ b/loopx/capabilities/issue_fix/pr_wait_reconcile.py @@ -5,6 +5,7 @@ """ from __future__ import annotations +from collections.abc import Callable, Mapping, Sequence from pathlib import Path from subprocess import TimeoutExpired from typing import Any @@ -27,6 +28,7 @@ def reconcile_pr_wait_dependencies( *, registry_path: Path, runtime_root_arg: str | None, goal_id: str, agent_id: str, fetch_timeout_seconds: int = 10, + shared_agent_todos_loader: Callable[[], Sequence[Mapping[str, Any]] | None] | None = None, ) -> dict[str, Any]: if agent_id not in registered_agent_ids_from_registry(registry_path, goal_id): raise ValueError("PR dependency observation requires a registered agent") @@ -40,7 +42,8 @@ def reconcile_pr_wait_dependencies( policy=LockAcquisitionPolicy.SINGLE_FLIGHT, agent_id=agent_id, operation="pr_wait_observation"): return _reconcile_locked(registry_path=registry_path, runtime_root_arg=str(runtime), - goal_id=goal_id, agent_id=agent_id, fetch_timeout_seconds=fetch_timeout_seconds) + goal_id=goal_id, agent_id=agent_id, fetch_timeout_seconds=fetch_timeout_seconds, + shared_agent_todos_loader=shared_agent_todos_loader) except LockAcquireTimeoutError: return {"ok": True, "degraded": False, "failure_count": 0, "external_read_count": 0, "observation_in_progress": True, "merged_count": 0, "results": [], @@ -50,13 +53,23 @@ def reconcile_pr_wait_dependencies( def _reconcile_locked( *, registry_path: Path, runtime_root_arg: str | None, goal_id: str, agent_id: str, fetch_timeout_seconds: int, + shared_agent_todos_loader: Callable[[], Sequence[Mapping[str, Any]] | None] | None = None, ) -> dict[str, Any]: runtime = (Path(runtime_root_arg).expanduser() if runtime_root_arg else resolve_runtime_root(load_registry(registry_path), None)) # Deliberately omit list --agent-id and display limits. The typed owner must # see archived/deferred/claimed facts before choosing this actor's subjects. - todos = list_goal_todos(registry_path=registry_path, runtime_root_arg=str(runtime), - goal_id=goal_id, role="agent")["todos"] + prefetched = shared_agent_todos_loader() if shared_agent_todos_loader is not None else None + todos = ( + [dict(item) for item in prefetched] + if prefetched is not None + else list_goal_todos( + registry_path=registry_path, + runtime_root_arg=str(runtime), + goal_id=goal_id, + role="agent", + )["todos"] + ) compact = compact_todo_resume_items(todos) for row, original in zip(compact, todos, strict=True): if "excluded_agents" in original: diff --git a/loopx/cli_commands/status.py b/loopx/cli_commands/status.py index b5cb47bcdd..b79eb76fc2 100644 --- a/loopx/cli_commands/status.py +++ b/loopx/cli_commands/status.py @@ -12,6 +12,7 @@ ) from ..paths import display_path_text from ..control_plane.coordination.local_authority import LocalCoordinationAuthorityUnavailable +from ..control_plane.effect_runtime import effect_runtime_request_scope from ..control_plane.runtime.status_projection_cache import ( load_status_projection_cache, resolve_status_projection_cache_runtime_root, @@ -24,6 +25,7 @@ compact_agent_lane_status_payload_for_display, ) from ..control_plane.todos.contract import normalize_todo_claimed_by +from ..control_plane.todos.quota_selection import StaleCanonicalQuotaSourceError from ..control_plane.quota.goal_boundary import registry_goal_by_id from ..control_plane.todos.quota_summary import ( compact_agent_lane_todos_for_status_display, @@ -193,6 +195,43 @@ def handle_check_command( return 0 if payload.get("ok") else 1 +_STATUS_CANONICAL_SOURCE_MAX_ATTEMPTS = 2 + + +def _attach_agent_lane_for_attempt( + payload: dict[str, object], + *, + agent_id: str, + attempt: int, + max_attempts: int = _STATUS_CANONICAL_SOURCE_MAX_ATTEMPTS, +) -> bool: + """Attach agent-lane actions, retrying stale canonical snapshots up to the ceiling.""" + try: + attach_agent_lane_next_actions( + payload, + agent_id=agent_id, + propagate_stale_canonical_source=True, + ) + except StaleCanonicalQuotaSourceError: + if attempt + 1 < max_attempts: + return False + raise + return True + + +def _annotate_status_collection_error( + payload: dict[str, object], exc: BaseException +) -> None: + """Attach typed error fields for known status-collection failures.""" + if isinstance(exc, LocalCoordinationAuthorityUnavailable): + payload["error_code"] = exc.code + payload["authority_read"] = exc.payload + elif isinstance(exc, StaleCanonicalQuotaSourceError): + payload["code"] = "quota_canonical_source_changed" + payload["error_code"] = "quota_canonical_source_changed" + payload["retry_attempts"] = _STATUS_CANONICAL_SOURCE_MAX_ATTEMPTS + + def handle_status_command( args: argparse.Namespace, *, @@ -213,55 +252,65 @@ def handle_status_command( ) payload = None cache_metadata = None - if args.use_projection_cache: - payload, cache_metadata = load_status_projection_cache( - registry_path=registry_path, - runtime_root=runtime_root, - limit=collection_limit, - include_task_graph=args.include_task_graph, - goal_id=args.goal_id, - max_age_seconds=args.projection_cache_ttl_seconds, - available_capabilities=args.available_capabilities, - agent_lane_id=args.agent_id, - ) - if payload is None: - payload = collect_status( - registry_path=registry_path, - runtime_root_override=runtime_root_arg, - limit=collection_limit, - include_task_graph=args.include_task_graph, - goal_id=args.goal_id, - available_capabilities=args.available_capabilities, - agent_lane_id=args.agent_id, - ) - if args.write_projection_cache: - cache_metadata = write_status_projection_cache( - registry_path=registry_path, - runtime_root=runtime_root, - limit=collection_limit, - include_task_graph=args.include_task_graph, - goal_id=args.goal_id, - payload=payload, - max_age_seconds=args.projection_cache_ttl_seconds, - available_capabilities=args.available_capabilities, - agent_lane_id=args.agent_id, - ) - payload["projection_cache"] = cache_metadata - elif cache_metadata: - payload["projection_cache"] = cache_metadata - if args.agent_id: - attach_agent_lane_next_actions(payload, agent_id=args.agent_id) - _trim_run_history_for_status_display( - payload, - display_limit=display_limit, - collection_limit=collection_limit, - ) - compact_agent_lane_todos_for_status_display(payload) - compact_agent_lane_status_payload_for_display( - payload, - agent_id=args.agent_id, - ) - compact_agent_lane_todo_index_for_status_display(payload) + with effect_runtime_request_scope(): + for attempt in range(_STATUS_CANONICAL_SOURCE_MAX_ATTEMPTS): + payload = None + cache_metadata = None + if attempt == 0 and args.use_projection_cache: + payload, cache_metadata = load_status_projection_cache( + registry_path=registry_path, + runtime_root=runtime_root, + limit=collection_limit, + include_task_graph=args.include_task_graph, + goal_id=args.goal_id, + max_age_seconds=args.projection_cache_ttl_seconds, + available_capabilities=args.available_capabilities, + agent_lane_id=args.agent_id, + ) + if payload is None: + payload = collect_status( + registry_path=registry_path, + runtime_root_override=runtime_root_arg, + limit=collection_limit, + include_task_graph=args.include_task_graph, + goal_id=args.goal_id, + available_capabilities=args.available_capabilities, + agent_lane_id=args.agent_id, + ) + if args.write_projection_cache: + cache_metadata = write_status_projection_cache( + registry_path=registry_path, + runtime_root=runtime_root, + limit=collection_limit, + include_task_graph=args.include_task_graph, + goal_id=args.goal_id, + payload=payload, + max_age_seconds=args.projection_cache_ttl_seconds, + available_capabilities=args.available_capabilities, + agent_lane_id=args.agent_id, + ) + payload["projection_cache"] = cache_metadata + elif cache_metadata: + payload["projection_cache"] = cache_metadata + if args.agent_id: + if not _attach_agent_lane_for_attempt( + payload, + agent_id=args.agent_id, + attempt=attempt, + ): + continue + _trim_run_history_for_status_display( + payload, + display_limit=display_limit, + collection_limit=collection_limit, + ) + compact_agent_lane_todos_for_status_display(payload) + compact_agent_lane_status_payload_for_display( + payload, + agent_id=args.agent_id, + ) + compact_agent_lane_todo_index_for_status_display(payload) + break pending_composition_retries = collect_pending_composition_retry_projection( runtime_root, args.goal_id, agent_id=args.agent_id ) @@ -297,9 +346,7 @@ def handle_status_command( ], }, } - if isinstance(exc, LocalCoordinationAuthorityUnavailable): - payload["error_code"] = exc.code - payload["authority_read"] = exc.payload + _annotate_status_collection_error(payload, exc) print_payload( display_report_value(payload), output_format(args), @@ -667,7 +714,10 @@ def _agent_reward_memory_projection( def attach_agent_lane_next_actions( - payload: dict[str, object], *, agent_id: str + payload: dict[str, object], + *, + agent_id: str, + propagate_stale_canonical_source: bool = True, ) -> dict[str, object]: safe_agent_id = str(agent_id or "").strip() if not safe_agent_id: @@ -714,11 +764,16 @@ def attach_agent_lane_next_actions( decision_payload, goal_id=goal_id, agent_id=safe_agent_id, + reuse_fresh_canonical_snapshot=True, ) selected = guard.get("replan_action_packet") or {} obligation = (frontier or {}).get("obligation") or {} if selected.get("capability_guard") and selected.get("obligation_id") == obligation.get("obligation_id"): guard["autonomous_replan_obligation"] = obligation + except StaleCanonicalQuotaSourceError: + if propagate_stale_canonical_source: + raise + continue except Exception: continue next_action = guard.get("agent_lane_next_action") @@ -915,17 +970,25 @@ def handle_review_packet_command( ) -> int: selected_format = output_format(args, "review_packet_format") try: - status_payload = collect_status( - registry_path=registry_path, - runtime_root_override=runtime_root_arg, - limit=max(0, args.limit), - include_task_graph=not args.handoff_only, - goal_id=args.goal_id, - available_capabilities=args.available_capabilities, - agent_lane_id=args.agent_id, - ) - if args.agent_id: - attach_agent_lane_next_actions(status_payload, agent_id=args.agent_id) + with effect_runtime_request_scope(): + for attempt in range(_STATUS_CANONICAL_SOURCE_MAX_ATTEMPTS): + status_payload = collect_status( + registry_path=registry_path, + runtime_root_override=runtime_root_arg, + limit=max(0, args.limit), + include_task_graph=not args.handoff_only, + goal_id=args.goal_id, + available_capabilities=args.available_capabilities, + agent_lane_id=args.agent_id, + ) + if args.agent_id: + if not _attach_agent_lane_for_attempt( + status_payload, + agent_id=args.agent_id, + attempt=attempt, + ): + continue + break if args.handoff_only: payload = build_project_agent_handoff( status_payload, goal_id=args.goal_id, action_kind=args.action_kind, @@ -941,6 +1004,7 @@ def handle_review_packet_command( "goal_id": args.goal_id, "error": str(exc), } + _annotate_status_collection_error(payload, exc) if args.handoff_only: payload = review_packet_handoff_only_payload(payload) if args.handoff_only and selected_format != "json" and payload.get("ok"): diff --git a/loopx/control_plane/agents/workspace_guard.py b/loopx/control_plane/agents/workspace_guard.py index 6d2f73ebd6..e5acff722e 100644 --- a/loopx/control_plane/agents/workspace_guard.py +++ b/loopx/control_plane/agents/workspace_guard.py @@ -237,6 +237,7 @@ def observe_goal_delivery_workspace_isolation( selected_todo: dict[str, Any], *, project_asset: Mapping[str, Any] | None = None, + captured_local_workspace: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Preview settlement's typed policy, without granting workspace admission. @@ -265,9 +266,16 @@ def observe_goal_delivery_workspace_isolation( if repo and goal_id and not selected_todo.get("task_repository"): root = Path(str(repo)).expanduser() if root.is_absolute(): - workspace = capture_delivery_workspace( - root, local_goal_id=str(goal_id), local_project_root=root, - ) + if ( + isinstance(captured_local_workspace, Mapping) + and captured_local_workspace.get("goal_id") == str(goal_id) + and captured_local_workspace.get("root") == str(root) + ): + workspace = captured_local_workspace.get("workspace") + else: + workspace = capture_delivery_workspace( + root, local_goal_id=str(goal_id), local_project_root=root, + ) policy = goal.get("workspace_guard_policy") policy = policy if isinstance(policy, dict) else {} explicit_requirement = policy.get("peer_independent_worktree_required") @@ -435,6 +443,8 @@ def observe_goal_local_workspace( goal: dict[str, Any], selected_todo: dict[str, Any] | None, allowed_write_scopes: list[str] | None = None, + *, + captured_out: dict[str, Any] | None = None, ) -> dict[str, Any]: """Reuse the registered workspace identity and project its existing grants.""" empty: dict[str, Any] = {} @@ -450,6 +460,13 @@ def observe_goal_local_workspace( snapshot = capture_delivery_workspace( root, local_goal_id=str(goal_id), local_project_root=root ) + if captured_out is not None: + captured_out.clear() + captured_out.update({ + "root": str(root), + "goal_id": str(goal_id), + "workspace": snapshot, + }) if not snapshot or snapshot.get("identity_kind") != "local_goal": return empty boundary = goal.get("coordination") or {} diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 109c6bce0a..46ce8842d5 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -281,6 +281,7 @@ export function createEffectRuntimeHandlers( ["turn_journal.observed_capabilities", lazyHandler(() => import("./turn_driver/turn_journal_query.ts"), ({readTurnJournalCapabilities}) => readTurnJournalCapabilities)], ["todo.priority.plan", lazyHandler(() => import("./todos/priority.ts"), ({evaluateTodoPriority}) => evaluateTodoPriority)], ["todo.read", lazyHandler(() => import("./todos/read_transport.ts"), ({readTodoRuntime}) => readTodoRuntime)], + ["todo.authority_head.verify", lazyHandler(() => import("./todos/read_transaction.ts"), ({verifyCanonicalTodoAuthorityWitness}) => verifyCanonicalTodoAuthorityWitness)], ["capabilities.periodic_report.progress.select", lazyHandler(() => import("./capabilities/periodic_report_progress.ts"), ({selectPeriodicReportProgress}) => selectPeriodicReportProgress)], ["capabilities.periodic_report.approval_retry.select", lazyHandler(() => import("./capabilities/periodic_report_progress.ts"), ({selectPeriodicReportApprovalRetry}) => selectPeriodicReportApprovalRetry)], ["todo.succession.project", lazyHandler(() => import("./todos/succession.ts"), ({projectTodoSuccession}) => projectTodoSuccession)], @@ -319,7 +320,13 @@ export function createEffectRuntimeHandlers( ["goal.fallback_disposition.project", lazyHandler(() => import("./goals/goal_frontier/fallback_disposition.ts"), ({projectFallbackDisposition}) => projectFallbackDisposition)], ["todo.pr_wait_observation.plan", lazyHandler(() => import("./todos/pr_wait_observation.ts"), ({planPrWaitObservationsFromSource}) => planPrWaitObservationsFromSource)], ["todo.resume_planning.project", lazyHandler(() => import("./todos/resume_planning.ts"), ({projectTodoResumePlanning}) => projectTodoResumePlanning)], - ["todo.quota_planning.project", lazyHandler(() => import("./todos/quota_selection.ts"), ({projectTodoQuotaPlanning}) => projectTodoQuotaPlanning)], + ["todo.quota_planning.project", lazyHandler( + () => Promise.all([import("./todos/quota_selection.ts"), import("./todos/read_transaction.ts")]), + ([{projectTodoQuotaPlanning}, {projectCanonicalQuotaBatch}]) => + (params) => params?.schema_version === "todo_quota_planning_batch_v0" + ? projectCanonicalQuotaBatch(params) + : projectTodoQuotaPlanning(params), + )], ["todo.frontier_revision.project", lazyHandler(() => import("./todos/frontier_revision.ts"), ({projectAdvancementFrontier}) => projectAdvancementFrontier)], ["goal.long_todo_chain.evaluate", lazyHandler(() => import("./todos/frontier_revision.ts"), ({evaluateLongTodoChain}) => evaluateLongTodoChain)], ["scheduler.state_transition.evaluate", lazyHandler(() => import("./scheduler/state_transition_rules.ts"), ({evaluateSchedulerStateTransition}) => evaluateSchedulerStateTransition)], diff --git a/loopx/control_plane/quota/should_run.py b/loopx/control_plane/quota/should_run.py index 35e8716efc..ce56b17e2b 100644 --- a/loopx/control_plane/quota/should_run.py +++ b/loopx/control_plane/quota/should_run.py @@ -328,9 +328,13 @@ def _apply_selected_todo_guards( # A compact legacy projection may legitimately omit every boundary field. # Observe the selected workspace without inventing a write grant. goal_boundary = prepared.goal_boundary or {} + captured_workspace: dict[str, Any] = {} local_workspace = observe_goal_local_workspace( - prepared.item, selected_todo, goal_boundary.get("write_scope", []) + prepared.item, selected_todo, goal_boundary.get("write_scope", []), + captured_out=captured_workspace, ) + if captured_workspace: + prepared.captured_local_workspace = captured_workspace if direct_sources is not None: direct_sources["delivery_workspace"] = source_fact( "delivery_workspace", @@ -587,6 +591,7 @@ def build_quota_should_run( authoritative_fallback_todo_items: FallbackTodoSource = None, replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None = None, app_scheduler_state_observer: Callable[[Mapping[str, Any]], None] | None = None, + reuse_fresh_canonical_snapshot: bool = False, ) -> dict[str, Any]: safe_goal_id = str(goal_id or "").strip() direct_sources: dict[str, dict[str, Any]] = {} @@ -681,6 +686,7 @@ def build_quota_should_run( receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, receipt_bound_replan_review=receipt_bound_replan_review, + reuse_fresh_canonical_snapshot=reuse_fresh_canonical_snapshot, ) if runtime_root is not None and turn_instance_id and prepared.agent_frontier_id: prepared.vision_initialization_context = { diff --git a/loopx/control_plane/quota/should_run_packet.py b/loopx/control_plane/quota/should_run_packet.py index 774896699d..a7fad2628d 100644 --- a/loopx/control_plane/quota/should_run_packet.py +++ b/loopx/control_plane/quota/should_run_packet.py @@ -38,9 +38,7 @@ build_agent_scope_frontier_payload, read_frontier_action, ) -from ..goals.goal_frontier import ( - AUTONOMOUS_REPLAN_REQUIRED_MODE, -) +from ..goals.goal_frontier import AUTONOMOUS_REPLAN_REQUIRED_MODE from ..goals.goal_vision_policy import DEFAULT_PLANNING_HORIZON_GOAL from ..quota.decision_summary import ( quota_decision_agent_id, @@ -1716,6 +1714,7 @@ def _build_quota_should_run_payload( payload["delivery_workspace_isolation"] = observe_goal_delivery_workspace_isolation( prepared.item, selected_todo, project_asset=prepared.project_asset, + captured_local_workspace=prepared.captured_local_workspace, ) apply_selected_todo_execution_preparation( payload, diff --git a/loopx/control_plane/quota/should_run_prepare.py b/loopx/control_plane/quota/should_run_prepare.py index 5c8de046b1..650415d75f 100644 --- a/loopx/control_plane/quota/should_run_prepare.py +++ b/loopx/control_plane/quota/should_run_prepare.py @@ -187,6 +187,7 @@ class _QuotaDecisionPreparation: delivery_continuity_anchor: dict[str, Any] | None delivery_continuity_todo: dict[str, Any] | None vision_initialization_context: dict[str, Any] | None = None + captured_local_workspace: dict[str, Any] | None = None @property def inbox_priority_due(self) -> bool: @@ -756,6 +757,7 @@ def _prepare_quota_should_run_item( receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, Any] | None = None, + reuse_fresh_canonical_snapshot: bool = False, ) -> _QuotaDecisionPreparation: quota = cast(dict[str, Any], item.get("quota")) if isinstance(item.get("quota"), dict) else {} state = str(quota.get("state") or "unknown") @@ -783,6 +785,7 @@ def _prepare_quota_should_run_item( project_asset.get("agent_todos") if project_asset else None, agent_identity=agent_identity, available_capabilities=effective_available_capabilities, + reuse_fresh_canonical_snapshot=reuse_fresh_canonical_snapshot, ) # Only this Agent source is consumed as summary, planning and retained # terminal rows below. User-source and general display calls stay single-view. diff --git a/loopx/control_plane/rollout_receipt_log.ts b/loopx/control_plane/rollout_receipt_log.ts index d1f3a8d044..6b9a45e3a6 100644 --- a/loopx/control_plane/rollout_receipt_log.ts +++ b/loopx/control_plane/rollout_receipt_log.ts @@ -12,7 +12,11 @@ import { relative, resolve, sep } from "node:path"; import type { JsonObject } from "./effect_program.ts"; import { EffectRuntimeRequestError } from "./effect_runtime_errors.ts"; import { jsonObject, requireNonEmptyString } from "./runtime_decode.ts"; -import { readReceiptLogSnapshot } from "./runtime/receipt_log_snapshot.ts"; +import { + readReceiptLogSnapshot, + readReceiptLogSnapshotWithStat, + type ReceiptLogStat, +} from "./runtime/receipt_log_snapshot.ts"; export const ROLLOUT_EVENT_SCHEMA_VERSION = "loopx_rollout_event_v0"; export const HEARTBEAT_RECEIPT_EVENT_KIND = "quota_should_run"; @@ -90,25 +94,46 @@ export function goalRolloutEventLogPath( return path; } -/** Read and parse the rollout log once, retaining strict-read diagnostics. */ -export async function readGoalRolloutEventSnapshot( +export interface GoalRolloutEventSnapshotWithStat { + readonly snapshot: GoalRolloutEventSnapshot | null; + readonly logPath: string; + readonly stat: ReceiptLogStat; + readonly stable: boolean; +} + +/** Read and parse the rollout log once, retaining strict-read diagnostics and exact stat. */ +export async function readGoalRolloutEventSnapshotWithStat( runtimeRoot: string, goalId: string, -): Promise { - const snapshot = await readReceiptLogSnapshot( - goalRolloutEventLogPath(runtimeRoot, goalId), +): Promise { + const logPath = goalRolloutEventLogPath(runtimeRoot, goalId); + const result = await readReceiptLogSnapshotWithStat( + logPath, ROLLOUT_EVENT_SCHEMA_VERSION, ADMISSION_IDENTITY_MEMBERS, ); - return snapshot === null ? null : { - runtimeRoot, goalId, events: snapshot.records, - eventLines: snapshot.recordLines, - malformedLines: snapshot.malformedLines, - firstStrictErrorLine: snapshot.firstErrorLine, - unterminatedRecordLine: snapshot.unterminatedRecordLine, + return { + snapshot: result.snapshot === null ? null : { + runtimeRoot, goalId, events: result.snapshot.records, + eventLines: result.snapshot.recordLines, + malformedLines: result.snapshot.malformedLines, + firstStrictErrorLine: result.snapshot.firstErrorLine, + unterminatedRecordLine: result.snapshot.unterminatedRecordLine, + }, + logPath, + stat: result.stat, + stable: result.stable, }; } +/** Read and parse the rollout log once, retaining strict-read diagnostics. */ +export async function readGoalRolloutEventSnapshot( + runtimeRoot: string, + goalId: string, +): Promise { + return (await readGoalRolloutEventSnapshotWithStat(runtimeRoot, goalId)).snapshot; +} + /** * Rows whose writer reached the committing newline. * diff --git a/loopx/control_plane/runtime/receipt_log_snapshot.ts b/loopx/control_plane/runtime/receipt_log_snapshot.ts index e2420af9a8..25b1b56374 100644 --- a/loopx/control_plane/runtime/receipt_log_snapshot.ts +++ b/loopx/control_plane/runtime/receipt_log_snapshot.ts @@ -1,6 +1,7 @@ /** Disposable parsing acceleration; the bytes on disk remain the authority. */ import { createHash } from "node:crypto"; -import { readFile } from "node:fs/promises"; +import type { BigIntStats } from "node:fs"; +import { readFile, stat } from "node:fs/promises"; import { resolve } from "node:path"; import { setImmediate } from "node:timers/promises"; @@ -190,37 +191,156 @@ async function parseThrough( }); } +export type ReceiptLogStat = { + readonly exists: boolean; + readonly dev: string | null; + readonly ino: string | null; + readonly size: number; + readonly mtime_ns: string | null; + readonly ctime_ns: string | null; + readonly mtime_ms: string | null; +}; + +export interface ReceiptLogSnapshotWithStat { + readonly snapshot: ReceiptLogSnapshot | null; + readonly stat: ReceiptLogStat; + readonly stable: boolean; +} + +export const MISSING_RECEIPT_LOG_STAT: ReceiptLogStat = Object.freeze({ + exists: false, + dev: null, + ino: null, + size: 0, + mtime_ns: null, + ctime_ns: null, + mtime_ms: null, +}); + +function formatReceiptLogStat(info: BigIntStats): ReceiptLogStat { + if (info.size < 0n || info.size > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error("receipt log size exceeds safe integer range"); + } + return Object.freeze({ + exists: true, + dev: String(info.dev), + ino: String(info.ino), + size: Number(info.size), + mtime_ns: String(info.mtimeNs), + ctime_ns: String(info.ctimeNs), + mtime_ms: String(info.mtimeMs), + }); +} + +function bigIntStatsMatch(left: BigIntStats, right: BigIntStats): boolean { + return ( + left.dev === right.dev && + left.ino === right.ino && + left.size === right.size && + left.mtimeNs === right.mtimeNs && + left.ctimeNs === right.ctimeNs + ); +} + +async function safePathStat(path: string): Promise { + try { + return await stat(path, { bigint: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return null; + throw error; + } +} + +export function isReceiptLogStat(value: unknown): value is ReceiptLogStat { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const raw = value as Record; + if (typeof raw.exists !== "boolean") return false; + if (typeof raw.size !== "number" || !Number.isSafeInteger(raw.size) || raw.size < 0) return false; + const optionalString = (item: unknown) => item === null || typeof item === "string"; + return ( + optionalString(raw.dev) && + optionalString(raw.ino) && + optionalString(raw.mtime_ns) && + optionalString(raw.ctime_ns) && + optionalString(raw.mtime_ms) + ); +} + +export function receiptLogStatsEqual(left: ReceiptLogStat, right: ReceiptLogStat): boolean { + return ( + left.exists === right.exists && + left.dev === right.dev && + left.ino === right.ino && + left.size === right.size && + left.mtime_ns === right.mtime_ns && + left.ctime_ns === right.ctime_ns && + left.mtime_ms === right.mtime_ms + ); +} + +export async function statReceiptLog(path: string): Promise { + const info = await safePathStat(path); + return info === null ? MISSING_RECEIPT_LOG_STAT : formatReceiptLogStat(info); +} + /** - * Read fresh bytes on EVERY invocation. Only reuse a parsed newline-terminated - * prefix after hashing those exact bytes. Rewrites, rotation, truncation and - * same-size edits all remain observable, including edits to an old - * identity-conflicting receipt. + * Read fresh bytes on EVERY invocation and bind the returned stat strictly to + * the exact open file descriptor snapshot consumed during parsing. + * Only reuse a parsed newline-terminated prefix after hashing those exact bytes. + * Rewrites, rotation, truncation and same-size edits all remain observable, + * including edits to an old identity-conflicting receipt. * Never cache an unterminated tail: an append can finish its UTF-8 character or * JSON token. The tail still participates in this read, including strict errors. * Cache loss/eviction/restart affects cost only, never the returned facts. */ -export async function readReceiptLogSnapshot( +export async function readReceiptLogSnapshotWithStat( path: string, schemaVersion?: string, recoveryKeys: readonly string[] = [], -): Promise { +): Promise { const key = JSON.stringify([resolve(path), schemaVersion ?? null, recoveryKeys]); + const pre = await safePathStat(path); let bytes: Buffer; try { bytes = await readFile(path); } catch (error) { forget(key); - if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + const postMissing = await safePathStat(path); + return { + snapshot: null, + stat: MISSING_RECEIPT_LOG_STAT, + stable: pre === null && postMissing === null, + }; + } throw error; } + const post = await safePathStat(path); + const stable = + pre !== null && + post !== null && + bigIntStatsMatch(pre, post) && + BigInt(bytes.length) === pre.size; + const consumedStat = stable ? formatReceiptLogStat(pre) : MISSING_RECEIPT_LOG_STAT; + const snapshot = await decodeReceiptLogBytes(bytes, key, schemaVersion, recoveryKeys, stable); + return { snapshot, stat: consumedStat, stable }; +} + +async function decodeReceiptLogBytes( + bytes: Buffer, + key: string, + schemaVersion: string | undefined, + recoveryKeys: readonly string[], + stable: boolean, +): Promise { // Each caller owns a fresh read. Only coalesce large, byte-identical reads // with the same decode contract while the original parse is still running. - if (bytes.length < 1024 * 1024 || bytes.length > MAX_RETAINED_BYTES) { - return parseSnapshot(bytes, key, schemaVersion, recoveryKeys); + if (!stable || bytes.length < 1024 * 1024 || bytes.length > MAX_RETAINED_BYTES) { + return parseSnapshot(bytes, key, schemaVersion, recoveryKeys, stable); } const active = decoding.get(key); if (active && bytes.equals(active.bytes)) return active.result; - const result = parseSnapshot(bytes, key, schemaVersion, recoveryKeys); + const result = parseSnapshot(bytes, key, schemaVersion, recoveryKeys, true); if (active || decoding.size >= MAX_RETAINED_LOGS) return result; decoding.set(key, { bytes, result }); try { @@ -230,8 +350,26 @@ export async function readReceiptLogSnapshot( } } +export async function readReceiptLogSnapshot( + path: string, + schemaVersion?: string, + recoveryKeys: readonly string[] = [], +): Promise { + const key = JSON.stringify([resolve(path), schemaVersion ?? null, recoveryKeys]); + let bytes: Buffer; + try { + bytes = await readFile(path); + } catch (error) { + forget(key); + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } + return decodeReceiptLogBytes(bytes, key, schemaVersion, recoveryKeys, true); +} + async function parseSnapshot( bytes: Buffer, key: string, schemaVersion: string | undefined, recoveryKeys: readonly string[], + rememberPrefix = true, ): Promise { const completeBytes = bytes.lastIndexOf(10) + 1; const prior = prefixes.get(key); @@ -257,7 +395,7 @@ async function parseSnapshot( ...await parseThrough(bytes, retainedEnd, reusable, schemaVersion, recoveryKeys), digest: retainedDigest ?? digest(bytes.subarray(0, retainedEnd)), }); - remember(key, retained); + if (rememberPrefix) remember(key, retained); const prefix = retainedEnd === completeBytes ? retained : await parseThrough(bytes, completeBytes, retained, schemaVersion, recoveryKeys); const tail = strictUtf8(bytes.subarray(completeBytes)); diff --git a/loopx/control_plane/status/attention_projection.py b/loopx/control_plane/status/attention_projection.py index 8aa20cf734..f860048b75 100644 --- a/loopx/control_plane/status/attention_projection.py +++ b/loopx/control_plane/status/attention_projection.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Sequence +from functools import partial from typing import Any from ..todos.contract import ( @@ -37,7 +38,7 @@ def autonomous_backlog_candidates( ) -> dict[str, Any] | None: return _autonomous_backlog_candidates( items, - open_todo_items=open_todo_items, + open_todo_items=partial(open_todo_items, include_handoff_note=False), todo_item_is_actionable_open=todo_item_is_actionable_open, normalize_todo_text=normalize_todo_text, advancement_task_class=TODO_TASK_CLASS_ADVANCEMENT, @@ -52,7 +53,7 @@ def autonomous_monitor_candidates( ) -> dict[str, Any] | None: return _autonomous_monitor_candidates( items, - open_todo_items=open_todo_items, + open_todo_items=partial(open_todo_items, include_handoff_note=False), todo_item_is_actionable_open=todo_item_is_actionable_open, normalize_todo_text=normalize_todo_text, monitor_task_class=TODO_TASK_CLASS_MONITOR, diff --git a/loopx/control_plane/status/monitor_display_projection.py b/loopx/control_plane/status/monitor_display_projection.py index 824a1bfbc4..f44f65c43c 100644 --- a/loopx/control_plane/status/monitor_display_projection.py +++ b/loopx/control_plane/status/monitor_display_projection.py @@ -2,6 +2,7 @@ from __future__ import annotations +from functools import partial from typing import Any, Literal from ..scheduler.monitor_display import ( @@ -59,7 +60,7 @@ def build_project_asset( def todo_summary_open_count(summary: dict[str, Any] | None) -> int: return _todo_summary_open_count( summary, - open_todo_items=open_todo_items, + open_todo_items=partial(open_todo_items, include_handoff_note=False), todo_item_is_actionable_open=todo_item_is_actionable_open, fallback_limit=MAX_STATUS_TODOS_PER_ROLE, ) @@ -72,7 +73,7 @@ def todo_summary_lane_items(summary: dict[str, Any] | None, lane: str) -> list[d def attention_item_is_monitor_quiet_display_candidate(item: dict[str, Any]) -> bool: return _attention_item_is_monitor_quiet_display_candidate( item, - open_todo_items=open_todo_items, + open_todo_items=partial(open_todo_items, include_handoff_note=False), todo_item_is_actionable_open=todo_item_is_actionable_open, fallback_limit=MAX_STATUS_TODOS_PER_ROLE, ) diff --git a/loopx/control_plane/todos/goal_todo_projection.py b/loopx/control_plane/todos/goal_todo_projection.py index 3dcea4291e..f4d3bf5914 100644 --- a/loopx/control_plane/todos/goal_todo_projection.py +++ b/loopx/control_plane/todos/goal_todo_projection.py @@ -307,7 +307,8 @@ def project_todo_read(params: dict[str, Any]) -> dict[str, Any]: raise ValueError("invalid Todo read result continuation") request = {**request, "result_page": after} except EffectRuntimeRejected as exc: - raise ValueError(str(exc)) from exc + from .quota_selection import raise_quota_runtime_rejection + raise_quota_runtime_rejection(exc, cause=exc) if not isinstance(result, dict) or result.get("schema_version") != "todo_read_result_v0": raise ValueError("invalid typed Todo read result") if result.get("rejection"): diff --git a/loopx/control_plane/todos/handoff_gate.py b/loopx/control_plane/todos/handoff_gate.py index 2c54fd0772..d5e93a5c27 100644 --- a/loopx/control_plane/todos/handoff_gate.py +++ b/loopx/control_plane/todos/handoff_gate.py @@ -122,6 +122,8 @@ def todo_summary_handoff_gates(value: dict[str, Any]) -> list[dict[str, Any]]: projected = value.get("handoff_gates") if isinstance(projected, list): return [item for item in projected if isinstance(item, dict)] + if getattr(value, "handoff_gates_evaluated", False): + return [] raw_items = value.get("items") source_items = raw_items if isinstance(raw_items, list) else [] return build_todo_handoff_gate_states(source_items) diff --git a/loopx/control_plane/todos/handoff_note.py b/loopx/control_plane/todos/handoff_note.py index 299fb84d0c..c5b8a471ff 100644 --- a/loopx/control_plane/todos/handoff_note.py +++ b/loopx/control_plane/todos/handoff_note.py @@ -117,6 +117,8 @@ def attach_todo_handoff_note(item: dict[str, Any], *, goal_id: str | None = None def attach_todo_handoff_notes(items: list[dict[str, Any]]) -> list[dict[str, Any]]: + if not items: + return items results = project_handoff_context([todo_read_source(item) for item in items]) for item, result in zip(items, results, strict=True): if result["note"]: diff --git a/loopx/control_plane/todos/list_readback.py b/loopx/control_plane/todos/list_readback.py index 233b94cec7..ef24927a9c 100644 --- a/loopx/control_plane/todos/list_readback.py +++ b/loopx/control_plane/todos/list_readback.py @@ -10,10 +10,8 @@ from ..projects.registry_codec import load_registry from ..runtime.runtime_projection_route import resolve_goal_source_runtime_route -from ...rollout_event_log import load_rollout_events, rollout_event_log_path from ..goals.state_resolution import resolve_goal_state from .contract import normalize_todo_claimed_by, normalize_todo_id, normalize_todo_status -from .todo_index import MAX_TODO_INDEX_ROLLOUT_EVENTS_PER_GOAL from .resume_condition import TodoResumeRolloutEvents @@ -78,12 +76,7 @@ def list_goal_todos( raise ValueError(f"goal {goal_id!r} is not present in the registry") runtime_root = Path(route["source_runtime_root"]) - rollout_events = load_rollout_events( - rollout_event_log_path(runtime_root, goal_id), - limit=MAX_TODO_INDEX_ROLLOUT_EVENTS_PER_GOAL, - ) - - rollout_events = TodoResumeRolloutEvents(rollout_events, runtime_root=runtime_root, goal_id=goal_id) + rollout_events = TodoResumeRolloutEvents([], runtime_root=runtime_root, goal_id=goal_id) from ..coordination.local_authority import CanonicalAuthorityRequired, LocalCoordinationAuthorityUnavailable from .goal_todo_projection import project_todo_read diff --git a/loopx/control_plane/todos/pr_wait_observation.ts b/loopx/control_plane/todos/pr_wait_observation.ts index 98dd148ad1..1ac88aabf8 100644 --- a/loopx/control_plane/todos/pr_wait_observation.ts +++ b/loopx/control_plane/todos/pr_wait_observation.ts @@ -109,6 +109,6 @@ export function planPrWaitObservations(value: unknown): JsonObject { export async function planPrWaitObservationsFromSource(value: unknown): Promise { const request = requireJsonObject(value, "PR wait observation request"); const plan = planPrWaitObservations(request); // Validate before reading local state. - if (request.rollout_event_source === undefined) return plan; + if (request.rollout_event_source === undefined || !(plan.waiting_targets as unknown[]).length) return plan; return planPrWaitObservations({...request, rollout_events: [...await readTodoResumeRolloutEvents(request)]}); } diff --git a/loopx/control_plane/todos/quota_selection.py b/loopx/control_plane/todos/quota_selection.py index d78078f5af..78bd6f3c97 100644 --- a/loopx/control_plane/todos/quota_selection.py +++ b/loopx/control_plane/todos/quota_selection.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Any, cast +from typing import Any, NoReturn, cast import json @@ -30,6 +30,19 @@ from .handoff_gate import todo_summary_handoff_gates +class StaleCanonicalQuotaSourceError(ValueError): + """Canonical Todo or rollout-log snapshot changed after initial collection.""" + + +def raise_quota_runtime_rejection( + exc: EffectRuntimeRejected, *, cause: BaseException | None = None, +) -> NoReturn: + """Preserve typed stale-source rejections without substring classification.""" + if exc.diagnostic_code == "quota_canonical_source_changed": + raise StaleCanonicalQuotaSourceError(str(exc)) from cause + raise ValueError(str(exc)) from cause + + def _closure_source_facts(value: dict[str, Any]) -> dict[str, Any]: # JSON erases Python's int/float distinction. Retain the strict integer # evidence type before transport; the typed owner decides validity. @@ -117,6 +130,7 @@ def project_quota_planning( summary_kind: str | None = None, consume_display_views: bool = False, request_only: bool = False, display_view_names: list[str] | None = None, + include_source_reference: bool = True, ) -> dict[str, Any]: identity = agent_identity if isinstance(agent_identity, dict) else {} profile = identity.get("agent_profile") @@ -170,7 +184,7 @@ def integer_text(raw: Any) -> str | None: return None from .summary_item import canonical_todo_source_reference - reference = canonical_todo_source_reference(value) if summary_kind else None + reference = canonical_todo_source_reference(value) if summary_kind and include_source_reference else None resume_request = None if reference is not None or request_only else build_referenced_todo_resume_planning_request( value, agent_id=agent, @@ -231,7 +245,7 @@ def integer_text(raw: Any) -> str | None: else: wire = effect_runtime_result("todo.quota_planning.project", request, large_local_snapshot=True) except EffectRuntimeRejected as exc: - raise ValueError(str(exc)) from None + raise_quota_runtime_rejection(exc) if summary_kind: return _decode_quota_summary_wire(wire, value) result = _decode_quota_planning_wire(wire) @@ -310,3 +324,49 @@ def child(parent: Any, key: Any) -> Any: "first_open_items", "first_executable_items", "monitor_open_items", "backlog_items"))): raise RuntimeError(error) return summary + + +def collect_quota_authority_checks(sources: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Build head-verification checks for small already-loaded canonical snapshots.""" + from .summary_item import canonical_todo_authority_check, canonical_todo_source_reference + + checks: list[dict[str, Any]] = [] + for source in sources: + items = source.get("items") + if isinstance(items, list) and len(items) > 500: + return [] + check = canonical_todo_authority_check(source) + if check is None or canonical_todo_source_reference(source) is None: + return [] + checks.append(check) + return checks + + +def project_quota_wires_with_head_checks( + requests: list[Any], *, authority_checks: list[dict[str, Any]], error: str, +) -> list[object]: + """Batch quota planning over loaded summaries after checking live TS authority/log stat.""" + from ..coordination.local_authority import validate_canonical_todo_read + + try: + result = effect_runtime_result( + "todo.quota_planning.project", + { + "schema_version": "todo_quota_planning_batch_v0", + "authority_checks": authority_checks, + "requests": requests, + }, + large_local_snapshot=True, + ) + except EffectRuntimeRejected as exc: + raise_quota_runtime_rejection(exc, cause=exc) + if isinstance(result, dict) and result.get("canonical") is not None: + first_read = cast(dict[str, Any], authority_checks[0]["read"]) + first_source = cast(dict[str, Any], first_read["source"]) + validate_canonical_todo_read(result["canonical"], goal_id=str(first_source["goal_id"])) + if not isinstance(result, dict) or result.get("schema_version") != "todo_quota_planning_batch_result_v0": + raise RuntimeError(error) + wires = result.get("quota_wires") + if not isinstance(wires, list) or len(wires) != len(requests): + raise RuntimeError(error) + return cast(list[object], wires) diff --git a/loopx/control_plane/todos/quota_summary.py b/loopx/control_plane/todos/quota_summary.py index b21d498e2d..116527c93c 100644 --- a/loopx/control_plane/todos/quota_summary.py +++ b/loopx/control_plane/todos/quota_summary.py @@ -7,7 +7,10 @@ from ..goals.goal_vision_policy import COMPLETED_TODO_CHAIN_REPLAN_THRESHOLD from ..runtime.time import now_utc from .frontier_deadline import todo_summary_frontier_deadline -from .quota_selection import project_quota_planning +from .quota_selection import ( + _decode_quota_summary_wire, collect_quota_authority_checks, + project_quota_planning, project_quota_wires_with_head_checks, +) from .summary_item import todo_planning_source_items, todo_summary_source_items Payload = dict[str, object] @@ -19,25 +22,12 @@ QUOTA_PAYLOAD_USER_ACTION_ITEM_LIMIT = 3 QUOTA_PAYLOAD_DIAGNOSTIC_LANE_LIMIT = 2 QUOTA_PAYLOAD_COMPACTION_SCHEMA_VERSION = "quota_todo_summary_payload_compaction_v0" -AGENT_LANE_STATUS_TODO_COMPACTION_SCHEMA_VERSION = ( - "agent_lane_status_todo_summary_compaction_v1" -) -AGENT_LANE_STATUS_TODO_REFERENCE_SCHEMA_VERSION = ( - "agent_lane_status_todo_reference_v0" -) +AGENT_LANE_STATUS_TODO_COMPACTION_SCHEMA_VERSION = "agent_lane_status_todo_summary_compaction_v1" +AGENT_LANE_STATUS_TODO_REFERENCE_SCHEMA_VERSION = "agent_lane_status_todo_reference_v0" QUOTA_PAYLOAD_ITEM_FIELDS = ( - "goal_acceptance_guard", - "schema_version", - "index", - "text", - "title", - "todo_id", - "status", - "priority", - "task_class", - "action_kind", - "task_domain", - "decision_scope", + "goal_acceptance_guard", "schema_version", "index", "text", "title", + "todo_id", "status", "priority", "task_class", "action_kind", + "task_domain", "decision_scope", "required_decision_scopes", "task_repository", "continuation_policy", @@ -450,7 +440,8 @@ def _quota_projection_request( source: Payload, *, agent_identity: PayloadView | None, filter_user_gate_blocks_agent: bool, available_capabilities: object = None, resolve_capacity: bool = False, summary_kind: str = "user", - consume_display_views: bool = False, display_view_names: list[str] | None = None, + consume_display_views: bool = False, + display_view_names: list[str] | None = None, include_source_reference: bool = True, ) -> Payload: return cast(Payload, project_quota_planning( source, all_open_items=[], source_open_count=source.get("open_count"), @@ -459,6 +450,7 @@ def _quota_projection_request( available_capabilities=available_capabilities, resolve_capacity=resolve_capacity, summary_kind=summary_kind, consume_display_views=consume_display_views, request_only=True, display_view_names=display_view_names, + include_source_reference=include_source_reference, )) @@ -551,32 +543,32 @@ def select_quota_todo_summaries_with_terminal( def select_quota_todo_contexts( user_canonical: object, user_asset: object, agent_canonical: object, agent_asset: object, *, agent_identity: PayloadView | None, available_capabilities: object, + reuse_fresh_canonical_snapshot: bool = False, ) -> tuple[Payload | None, Payload | None, dict[str, list[Payload]], list[Payload]]: """The quota caller explicitly consumes both summaries and Agent displays. One native read transaction materializes each complete source. A supplied compatibility source retains its full codec and cannot acquire authority. """ - from .quota_selection import _decode_quota_summary_wire from .summary_item import _QuotaProjectedSummary - values: list[Payload] = [] - roles: list[str] = [] + selected = [ + (role, *pair) for role, c, a in (("user", user_canonical, user_asset), ("agent", agent_canonical, agent_asset)) + if (pair := _select_todo_source(c, a)) is not None + ] + values = [source for _, _, source in selected] + roles = [role for role, _, _ in selected] + authority_checks = ( + collect_quota_authority_checks(values) + if reuse_fresh_canonical_snapshot and selected else [] + ) requests: list[Payload] = [] - for role, canonical, asset in ( - ("user", user_canonical, user_asset), - ("agent", agent_canonical, agent_asset), - ): - selected = _select_todo_source(canonical, asset) - if selected is None: - continue - kind, source = selected - values.append(source) - roles.append(role) + for role, kind, source in selected: request = _quota_projection_request( source, agent_identity=agent_identity, filter_user_gate_blocks_agent=role == "user", available_capabilities=available_capabilities, resolve_capacity=True, summary_kind=kind, consume_display_views=role == "agent", + include_source_reference=not authority_checks, ) summary_req = _as_dict(request.get("summary_request")) if summary_req is not None: @@ -587,7 +579,11 @@ def select_quota_todo_contexts( views: dict[str, list[Payload]] = {"summary": [], "planning": [], "terminal": []} user_rows: list[Payload] = [] if requests: - wires = _project_quota_wires(requests, error="invalid complete quota projection response") + error = "invalid complete quota projection response" + wires = ( + project_quota_wires_with_head_checks(requests, authority_checks=authority_checks, error=error) + if authority_checks else _project_quota_wires(requests, error=error) + ) for role, source, wire in zip(roles, values, wires, strict=True): summaries[role] = cast(Payload, _decode_quota_summary_wire(wire, source)) wire_dict = _as_dict(wire) diff --git a/loopx/control_plane/todos/read_projection.ts b/loopx/control_plane/todos/read_projection.ts index d25f992f64..f2f9cf9cb8 100644 --- a/loopx/control_plane/todos/read_projection.ts +++ b/loopx/control_plane/todos/read_projection.ts @@ -9,7 +9,7 @@ import type {JsonObject} from "../effect_program.ts"; import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; import {requireJsonObject, requireBoolean} from "../runtime_decode.ts"; import {schedulerTimestampMilliseconds} from "../scheduler/state_store.ts"; -import {evaluateTodoResumeConditionsFromSource} from "./resume_condition.ts"; +import {evaluateTodoResumeConditionsFromSource, type TodoResumeRolloutReadOptions} from "./resume_condition.ts"; import {readTodoPriority, todoPriorityRank} from "./priority.ts"; import {evaluateTodoSuccession, validateTodoSuccession, SUCCESSION_CONTEXT_FIELDS} from "./succession.ts"; import {projectTodoSummary} from "./summary_projection.ts"; @@ -170,7 +170,10 @@ function projectCapabilityActions( }; } -export async function projectTodoReadGroup(input: JsonObject): Promise { +export async function projectTodoReadGroup( + input: JsonObject, + options?: TodoResumeRolloutReadOptions, +): Promise { if (!Array.isArray(input.items) || !Array.isArray(input.lineage)) throw new EffectRuntimeRequestError("Todo read requires complete source arrays"); const items = input.items.map(value => ({...requireJsonObject(value, "Todo read item")})); const lineage = input.lineage.map(value => requireJsonObject(value, "Todo read lineage")); @@ -192,7 +195,7 @@ export async function projectTodoReadGroup(input: JsonObject): Promise [row.todo_id, row.condition])); for (const item of waiting) { item.resume_condition = conditions.get(item.todo_id) ?? {schema_version: "todo_resume_condition_v0", resume_when: item.resume_when!, satisfied: false, unsupported: true}; @@ -261,7 +264,10 @@ export async function projectTodoReadGroup(input: JsonObject): Promise [name, ordinals.map(i => compacts[i]!)]))}; } -export async function projectCanonicalTodoFields(input: JsonObject): Promise { +export async function projectCanonicalTodoFields( + input: JsonObject, + options?: TodoResumeRolloutReadOptions, +): Promise { if (!Array.isArray(input.todos)) throw new EffectRuntimeRequestError("canonical Todo read source must be an array"); const original = input.todos.map(value => requireJsonObject(value, "canonical Todo source")); const decisions = original.filter(row => row.role === "user"); @@ -285,7 +291,7 @@ export async function projectCanonicalTodoFields(input: JsonObject): Promise readResume(row.resume_when)) - ? all.map(row => structureCanonicalTodo(row, row.role ?? null, row.source_section ?? section)) : []}); + ? all.map(row => structureCanonicalTodo(row, row.role ?? null, row.source_section ?? section)) : []}, options); if (grouped.rejection) return grouped; const summary = requireJsonObject(grouped.summary, "canonical Todo summary"); if (role === "agent" && input.retained !== true) { diff --git a/loopx/control_plane/todos/read_transaction.ts b/loopx/control_plane/todos/read_transaction.ts index 9603109140..365a9e09ee 100644 --- a/loopx/control_plane/todos/read_transaction.ts +++ b/loopx/control_plane/todos/read_transaction.ts @@ -12,10 +12,17 @@ import {compactTodoReadSummary, compactThinTodoRead, compactTodoQueueSummary, to import {projectTodoContextPage, SUMMARY_SOURCES, PLANNING_SOURCES} from "./context_projection.ts"; import {SOURCE_KEYS as RESUME_SOURCES} from "./resume_planning.ts"; import {sealProjectionEnvelope, PROJECTION_ENVELOPE_SEAL_REQUEST} from "../projection_envelope.ts"; -import {canonicalAuthoritySha256, canonicalAuthorityJson} from "../coordination/authority_store_codec.ts"; +import {canonicalAuthoritySha256, canonicalAuthorityJson, requireAuthorityStoreId} from "../coordination/authority_store_codec.ts"; import {decodeTodoReadSource} from "./read_codec.ts"; import {projectTodoQuotaPlanning} from "./quota_selection.ts"; -import type {LocalAuthorityProviderDependencies} from "../coordination/local_authority_provider.ts"; +import {authorityStoreSourceAuthority as sourceAuthorityFor, readAuthoritySnapshot} from "../coordination/authority_store.ts"; +import {canonicalAuthorityRouteFailure, requireCanonicalAuthority} from "../coordination/local_authority_write.ts"; +import {localAuthorityOpenFailure, openRuntimeAuthorityStore as openRuntimeStore, + requireLocalAuthorityRuntimeRoot as runtimeRoot, + type LocalAuthorityProviderDependencies} from "../coordination/local_authority_provider.ts"; +import {goalRolloutEventLogPath} from "../rollout_receipt_log.ts"; +import {isReceiptLogStat, receiptLogStatsEqual, statReceiptLog, type ReceiptLogStat} from "../runtime/receipt_log_snapshot.ts"; +import type {RolloutLogReadWitness} from "./resume_condition.ts"; const includesArchivedRows = (query: JsonObject): boolean => query.read_scope === "completed_history" || query.include_archived === true; @@ -38,9 +45,15 @@ export async function readCanonicalTodoProjection(input: JsonObject, dependencie const query = requireJsonObject(input.query ?? {}, "Todo query"); const includeArchived = includesArchivedRows(query); const retained = query.read_scope === "completed_history"; + const expectedLogPath = (typeof source.runtime_root === "string" && typeof source.goal_id === "string") + ? goalRolloutEventLogPath(source.runtime_root, source.goal_id) + : null; + const preProjectionStat = expectedLogPath !== null ? await statReceiptLog(expectedLogPath) : undefined; + const rolloutReads: RolloutLogReadWitness[] = []; let projected = await projectCanonicalTodoFields({...input, todos, retained, include_archived: includeArchived, goal_acceptance_contract: canonical.goal_acceptance_contract ?? null, - goal_acceptance_work_guards: guards}); + goal_acceptance_work_guards: guards}, + {onRolloutLogRead: witness => rolloutReads.push(witness)}); if (input.read_pipeline !== undefined) { if (input.kind !== "canonical_fields" || input.query != null || !Array.isArray(input.read_pipeline) || !input.read_pipeline.length) { throw new EffectRuntimeRequestError("Todo select pipeline requires a complete canonical read"); @@ -77,10 +90,25 @@ export async function readCanonicalTodoProjection(input: JsonObject, dependencie const {canonical_contract_fields: _contractFields, read_observed_at: _readObserved, ...replayRead} = input; replay = {replay_read: replayRead}; } + let rolloutLogStat: ReceiptLogStat | undefined; + if (projected.fields && !projected.rejection && expectedLogPath !== null) { + const postProjectionStat = await statReceiptLog(expectedLogPath); + if (rolloutReads.length > 0) { + if (rolloutReads.every(witness => + witness.stable && witness.logPath === expectedLogPath && + receiptLogStatsEqual(witness.stat, postProjectionStat) + )) { + rolloutLogStat = rolloutReads[0]!.stat; + } + } else if (preProjectionStat !== undefined && receiptLogStatsEqual(preProjectionStat, postProjectionStat)) { + rolloutLogStat = preProjectionStat; + } + } return { ...(input.return_projection === true && projected.projection ? {schema_version: TODO_READ_RESULT, projection: projected.projection, field_evaluations: projected.field_evaluations} : {...projected, canonical: canonicalResult}), + ...(rolloutLogStat !== undefined ? {rollout_log_stat: rolloutLogStat} : {}), ...(projected.fields && !projected.rejection ? {source_projection: {source_row_fields: [...canonicalSourceRows], source: Object.fromEntries(["source_authority", "store_identity", "provider_revision", "cursor"].map(key => [key, canonical[key]])), ...replay, field_digests: Object.fromEntries(Object.entries(requireJsonObject(projected.fields, "Todo fields")) @@ -92,7 +120,7 @@ export async function readCanonicalTodoProjection(input: JsonObject, dependencie function validateCanonicalSource(canonical: JsonObject, expected: JsonObject): void { if (canonical.status !== "loaded" || Object.keys(expected).length !== 4 || ["source_authority", "store_identity", "provider_revision", "cursor"].some(field => expected[field] !== canonical[field])) { - throw new EffectRuntimeRequestError("quota canonical source changed; restart the complete guarded read"); + throw new EffectRuntimeRequestError("quota canonical source changed; restart the complete guarded read", "quota_canonical_source_changed"); } } @@ -105,7 +133,7 @@ function resolveCanonicalSource(fields: JsonObject, reference: JsonObject, expec } const field = requireJsonObject(fields[reference.field], "quota source field"); if ((fieldDigests?.[reference.field] ?? canonicalAuthoritySha256(field)) !== reference.field_sha256) { - throw new EffectRuntimeRequestError("quota source projection no longer matches the original complete read"); + throw new EffectRuntimeRequestError("quota source projection no longer matches the original complete read", "quota_canonical_source_changed"); } const record = JSON.parse(JSON.stringify(field)) as JsonObject; if (!Array.isArray(reference.changes)) throw new EffectRuntimeRequestError("quota source changes must be an array"); @@ -155,6 +183,140 @@ function resolveCanonicalSource(fields: JsonObject, reference: JsonObject, expec return decodeTodoReadSource({record, python_values: reference.python_values ?? []}); } +const EXPECTED_WITNESS_FIELDS = ["source_authority", "provider_revision", "cursor"] as const; + +async function loadCanonicalAuthorityHeadWitness( + rawRuntimeRoot: unknown, + rawGoalId: unknown, + dependencies: LocalAuthorityProviderDependencies = {}, +): Promise<{ok: true; goalId: string; head: JsonObject} | {ok: false; canonical: JsonObject}> { + let sourceAuthority = "file_v0"; + try { + const root = runtimeRoot(rawRuntimeRoot); + const goalId = requireAuthorityStoreId(rawGoalId, "goal id"); + await requireCanonicalAuthority(root, goalId, "todo_read"); + const store = await openRuntimeStore(root, goalId, dependencies); + sourceAuthority = sourceAuthorityFor(store); + const {identity, authority} = await readAuthoritySnapshot(store); + if (identity.status !== "available") { + return {ok: false, canonical: { + ...identity, schema_version: LOCAL_COORDINATION_TODO_LIST_RESULT_SCHEMA, + source_authority: sourceAuthority, decision_read_from_provider: true, legacy_fallback_used: false}}; + } + if (authority.status !== "loaded") { + return {ok: false, canonical: { + ...authority, schema_version: LOCAL_COORDINATION_TODO_LIST_RESULT_SCHEMA, + source_authority: sourceAuthority, decision_read_from_provider: true, legacy_fallback_used: false}}; + } + return { + ok: true, + goalId, + head: { + status: "loaded", + source_authority: sourceAuthority, + store_identity: identity.store_identity, + provider_revision: authority.provider_revision, + cursor: authority.cursor, + }, + }; + } catch (error) { + if (error instanceof EffectRuntimeRequestError) throw error; + return {ok: false, canonical: { + schema_version: LOCAL_COORDINATION_TODO_LIST_RESULT_SCHEMA, + status: "failed", + reason_code: "canonical_snapshot_unavailable", + reason: error instanceof Error ? error.message : "invalid authority check", + source_authority: sourceAuthority, + decision_read_from_provider: true, + legacy_fallback_used: false, + ...localAuthorityOpenFailure(error), + ...canonicalAuthorityRouteFailure(error)}}; + } +} + +/** Verify whether the live canonical Todo head revision and cursor match a previously captured witness. */ +export async function verifyCanonicalTodoAuthorityWitness( + value: unknown, + dependencies: LocalAuthorityProviderDependencies = {}, +): Promise { + const input = requireJsonObject(value, "Todo authority witness verification"); + if (input.schema_version !== "todo_authority_head_verify_v0") { + throw new EffectRuntimeRequestError("Todo authority witness schema mismatch"); + } + const rawExpected = input.expected_witness; + if (typeof rawExpected !== "object" || rawExpected === null || Array.isArray(rawExpected)) { + return {schema_version: "todo_authority_head_verify_result_v0", fresh: false, reason_code: "expected_witness_incomplete"}; + } + const expected = rawExpected as JsonObject; + if (!EXPECTED_WITNESS_FIELDS.every(key => typeof expected[key] === "string" && (expected[key] as string).trim() !== "")) { + return {schema_version: "todo_authority_head_verify_result_v0", fresh: false, reason_code: "expected_witness_incomplete"}; + } + try { + const live = await loadCanonicalAuthorityHeadWitness(input.runtime_root, input.goal_id, dependencies); + if (!live.ok) { + return {schema_version: "todo_authority_head_verify_result_v0", fresh: false, reason_code: String(live.canonical.reason_code ?? "canonical_head_unavailable")}; + } + const matches = EXPECTED_WITNESS_FIELDS.every(key => live.head[key] === expected[key]) && + (expected.store_identity === undefined || live.head.store_identity === expected.store_identity); + return { + schema_version: "todo_authority_head_verify_result_v0", + fresh: matches, + reason_code: matches ? "matched" : "canonical_witness_drifted", + source_authority: live.head.source_authority, + provider_revision: live.head.provider_revision, + cursor: live.head.cursor, + }; + } catch { + return {schema_version: "todo_authority_head_verify_result_v0", fresh: false, reason_code: "canonical_witness_check_failed"}; + } +} + +/** Batch quota planning from already-loaded canonical summaries after checking + * the live authority head and rollout log stat against mutation/unavailability. */ +export async function projectCanonicalQuotaBatch( + value: unknown, + dependencies: LocalAuthorityProviderDependencies = {}, +): Promise { + const input = requireJsonObject(value, "quota planning batch"); + if (input.schema_version !== "todo_quota_planning_batch_v0") { + throw new EffectRuntimeRequestError("quota planning batch schema mismatch"); + } + if (!Array.isArray(input.requests) || !input.requests.length || input.requests.length > 2) { + throw new EffectRuntimeRequestError("quota planning batch requires one or two requests"); + } + if (!Array.isArray(input.authority_checks) || !input.authority_checks.length || input.authority_checks.length > 2) { + throw new EffectRuntimeRequestError("quota planning batch requires explicit authority checks"); + } + const verified = new Set(); + for (const rawCheck of input.authority_checks) { + const check = requireJsonObject(rawCheck, "quota authority check"); + const read = requireJsonObject(check.read, "quota source read"); + if (read.kind !== "canonical_fields" || read.query != null || read.canonical_contract_fields !== undefined) { + throw new EffectRuntimeRequestError("quota source requires the original complete canonical read"); + } + const source = requireJsonObject(read.source, "quota source"); + const expected = requireJsonObject(check.expected_source, "quota source identity"); + const dedupeKey = JSON.stringify(canonicalAuthorityJson({ + runtime_root: source.runtime_root, goal_id: source.goal_id, expected, + rollout_log_stat: check.rollout_log_stat ?? null, + })); + if (verified.has(dedupeKey)) continue; + const live = await loadCanonicalAuthorityHeadWitness(source.runtime_root, source.goal_id, dependencies); + if (!live.ok) return {schema_version: TODO_READ_RESULT, canonical: live.canonical}; + validateCanonicalSource(live.head, expected); + if (!isReceiptLogStat(check.rollout_log_stat)) { + throw new EffectRuntimeRequestError("quota canonical source changed; restart the complete guarded read", "quota_canonical_source_changed"); + } + const currentStat = await statReceiptLog(goalRolloutEventLogPath(String(source.runtime_root), live.goalId)); + if (!receiptLogStatsEqual(currentStat, check.rollout_log_stat)) { + throw new EffectRuntimeRequestError("quota canonical source changed; restart the complete guarded read", "quota_canonical_source_changed"); + } + verified.add(dedupeKey); + } + const wires = input.requests.map(request => projectTodoQuotaPlanning(request)); + return {schema_version: "todo_quota_planning_batch_result_v0", quota_wires: wires}; +} + /** Resolve complete source differences against one freshly validated provider * revision. Nothing is retained between RPCs; supplied evidence remains supplied. */ export async function readCanonicalQuotaProjection(input: JsonObject, dependencies: LocalAuthorityProviderDependencies = {}): Promise { diff --git a/loopx/control_plane/todos/resume_condition.ts b/loopx/control_plane/todos/resume_condition.ts index 67ca144631..7ab66ae9a7 100644 --- a/loopx/control_plane/todos/resume_condition.ts +++ b/loopx/control_plane/todos/resume_condition.ts @@ -1,7 +1,8 @@ import { createHash } from "node:crypto"; import { completionDependencyCycles } from "./completion_dependency.ts"; -import { readGoalRolloutEventSnapshot } from "../rollout_receipt_log.ts"; +import { readGoalRolloutEventSnapshotWithStat } from "../rollout_receipt_log.ts"; +import type { ReceiptLogStat } from "../runtime/receipt_log_snapshot.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { monitorScopeGeneration, normalizeMonitorChangeScope } from "./monitor_scope.ts"; @@ -459,21 +460,43 @@ export function compactTodoResumeMergeEvidence(items: unknown[], events: readonl return [...facts.values()]; } +export interface RolloutLogReadWitness { + readonly logPath: string; + readonly stat: ReceiptLogStat; + readonly stable: boolean; +} + +export interface TodoResumeRolloutReadOptions { + readonly onRolloutLogRead?: (witness: RolloutLogReadWitness) => void; +} + /** Host transport supplies the existing Goal log location, never a display * tail as complete evidence. The pure evaluator and all non-local callers keep * their existing request shape and semantics. No Todo or log is written here. */ -export async function readTodoResumeRolloutEvents(request: JsonObject): Promise { +export async function readTodoResumeRolloutEvents( + request: JsonObject, + options?: TodoResumeRolloutReadOptions, +): Promise { if (request.rollout_event_source === undefined) { return Array.isArray(request.rollout_events) ? request.rollout_events as JsonObject[] : []; } const source = requireJsonObject(request.rollout_event_source, "rollout_event_source"); const runtimeRoot = requireNonEmptyString(source.runtime_root, "runtime_root"); const goalId = requireNonEmptyString(source.goal_id, "goal_id"); - return (await readGoalRolloutEventSnapshot(runtimeRoot, goalId))?.events ?? []; + const result = await readGoalRolloutEventSnapshotWithStat(runtimeRoot, goalId); + options?.onRolloutLogRead?.({ + logPath: result.logPath, + stat: result.stat, + stable: result.stable, + }); + return result.snapshot?.events ?? []; } -export async function evaluateTodoResumeConditionsFromSource(value: unknown): Promise { +export async function evaluateTodoResumeConditionsFromSource( + value: unknown, + options?: TodoResumeRolloutReadOptions, +): Promise { const request = requireJsonObject(value, "todo_resume_evaluation_request"); const evaluated = evaluateTodoResumeConditions(request); // Reject bad input before IO. if (request.rollout_event_source === undefined) return evaluated; @@ -481,7 +504,7 @@ export async function evaluateTodoResumeConditionsFromSource(value: unknown): Pr const waits = items.some(raw => parseResumeWhen(raw.resume_when)?.kind === "pr_merged"); if (!waits) return evaluated; return evaluateTodoResumeConditions({...request, rollout_events: [ - ...compactTodoResumeMergeEvidence(items, await readTodoResumeRolloutEvents(request)), + ...compactTodoResumeMergeEvidence(items, await readTodoResumeRolloutEvents(request, options)), ...(Array.isArray(request.rollout_events) ? request.rollout_events : []), ]}); } diff --git a/loopx/control_plane/todos/summary_item.py b/loopx/control_plane/todos/summary_item.py index c2c9c0020d..849c638cf3 100644 --- a/loopx/control_plane/todos/summary_item.py +++ b/loopx/control_plane/todos/summary_item.py @@ -14,19 +14,25 @@ class _CanonicalTodoSummary(dict[str, Any]): def __init__(self, value: dict[str, Any], *, read: dict[str, Any], expected: dict[str, Any], field: str, digest: str, basis: bytes, request_identity: object, evaluations: Any = None, - source_row_fields: tuple[str, ...] = ()) -> None: + source_row_fields: tuple[str, ...] = (), + handoff_gates_evaluated: bool = False, + rollout_log_stat: Any = None) -> None: super().__init__(value) self.read, self.expected, self.field, self.digest = read, expected, field, digest self.basis, self.request_identity = basis, request_identity self.evaluations = evaluations self.source_row_fields = source_row_fields + self.handoff_gates_evaluated = handoff_gates_evaluated + self.rollout_log_stat = rollout_log_stat def __deepcopy__(self, memo: dict[int, Any]) -> _CanonicalTodoSummary: from copy import deepcopy result = _CanonicalTodoSummary({}, read=deepcopy(self.read, memo), expected=deepcopy(self.expected, memo), field=self.field, digest=self.digest, basis=self.basis, request_identity=self.request_identity, - evaluations=deepcopy(self.evaluations, memo), source_row_fields=self.source_row_fields) + evaluations=deepcopy(self.evaluations, memo), source_row_fields=self.source_row_fields, + handoff_gates_evaluated=self.handoff_gates_evaluated, + rollout_log_stat=deepcopy(self.rollout_log_stat, memo)) memo[id(self)] = result result.update(deepcopy(dict(self), memo)) return result @@ -38,7 +44,9 @@ def preserve_canonical_todo_source(source: dict[str, Any], value: dict[str, Any] return _CanonicalTodoSummary(value, read=source.read, expected=source.expected, field=source.field, digest=source.digest, basis=source.basis, request_identity=source.request_identity, evaluations=source.evaluations, - source_row_fields=source.source_row_fields) + source_row_fields=source.source_row_fields, + handoff_gates_evaluated=source.handoff_gates_evaluated, + rollout_log_stat=source.rollout_log_stat) def bind_canonical_todo_sources(result: dict[str, Any], read: dict[str, Any]) -> None: @@ -64,7 +72,9 @@ def bind_canonical_todo_sources(result: dict[str, Any], read: dict[str, Any]) -> expected=metadata["source"], field=field, digest=digest, basis=observed, request_identity=identity, evaluations=(result.get("field_evaluations") or {}).get(field), - source_row_fields=tuple(metadata.get("source_row_fields", []))) + source_row_fields=tuple(metadata.get("source_row_fields", [])), + handoff_gates_evaluated=True, + rollout_log_stat=result.get("rollout_log_stat")) def canonical_todo_select_read(params: dict[str, Any]) -> dict[str, Any] | None: @@ -129,6 +139,24 @@ def diff(before: Any, after: Any, path: list[Any]) -> None: "changes": changes, "python_values": current.get("python_values", [])} +def canonical_todo_authority_check(value: dict[str, Any]) -> dict[str, Any] | None: + from ..effect_runtime import todo_projection_request_identity + + if ( + not isinstance(value, _CanonicalTodoSummary) + or value.request_identity is not todo_projection_request_identity() + or not isinstance(value.read, dict) + or not isinstance(value.expected, dict) + or not isinstance(value.rollout_log_stat, dict) + ): + return None + return { + "read": value.read, + "expected_source": value.expected, + "rollout_log_stat": value.rollout_log_stat, + } + + class _QuotaProjectedSummary(dict[str, Any]): """Prepared wait facts over an explicitly consumed immutable source view.""" diff --git a/loopx/control_plane/todos/todo_summary.py b/loopx/control_plane/todos/todo_summary.py index fa0ecee6ed..0a9a6bfcdd 100644 --- a/loopx/control_plane/todos/todo_summary.py +++ b/loopx/control_plane/todos/todo_summary.py @@ -8,9 +8,7 @@ from ..coordination.coordination_state_contract import ( TODO_CANONICAL_READ_RECORD_FIELDS, TODO_CANONICAL_READ_RECORD_SCHEMA_VERSION as TODO_CANONICAL_READ_RECORD_SCHEMA_VERSION, - TODO_CANONICAL_REQUIRED_READ_FIELDS, - TODO_ITEM_SCHEMA_VERSION, - canonical_record_fields, + TODO_CANONICAL_REQUIRED_READ_FIELDS, TODO_ITEM_SCHEMA_VERSION, canonical_record_fields, ) from ..goals.goal_vision_wait_projection import attach_active_vision_waits from ..work_items.project_asset import build_project_asset_todo_summary @@ -19,19 +17,13 @@ TODO_TASK_CLASS_ADVANCEMENT, TODO_TASK_CLASS_USER_ACTION, build_todo_id, - normalize_explore_result_node_refs, - normalize_removed_todo_continuation_policy, - normalize_required_capabilities, - normalize_required_write_scopes, + normalize_explore_result_node_refs, normalize_removed_todo_continuation_policy, + normalize_required_capabilities, normalize_required_write_scopes, normalize_target_capabilities, - normalize_todo_action_kind, - normalize_todo_blocks_agent, - normalize_todo_bound_agent, - normalize_todo_capability_binding_ref, - normalize_todo_claimed_by, - normalize_todo_continuation_policy, - normalize_todo_decision_outcome, - normalize_todo_decision_scope, + normalize_todo_action_kind, normalize_todo_blocks_agent, + normalize_todo_bound_agent, normalize_todo_capability_binding_ref, + normalize_todo_claimed_by, normalize_todo_continuation_policy, + normalize_todo_decision_outcome, normalize_todo_decision_scope, normalize_todo_decision_scope_outcomes, normalize_todo_excluded_agents, normalize_todo_generation, @@ -352,13 +344,16 @@ def _compact_todo_item_record(item: PayloadView) -> Payload: return compact -def compact_todo_items(items: Sequence[PayloadView]) -> list[Payload]: - return cast(list[Payload], attach_todo_handoff_notes([_compact_todo_item_record(item) for item in items])) +def compact_todo_items(items: Sequence[PayloadView], *, include_handoff_note: bool = True) -> list[Payload]: + compacts = [_compact_todo_item_record(item) for item in items] + if not include_handoff_note or not compacts: + return compacts + return cast(list[Payload], attach_todo_handoff_notes(compacts)) -def compact_todo_item(item: PayloadView) -> Payload: +def compact_todo_item(item: PayloadView, *, include_handoff_note: bool = True) -> Payload: """Singleton adapter; whole-source consumers use the batch owner.""" - return compact_todo_items([item])[0] + return compact_todo_items([item], include_handoff_note=include_handoff_note)[0] def canonical_todo_read_record(item: PayloadView, *, reject_unknown: bool = False) -> Payload: @@ -440,6 +435,7 @@ def todo_item_is_deferred(item: Payload) -> bool: def open_todo_items( todos: PayloadView | None, *, limit: int = MAX_PROJECT_ASSET_TODO_ITEMS, text_limit: int = 220, source_keys: tuple[str, ...] = ("first_open_items", "items"), + include_handoff_note: bool = True, ) -> list[Payload]: if not isinstance(todos, Mapping): return [] @@ -464,19 +460,22 @@ def open_todo_items( if len(result) >= limit: break return cast(list[Payload], sorted( - attach_todo_handoff_notes(result), key=projection_todo_presentation_sort_key + attach_todo_handoff_notes(result) if include_handoff_note else result, + key=projection_todo_presentation_sort_key, )) def todo_lane_items( - todos: PayloadView | None, lane: str, *, - limit: int = MAX_STATUS_TODOS_PER_ROLE, text_limit: int = 220, + todos: PayloadView | None, lane: str, *, limit: int = MAX_STATUS_TODOS_PER_ROLE, + text_limit: int = 220, include_handoff_note: bool = True, ) -> list[Payload]: - return open_todo_items(todos, limit=limit, text_limit=text_limit, source_keys=(lane,)) + return open_todo_items( + todos, limit=limit, text_limit=text_limit, source_keys=(lane,), include_handoff_note=include_handoff_note, + ) def first_open_todo_text(todos: PayloadView | None, *, item_limit: int = 220) -> str | None: - items = open_todo_items(todos, limit=1, text_limit=item_limit) + items = open_todo_items(todos, limit=1, text_limit=item_limit, include_handoff_note=False) if not items: return None return str(items[0].get("text") or "") or None @@ -502,14 +501,13 @@ def project_asset_todo_summary( todos, role=role, item_limit=item_limit, deferred_item_limit=deferred_item_limit, advancement_task_class=advancement_task_class, open_todo_items=lambda value, **kwargs: open_todo_items( - value, limit=kwargs.get("limit", item_limit), - text_limit=kwargs.get("text_limit", 220), - source_keys=kwargs.get("source_keys", ("first_open_items", "items")), + value, limit=kwargs.get("limit", item_limit), text_limit=kwargs.get("text_limit", 220), + source_keys=kwargs.get("source_keys", ("first_open_items", "items")), include_handoff_note=False, ), - compact_todo_item=compact_todo_item, + compact_todo_item=lambda item: compact_todo_item(item, include_handoff_note=False), todo_lane_items=lambda value, lane, **kwargs: todo_lane_items( value, lane, limit=kwargs.get("limit", MAX_STATUS_TODOS_PER_ROLE), - text_limit=kwargs.get("text_limit", 220), + text_limit=kwargs.get("text_limit", 220), include_handoff_note=False, ), todo_item_is_actionable_open=todo_item_is_actionable_open, todo_item_task_class=todo_item_task_class, diff --git a/loopx/control_plane/work_items/interaction_contract.py b/loopx/control_plane/work_items/interaction_contract.py index 0d1fca0a39..d1895f67a6 100644 --- a/loopx/control_plane/work_items/interaction_contract.py +++ b/loopx/control_plane/work_items/interaction_contract.py @@ -285,20 +285,22 @@ def finalize_user_gate_notification_cooldown( ) if isinstance(cooldown, dict): payload["user_gate_notification_cooldown"] = dict(cooldown) - if _user_gate_notification_suppressed(payload): + suppressed = _user_gate_notification_suppressed(payload) + if suppressed: payload["pending_user_action"] = bool( payload.get("requires_user_action") or user_channel_action_todo_actions(payload.get("user_todo_summary")) ) payload["requires_user_action"] = False - payload["interaction_contract"] = build_interaction_contract( - payload, - available_capabilities=available_capabilities, - scheduler_execution_context=scheduler_execution_context, - turn_instance_id=turn_instance_id, - runtime_root=runtime_root, - registry_path=registry_path, - ) + if suppressed or not isinstance(payload.get("interaction_contract"), dict): + payload["interaction_contract"] = build_interaction_contract( + payload, + available_capabilities=available_capabilities, + scheduler_execution_context=scheduler_execution_context, + turn_instance_id=turn_instance_id, + runtime_root=runtime_root, + registry_path=registry_path, + ) attach_user_action_compat_fields(payload) diff --git a/loopx/heartbeat_prequota.py b/loopx/heartbeat_prequota.py index 81cb1f1ef2..7cabdf9cf2 100644 --- a/loopx/heartbeat_prequota.py +++ b/loopx/heartbeat_prequota.py @@ -7,11 +7,72 @@ reconcile_acknowledged_issue_fix_pr_reviews, ) from .capabilities.turn_start import extend_turn_start_dispatch +from .control_plane.effect_runtime import ( + EffectRuntimeRemoteError, + EffectRuntimeStartupError, + effect_runtime_request_scope, + effect_runtime_result, +) +from .control_plane.todos.list_readback import list_goal_todos from .history import load_registry from .paths import resolve_runtime_root HEARTBEAT_PRE_QUOTA_SCHEMA_VERSION = "heartbeat_pre_quota_v0" +_WITNESS_REQUIRED_KEYS: tuple[str, ...] = ( + "source_authority", + "provider_revision", + "cursor", +) + + +def _extract_authority_witness(payload: Any) -> dict[str, str] | None: + if not isinstance(payload, dict): + return None + authority = payload.get("authority_read") + if not isinstance(authority, dict): + return None + witness: dict[str, str] = {} + for key in _WITNESS_REQUIRED_KEYS: + value = authority.get(key) + if not isinstance(value, str) or not value.strip(): + return None + witness[key] = value + return witness + + +def _is_valid_authority_witness(witness: Any) -> bool: + return isinstance(witness, dict) and all( + isinstance(witness.get(key), str) and bool(str(witness.get(key)).strip()) + for key in _WITNESS_REQUIRED_KEYS + ) + + +def _canonical_witness_is_fresh( + *, + runtime_root: Path, + goal_id: str, + expected_witness: dict[str, str], +) -> bool: + try: + result = effect_runtime_result( + "todo.authority_head.verify", + { + "schema_version": "todo_authority_head_verify_v0", + "runtime_root": str(runtime_root.expanduser().resolve(strict=False)), + "goal_id": goal_id, + "expected_witness": expected_witness, + }, + ) + except ( + EffectRuntimeRemoteError, + EffectRuntimeStartupError, + OSError, + RuntimeError, + ValueError, + ): + return False + return isinstance(result, dict) and result.get("fresh") is True def run_heartbeat_pre_quota( @@ -22,71 +83,136 @@ def run_heartbeat_pre_quota( agent_id: str, fetch_timeout_seconds: int = 10, ) -> dict[str, Any]: - try: - review_reconciliation = reconcile_acknowledged_issue_fix_pr_reviews( + with effect_runtime_request_scope(): + runtime = resolve_runtime_root( + load_registry(registry_path), runtime_root_arg, registry_path=registry_path + ) + shared_todo_cache: dict[str, Any] = { + "todos": None, + "witness": None, + "dirty": False, + } + + def load_shared_todos() -> list[dict[str, Any]]: + cached = shared_todo_cache["todos"] + if cached is None or shared_todo_cache["dirty"]: + result = list_goal_todos( + registry_path=registry_path, + runtime_root_arg=str(runtime), + goal_id=goal_id, + role=None, + ) + cached = result["todos"] + shared_todo_cache["todos"] = cached + shared_todo_cache["witness"] = _extract_authority_witness(result) + shared_todo_cache["dirty"] = False + return list(cached) + + def invalidate_shared_todos() -> None: + shared_todo_cache["todos"] = None + shared_todo_cache["witness"] = None + shared_todo_cache["dirty"] = True + + def load_shared_agent_todos() -> list[dict[str, Any]] | None: + cached = shared_todo_cache["todos"] + witness = shared_todo_cache["witness"] + if ( + cached is None + or shared_todo_cache["dirty"] + or not _is_valid_authority_witness(witness) + ): + invalidate_shared_todos() + return None + if not _canonical_witness_is_fresh( + runtime_root=runtime, + goal_id=goal_id, + expected_witness=witness, + ): + invalidate_shared_todos() + return None + return [ + dict(todo) + for todo in cached + if isinstance(todo, dict) and todo.get("role") == "agent" + ] + + try: + review_reconciliation = reconcile_acknowledged_issue_fix_pr_reviews( + registry_path=registry_path, + runtime_root_arg=str(runtime), + goal_id=goal_id, + agent_id=agent_id, + project=None, + fetch_metadata=True, + fetch_timeout_seconds=fetch_timeout_seconds, + execute=True, + todo_loader=load_shared_todos, + on_todo_mutation=invalidate_shared_todos, + ) + degraded = bool(review_reconciliation.get("degraded")) + failure_count = int(review_reconciliation.get("failure_count") or 0) + except Exception as exc: + degraded = True + failure_count = 1 + review_reconciliation = { + "ok": True, + "degraded": True, + "failure_count": 1, + "failure_categories": [type(exc).__name__], + "external_read_count": 0, + "write_count": 0, + } + + dispatch = extend_turn_start_dispatch( + {}, registry_path=registry_path, - runtime_root_arg=runtime_root_arg, + runtime_root=runtime, goal_id=goal_id, agent_id=agent_id, - project=None, - fetch_metadata=True, - fetch_timeout_seconds=fetch_timeout_seconds, - execute=True, + available=None, + provider_options={ + "issue-fix": { + "fetch_timeout_seconds": fetch_timeout_seconds, + "shared_agent_todos_loader": load_shared_agent_todos, + } + }, ) - degraded = bool(review_reconciliation.get("degraded")) - failure_count = int(review_reconciliation.get("failure_count") or 0) - except Exception as exc: - degraded = True - failure_count = 1 - review_reconciliation = { + # Keep the released command's compatibility projection. Observation itself + # is registered and permission-resolved by the same lifecycle as execution. + failed = next((row for row in dispatch.get("failures", []) + if row.get("capability_id") == "issue-fix"), None) + dependencies = next((row["readback"] for row in dispatch.get("results", []) + if row.get("capability_id") == "issue-fix" and isinstance(row.get("readback"), dict)), + {"ok": not bool(failed), "degraded": bool(failed), "failure_count": 1 if failed else 0, + "external_read_count": None if failed else 0, "state_written": None if failed else False, + "status": "observation_unavailable" if failed else "not_configured_or_unavailable"}) + degraded = degraded or bool(dependencies.get("degraded")) + failure_count += int(dependencies.get("failure_count") or 0) + + return { "ok": True, - "degraded": True, - "failure_count": 1, - "failure_categories": [type(exc).__name__], - "external_read_count": 0, - "write_count": 0, + "schema_version": HEARTBEAT_PRE_QUOTA_SCHEMA_VERSION, + "goal_id": goal_id, + "agent_id": agent_id, + "degraded": degraded, + "failure_count": failure_count, + "checks": { + "acknowledged_pr_reviews": review_reconciliation, + "pr_dependencies": dependencies, + }, + "turn_start_capability_hook_dispatch": dispatch, + "quota_spend_required": False, + "continue_to_quota": True, } - runtime = resolve_runtime_root(load_registry(registry_path), runtime_root_arg, registry_path=registry_path) - dispatch = extend_turn_start_dispatch({}, registry_path=registry_path, runtime_root=runtime, - goal_id=goal_id, agent_id=agent_id, available=None, - provider_options={"issue-fix": {"fetch_timeout_seconds": fetch_timeout_seconds}}) - # Keep the released command's compatibility projection. Observation itself - # is registered and permission-resolved by the same lifecycle as execution. - failed = next((row for row in dispatch.get("failures", []) - if row.get("capability_id") == "issue-fix"), None) - dependencies = next((row["readback"] for row in dispatch.get("results", []) - if row.get("capability_id") == "issue-fix" and isinstance(row.get("readback"), dict)), - {"ok": not bool(failed), "degraded": bool(failed), "failure_count": 1 if failed else 0, - "external_read_count": None if failed else 0, "state_written": None if failed else False, - "status": "observation_unavailable" if failed else "not_configured_or_unavailable"}) - degraded = degraded or bool(dependencies.get("degraded")) - failure_count += int(dependencies.get("failure_count") or 0) - - return { - "ok": True, - "schema_version": HEARTBEAT_PRE_QUOTA_SCHEMA_VERSION, - "goal_id": goal_id, - "agent_id": agent_id, - "degraded": degraded, - "failure_count": failure_count, - "checks": { - "acknowledged_pr_reviews": review_reconciliation, - "pr_dependencies": dependencies, - }, - "turn_start_capability_hook_dispatch": dispatch, - "quota_spend_required": False, - "continue_to_quota": True, - } - def render_heartbeat_pre_quota_markdown(payload: dict[str, Any]) -> str: - checks = payload.get("checks") if isinstance(payload.get("checks"), dict) else {} - review = ( - checks.get("acknowledged_pr_reviews") - if isinstance(checks.get("acknowledged_pr_reviews"), dict) - else {} - ) + raw_checks = payload.get("checks") + checks: dict[str, Any] = raw_checks if isinstance(raw_checks, dict) else {} + raw_review = checks.get("acknowledged_pr_reviews") + review: dict[str, Any] = raw_review if isinstance(raw_review, dict) else {} + raw_deps = checks.get("pr_dependencies") + dependencies: dict[str, Any] = raw_deps if isinstance(raw_deps, dict) else {} return "\n".join( [ "# LoopX Heartbeat Pre-Quota", @@ -95,7 +221,7 @@ def render_heartbeat_pre_quota_markdown(payload: dict[str, Any]) -> str: f"- degraded: `{payload.get('degraded')}`", f"- reconciled_count: `{review.get('reconciled_count', 0)}`", f"- failure_count: `{payload.get('failure_count')}`", - f"- PR dependency reads: `{checks.get('pr_dependencies', {}).get('external_read_count', 0)}`", + f"- PR dependency reads: `{dependencies.get('external_read_count', 0)}`", f"- continue_to_quota: `{payload.get('continue_to_quota')}`", "- quota_spend_required: `False`", ] diff --git a/loopx/quota.py b/loopx/quota.py index 711aa78945..c9eb31cdf6 100644 --- a/loopx/quota.py +++ b/loopx/quota.py @@ -12,9 +12,7 @@ from .control_plane import compact_control_plane_policy from .control_plane.effect_program import ( - ReceiptBoundMonitorPhase, - ReceiptBoundReplayPhase, - ReceiptBoundTerminalPhase, + ReceiptBoundMonitorPhase, ReceiptBoundReplayPhase, ReceiptBoundTerminalPhase, ) from .control_plane.goals.activation import goal_is_stopped from .control_plane.quota.blocked_retry import overlay_active_turn_retries @@ -824,6 +822,7 @@ def build_quota_should_run( goal_ref: Mapping[str, object] | None = None, authoritative_fallback_todo_items: FallbackTodoSource = None, app_scheduler_state_observer: Callable[[Mapping[str, object]], None] | None = None, + reuse_fresh_canonical_snapshot: bool = False, ) -> dict[str, object]: from .control_plane.quota.should_run import build_quota_should_run as _build_quota_should_run @@ -861,6 +860,7 @@ def read_explore_context(read_goal_id: str, read_agent_id: str | None) -> dict[s runtime_root=runtime_root, workspace_path=workspace_path, goal_ref=goal_ref, authoritative_fallback_todo_items=authoritative_fallback_todo_items, replan_explore_reader=read_explore_context, app_scheduler_state_observer=app_scheduler_state_observer, + reuse_fresh_canonical_snapshot=reuse_fresh_canonical_snapshot, ) diff --git a/loopx/rollout_event_log.py b/loopx/rollout_event_log.py index 0d46e7137d..8df0fc1599 100644 --- a/loopx/rollout_event_log.py +++ b/loopx/rollout_event_log.py @@ -649,6 +649,33 @@ def load_rollout_events(log_path: Path, *, limit: int | None = None) -> list[dic return _recent_rollout_events(log_path, limit=limit) +def iter_reverse_rollout_events_by_kind( + log_path: Path, *, event_kind: str +) -> Iterator[dict[str, Any]]: + """Yield events matching ``event_kind`` newest-first, skipping non-matching JSON parses.""" + marker = event_kind.encode("utf-8") + try: + handle = log_path.open("rb") + except OSError: + return + with handle: + raw_lines: Iterator[bytes] = ( + reversed(list(handle)) + if not handle.seekable() + else _reverse_rollout_lines(handle) + ) + for encoded in raw_lines: + if marker and b"\\u" not in encoded and marker not in encoded: + continue + try: + line = encoded.decode("utf-8") + except UnicodeDecodeError: + continue + event = _parse_rollout_event_line(line) + if event is not None and event.get("event_kind") == event_kind: + yield event + + class RolloutEventSnapshot: def __init__(self, runtime_root: Path, *, limit: int) -> None: if limit <= 0: diff --git a/tests/control_plane/test_status_prequota_hotpath_efficiency.py b/tests/control_plane/test_status_prequota_hotpath_efficiency.py new file mode 100644 index 0000000000..ee7d1e348f --- /dev/null +++ b/tests/control_plane/test_status_prequota_hotpath_efficiency.py @@ -0,0 +1,1265 @@ +"""Non-mocked File and SQLite parity, freshness, and RPC-collapse tests.""" + +from __future__ import annotations + +import argparse +from collections.abc import Callable, Iterator +from datetime import datetime, timedelta, timezone +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +from typing import Any, cast + +import pytest + +from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime +from loopx.capabilities.issue_fix import pr_lifecycle, pr_wait_reconcile +from loopx.capabilities.issue_fix.pr_gate_reconcile import ( + reconcile_acknowledged_issue_fix_pr_reviews, +) +from loopx.capabilities.issue_fix.pr_review_ack import record_issue_fix_pr_review_ack +from loopx.cli_commands.status import ( + attach_agent_lane_next_actions, + handle_review_packet_command, + handle_status_command, +) +from loopx.control_plane import effect_runtime +from loopx.control_plane.coordination.authority_source_capture import ( + build_todo_runtime_shadow_projection, +) +from loopx.control_plane.coordination.local_authority import ( + LocalCoordinationAuthorityUnavailable, + claim_canonical_todo_if_promoted, + read_canonical_todos_if_promoted, +) +from loopx.control_plane.effect_runtime import effect_runtime_request_scope, restart_effect_runtime +from loopx.control_plane.status.agent_lane_projection import ( + compact_agent_lane_status_payload_for_display, +) +from loopx.control_plane.todos.list_readback import list_goal_todos +from loopx.control_plane.todos.quota_summary import ( + compact_agent_lane_todos_for_status_display, + select_quota_todo_contexts, +) +from loopx.control_plane.todos.todo_index import compact_agent_lane_todo_index_for_status_display +from loopx.control_plane.todos.todo_summary import ( + first_open_todo_text, + open_todo_items, + project_asset_todo_summary, +) +from loopx.heartbeat_prequota import ( + render_heartbeat_pre_quota_markdown, + run_heartbeat_pre_quota, +) +from loopx.presentation.renderers.status_markdown import render_status_markdown +import loopx.rollout_event_log as rollout_event_log_module +from loopx.rollout_event_log import ( + append_rollout_event, + build_rollout_event, + rollout_event_log_path, +) +from loopx.status import collect_status + +GOAL_ID = "hotpath-efficiency-goal" +AGENT_ID = "agent-hotpath" +REPO_SLUG = "example/hotpath" + + +@pytest.fixture(autouse=True) +def _isolated_sqlite_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + isolate_sqlite_runtime(tmp_path, monkeypatch) # type: ignore[no-untyped-call] + yield + restart_effect_runtime() + + +def _normalize_volatile(value: Any) -> Any: + """Strip wall-clock timestamps, durations, and envelope signatures for parity comparison.""" + if isinstance(value, list): + return [_normalize_volatile(item) for item in value] + if isinstance(value, dict): + normalized: dict[str, Any] = {} + for key, item in value.items(): + if key in { + "checked_at", + "generated_at", + "observed_at", + "last_read_at", + "recorded_at", + "duration_ms", + "projection_envelope", + "signature", + "next_check_at", + "next_due_at", + "last_checked_at", + "next_action_basis", + "recommendation_context", + }: + continue + normalized[key] = _normalize_volatile(item) + return normalized + return value + + +def _write_goal_fixture( + tmp_path: Path, + *, + provider: str, + deferred_count: int = 12, + include_pr_wait: bool = False, + include_pr_review_gate: bool = False, + capability_granted: bool = False, +) -> tuple[Path, Path, Path]: + project = tmp_path / "project" + runtime = tmp_path / "runtime" + state = project / "ACTIVE_GOAL_STATE.md" + state.parent.mkdir(parents=True, exist_ok=True) + state.write_text("# Hotpath Goal\n\nKeep state concise.\n", encoding="utf-8") + + records: list[dict[str, Any]] = [ + { + "schema_version": "todo_item_v0", + "todo_id": "todo_adv_primary", + "index": 1, + "role": "agent", + "status": "open", + "done": False, + "text": "[P1] Deliver primary agent hotpath slice", + "priority": "P1", + "task_class": "advancement_task", + "claimed_by": AGENT_ID, + "archive_state": "active", + "source_section": "Agent Todo", + "required_capabilities": ["shell"], + }, + { + "schema_version": "todo_item_v0", + "todo_id": "todo_adv_unclaimed", + "index": 2, + "role": "agent", + "status": "open", + "done": False, + "text": "[P2] Follow-up unclaimed agent work", + "priority": "P2", + "task_class": "advancement_task", + "archive_state": "active", + "source_section": "Agent Todo", + }, + { + "schema_version": "todo_item_v0", + "todo_id": "todo_monitor_quiet", + "index": 3, + "role": "agent", + "status": "open", + "done": False, + "text": "[P3] Monitor CI telemetry [repeat: every 6h]", + "priority": "P3", + "task_class": "monitor", + "archive_state": "active", + "source_section": "Agent Todo", + }, + { + "schema_version": "todo_item_v0", + "todo_id": "todo_user_open", + "index": 4, + "role": "user", + "status": "open", + "done": False, + "text": "[P2] Read architecture review note", + "priority": "P2", + "task_class": "user_action", + "archive_state": "active", + "source_section": "User Todo / Owner Review Reading Queue", + }, + ] + next_index = 5 + for offset in range(deferred_count): + records.append( + { + "schema_version": "todo_item_v0", + "todo_id": f"todo_deferred_{offset:02d}", + "index": next_index, + "role": "agent", + "status": "deferred", + "done": False, + "text": f"[P2] Deferred item {offset:02d} after blocker", + "priority": "P2", + "task_class": "advancement_task", + "resume_when": "todo_done:todo_adv_primary", + "archive_state": "active", + "source_section": "Agent Todo", + } + ) + next_index += 1 + if include_pr_wait: + records.append( + { + "schema_version": "todo_item_v0", + "todo_id": "todo_wait_pr_41", + "index": next_index, + "role": "agent", + "status": "deferred", + "done": False, + "text": "[P1] Resume follow-up after PR 41 merges", + "priority": "P1", + "task_class": "advancement_task", + "task_repository": f"git:github.com/{REPO_SLUG}", + "resume_when": "pr_merged:#41", + "archive_state": "active", + "source_section": "Agent Todo", + } + ) + next_index += 1 + if include_pr_review_gate: + records.append( + { + "schema_version": "todo_item_v0", + "todo_id": "todo_pr_review_41", + "index": next_index, + "role": "user", + "status": "open", + "done": False, + "text": f"[P1] Review PR https://github.com/{REPO_SLUG}/pull/41", + "priority": "P1", + "task_class": "user_action", + "bound_agent": AGENT_ID, + "updated_at": "2026-11-24T09:00:00Z", + "archive_state": "active", + "source_section": "User Todo / Owner Review Reading Queue", + } + ) + + goal_entry: dict[str, Any] = { + "id": GOAL_ID, + "status": "active", + "domain": "software", + "repo": str(project), + "state_file": state.name, + "adapter": {"kind": "read_only_project_map_v0"}, + "coordination": {"registered_agents": [AGENT_ID]}, + "available_capabilities": ( + ["shell", "external_evidence_poll"] if capability_granted else ["shell"] + ), + } + registry = project / ".loopx" / "registry.json" + registry.parent.mkdir(parents=True, exist_ok=True) + registry.write_text( + json.dumps( + { + "schema_version": 1, + "common_runtime_root": str(runtime), + "goals": [goal_entry], + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=records) + initialize_canonical_authority(runtime, GOAL_ID, projection, state_path=state, provider=provider) + return registry, runtime, state + + +def _append_unrelated_rollout_events(runtime: Path, count: int) -> None: + log_path = rollout_event_log_path(runtime, GOAL_ID) + base = datetime(2026, 11, 24, 1, 0, tzinfo=timezone.utc) + for idx in range(count): + ts = (base + timedelta(minutes=idx)).isoformat().replace("+00:00", "Z") + append_rollout_event( + log_path, + build_rollout_event( + goal_id=GOAL_ID, + event_kind="evidence_log_read", + agent_id=AGENT_ID, + status="completed", + summary=f"Read fixture {idx}.", + recorded_at=ts, + ), + ) + + +def _capture_rpc_calls(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, Any]]]: + calls: list[tuple[str, dict[str, Any]]] = [] + original = effect_runtime.effect_runtime_request + + def observed(method: str, params: dict[str, Any], **kwargs: Any) -> Any: + calls.append((method, dict(params) if isinstance(params, dict) else {})) + return original(method, params, **kwargs) + + monkeypatch.setattr(effect_runtime, "effect_runtime_request", observed) + return calls + + +def _status_cli_args(*, agent_id: str | None) -> argparse.Namespace: + return argparse.Namespace( + limit=5, + agent_id=agent_id, + include_task_graph=False, + goal_id=None, + available_capabilities=["shell"], + use_projection_cache=False, + write_projection_cache=False, + projection_cache_ttl_seconds=60, + format="json", + ) + + +def _run_status_cli_with_exit( + registry: Path, runtime: Path, *, agent_id: str | None +) -> tuple[int, dict[str, Any], str]: + captured: list[tuple[dict[str, Any], str]] = [] + + def capture(value: dict[str, Any], _fmt: str, renderer: Any) -> None: + captured.append((value, renderer(value))) + + exit_code = handle_status_command( + _status_cli_args(agent_id=agent_id), + registry_path=registry, + runtime_root_arg=str(runtime), + output_format=lambda _args: "json", + print_payload=capture, + ) + assert len(captured) == 1 + return exit_code, captured[0][0], captured[0][1] + + +def _run_status_cli(registry: Path, runtime: Path, *, agent_id: str | None) -> tuple[dict[str, Any], str]: + exit_code, payload, rendered_md = _run_status_cli_with_exit( + registry, runtime, agent_id=agent_id + ) + assert exit_code == 0 + return payload, rendered_md + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_status_collapses_duplicate_reads_and_n_plus_one_paging_with_exact_parity( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + registry_zero, runtime_zero, _ = _write_goal_fixture( + tmp_path / "zero", provider=provider, deferred_count=0 + ) + registry_many, runtime_many, _ = _write_goal_fixture( + tmp_path / "many", provider=provider, deferred_count=12 + ) + + calls = _capture_rpc_calls(monkeypatch) + fast_payload, fast_md = _run_status_cli(registry_many, runtime_many, agent_id=AGENT_ID) + many_methods = [method for method, _ in calls] + + # Zero-deferred vs 12-deferred must keep todo.context.page flat (no N+1 deferred RPCs). + calls.clear() + _run_status_cli(registry_zero, runtime_zero, agent_id=AGENT_ID) + zero_methods = [method for method, _ in calls] + + assert many_methods.count("todo.read") == 1 + assert many_methods.count("coordination.local_authority.todo_snapshot") <= 1 + assert many_methods.count("todo.succession.project") == 0 + assert many_methods.count("todo.context.page") <= 5 + assert many_methods.count("todo.context.page") == zero_methods.count("todo.context.page") + assert many_methods.count("agent.delivery_workspace.evaluate") == 2 + assert many_methods.count("work_item.interaction_execution.project") == 1 + assert many_methods.count("work_item.interaction_reads.project") == 1 + + # Un-reused baseline path: independent collect_status scope + standalone todo.read(quota_projection). + calls.clear() + baseline_payload = collect_status( + registry_path=registry_many, + runtime_root_override=str(runtime_many), + limit=5, + include_task_graph=False, + goal_id=None, + available_capabilities=["shell"], + agent_lane_id=AGENT_ID, + ) + attach_agent_lane_next_actions(baseline_payload, agent_id=AGENT_ID) + compact_agent_lane_todos_for_status_display(baseline_payload) + compact_agent_lane_status_payload_for_display(baseline_payload, agent_id=AGENT_ID) + compact_agent_lane_todo_index_for_status_display(baseline_payload) + attention_queue = cast(dict[str, Any], baseline_payload.get("attention_queue", {})) + for item in cast(list[dict[str, Any]], attention_queue.get("items", [])): + item.pop("recommendation_context", None) + item.pop("next_action_basis", None) + baseline_md = render_status_markdown(baseline_payload) + + def _scrub_iso_timestamps(markdown: str) -> str: + return re.sub( + r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z", + "", + markdown, + ) + + assert _normalize_volatile(fast_payload) == _normalize_volatile(baseline_payload) + assert _scrub_iso_timestamps(fast_md) == _scrub_iso_timestamps(baseline_md) + + # Verify non-agent status drops N+1 deferred/display handoff_sources calls cleanly and preserves output. + calls.clear() + plain_payload, plain_md = _run_status_cli(registry_many, runtime_many, agent_id=None) + plain_methods = [method for method, _ in calls] + calls.clear() + _run_status_cli(registry_zero, runtime_zero, agent_id=None) + plain_zero_methods = [method for method, _ in calls] + assert plain_methods.count("todo.read") == 1 + assert plain_methods.count("coordination.local_authority.todo_snapshot") <= 1 + assert plain_methods.count("todo.context.page") <= 2 + assert plain_methods.count("todo.context.page") == plain_zero_methods.count("todo.context.page") + assert "Deliver primary agent hotpath slice" in plain_md + agent_todos = plain_payload["attention_queue"]["items"][0]["agent_todos"] + assert open_todo_items(agent_todos, include_handoff_note=False) == [ + {k: v for k, v in item.items() if k != "handoff_note"} + for item in open_todo_items(agent_todos, include_handoff_note=True) + ] + assert first_open_todo_text(agent_todos) + assert ( + project_asset_todo_summary(agent_todos, role="agent") + == build_summary_with_notes(agent_todos) + ) + + +def build_summary_with_notes(agent_todos: dict[str, Any]) -> dict[str, Any] | None: + """Reference comparison where handoff_note was computed and immediately discarded.""" + summary = project_asset_todo_summary(agent_todos, role="agent") + assert summary is not None + # Confirm open_todo_items with notes matches the stripped project_asset rows. + for row in cast(list[dict[str, Any]], summary.get("items", [])): + assert "handoff_note" not in row + for row in cast(list[dict[str, Any]], summary.get("deferred_items", [])): + assert "handoff_note" not in row + return summary + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_status_reused_quota_projection_rejects_stale_and_unavailable_authority( + tmp_path: Path, provider: str +) -> None: + registry, runtime, _ = _write_goal_fixture( + tmp_path / "stale", provider=provider, deferred_count=2 + ) + with effect_runtime_request_scope(): + before = read_canonical_todos_if_promoted( + runtime_root=runtime, goal_id=GOAL_ID, include_summary=True + ) + fields = before["_todo_fields"] + claim_canonical_todo_if_promoted( + registry_path=registry, + runtime_root=runtime, + goal_id=GOAL_ID, + todo_id="todo_adv_unclaimed", + role="agent", + claimed_by=AGENT_ID, + actor_agent_id=AGENT_ID, + dry_run=False, + task_lease_idempotency_key="hotpath-lease-1", + task_lease_expected_version=0, + ) + with pytest.raises(ValueError, match="quota canonical source changed"): + select_quota_todo_contexts( + fields["user_todos"], + None, + fields["agent_todos"], + None, + agent_identity={"agent_id": AGENT_ID}, + available_capabilities=["shell"], + reuse_fresh_canonical_snapshot=True, + ) + + registry2, runtime2, _ = _write_goal_fixture( + tmp_path / "rollout", provider=provider, deferred_count=1 + ) + with effect_runtime_request_scope(): + before2 = read_canonical_todos_if_promoted( + runtime_root=runtime2, goal_id=GOAL_ID, include_summary=True + ) + fields2 = before2["_todo_fields"] + append_rollout_event( + rollout_event_log_path(runtime2, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="evidence_log_read", + agent_id=AGENT_ID, + status="completed", + summary="Concurrent log append.", + recorded_at="2026-11-24T10:00:00Z", + ), + ) + with pytest.raises(ValueError, match="quota canonical source changed"): + select_quota_todo_contexts( + fields2["user_todos"], + None, + fields2["agent_todos"], + None, + agent_identity={"agent_id": AGENT_ID}, + available_capabilities=["shell"], + reuse_fresh_canonical_snapshot=True, + ) + + authority_dir = runtime2 / "authority" / f"{provider}-v0" + hidden = authority_dir.with_name(authority_dir.name + "-hidden") + authority_dir.rename(hidden) + try: + with pytest.raises(LocalCoordinationAuthorityUnavailable): + select_quota_todo_contexts( + fields2["user_todos"], + None, + fields2["agent_todos"], + None, + agent_identity={"agent_id": AGENT_ID}, + available_capabilities=["shell"], + reuse_fresh_canonical_snapshot=True, + ) + finally: + if authority_dir.exists(): + shutil.rmtree(authority_dir) + hidden.rename(authority_dir) + + +def _write_pr_wait_status_fixture( + tmp_path: Path, *, provider: str, seed_rollout_log: bool +) -> tuple[Path, Path, Path]: + project = tmp_path / "project" + runtime = tmp_path / "runtime" + state = project / "ACTIVE_GOAL_STATE.md" + state.parent.mkdir(parents=True, exist_ok=True) + state.write_text("# Hotpath Goal\n\nKeep state concise.\n", encoding="utf-8") + records: list[dict[str, Any]] = [ + { + "schema_version": "todo_item_v0", + "todo_id": "todo_adv_primary", + "index": 1, + "role": "agent", + "status": "done", + "done": True, + "no_followup": True, + "text": "[P1] Completed primary work", + "priority": "P1", + "task_class": "advancement_task", + "claimed_by": AGENT_ID, + "completed_at": "2026-11-24T09:00:00Z", + "archive_state": "active", + "source_section": "Agent Todo", + }, + { + "schema_version": "todo_item_v0", + "todo_id": "todo_wait_pr_41", + "index": 2, + "role": "agent", + "status": "deferred", + "done": False, + "text": "[P1] Resume follow-up after PR 41 merges", + "priority": "P1", + "task_class": "advancement_task", + "claimed_by": AGENT_ID, + "task_repository": f"git:github.com/{REPO_SLUG}", + "resume_when": "pr_merged:#41", + "archive_state": "active", + "source_section": "Agent Todo", + }, + ] + goal_entry: dict[str, Any] = { + "id": GOAL_ID, + "status": "active", + "domain": "software", + "repo": str(project), + "state_file": state.name, + "adapter": {"kind": "read_only_project_map_v0", "status": "connected"}, + "coordination": {"registered_agents": [AGENT_ID]}, + "available_capabilities": ["shell"], + } + registry = project / ".loopx" / "registry.json" + registry.parent.mkdir(parents=True, exist_ok=True) + registry.write_text( + json.dumps( + { + "schema_version": 1, + "common_runtime_root": str(runtime), + "goals": [goal_entry], + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=records) + initialize_canonical_authority(runtime, GOAL_ID, projection, state_path=state, provider=provider) + log_path = rollout_event_log_path(runtime, GOAL_ID) + if seed_rollout_log: + append_rollout_event( + log_path, + build_rollout_event( + goal_id=GOAL_ID, + event_kind="evidence_log_read", + agent_id=AGENT_ID, + status="completed", + summary="Baseline log event prior to PR merge.", + recorded_at="2026-11-24T09:30:00Z", + ), + ) + return registry, runtime, log_path + + +def _install_rollout_toctou_preload( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + *, + log_path: Path, + mode: str, +) -> Path: + flag_path = tmp_path / "injected.flag" + merge_event = build_rollout_event( + goal_id=GOAL_ID, + event_kind="pr_merge", + agent_id=AGENT_ID, + pr_ref=f"{REPO_SLUG}#41", + status="merged", + summary="PR 41 merged.", + recorded_at="2026-11-24T10:00:00Z", + ) + merge_line = json.dumps(merge_event, sort_keys=True, ensure_ascii=False) + "\n" + resolved_log = str(log_path.expanduser().resolve(strict=False)) + hook_path = tmp_path / f"toctou-hook-{mode}.mjs" + hook_path.write_text( + 'import { appendFileSync, writeFileSync } from "node:fs";\n' + 'import fsPromises from "node:fs/promises";\n' + 'import { syncBuiltinESMExports } from "node:module";\n' + 'import { resolve } from "node:path";\n' + f"const targetLog = {json.dumps(resolved_log)};\n" + f"const flagPath = {json.dumps(str(flag_path))};\n" + f"const mergeLine = {json.dumps(merge_line)};\n" + f"const mode = {json.dumps(mode)};\n" + "let sawRead = false;\n" + "let injected = false;\n" + "const isTarget = (arg) => typeof arg === 'string' && resolve(arg) === targetLog;\n" + "const origReadFile = fsPromises.readFile.bind(fsPromises);\n" + "const origStat = fsPromises.stat.bind(fsPromises);\n" + "fsPromises.readFile = async function (pathArg, ...rest) {\n" + " try {\n" + " const data = await origReadFile(pathArg, ...rest);\n" + " if (isTarget(pathArg)) {\n" + " sawRead = true;\n" + " if (mode === 'after_read_before_post_stat' && !injected) {\n" + " injected = true;\n" + " appendFileSync(targetLog, mergeLine, 'utf8');\n" + " writeFileSync(flagPath, '1', 'utf8');\n" + " }\n" + " }\n" + " return data;\n" + " } catch (error) {\n" + " if (mode === 'created_after_enoent' && !injected && isTarget(pathArg) && error?.code === 'ENOENT') {\n" + " injected = true;\n" + " writeFileSync(targetLog, mergeLine, 'utf8');\n" + " writeFileSync(flagPath, '1', 'utf8');\n" + " }\n" + " throw error;\n" + " }\n" + "};\n" + "fsPromises.stat = async function (pathArg, ...rest) {\n" + " const info = await origStat(pathArg, ...rest);\n" + " if (mode === 'after_snapshot_before_line86' && sawRead && !injected && isTarget(pathArg)) {\n" + " injected = true;\n" + " appendFileSync(targetLog, mergeLine, 'utf8');\n" + " writeFileSync(flagPath, '1', 'utf8');\n" + " }\n" + " return info;\n" + "};\n" + "syncBuiltinESMExports();\n", + encoding="utf-8", + ) + existing_node_options = os.environ.get("NODE_OPTIONS", "").strip() + monkeypatch.setenv( + "NODE_OPTIONS", + f"{existing_node_options} --import={hook_path.as_uri()}".strip(), + ) + restart_effect_runtime() + return flag_path + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize( + ("mode", "seed_rollout_log"), + [ + ("after_read_before_post_stat", True), + ("after_snapshot_before_line86", True), + ("created_after_enoent", False), + ], +) +def test_status_agent_lane_never_emits_stale_resume_ready_on_mid_read_pr_merge_toctou( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, + mode: str, + seed_rollout_log: bool, +) -> None: + registry, runtime, log_path = _write_pr_wait_status_fixture( + tmp_path, provider=provider, seed_rollout_log=seed_rollout_log + ) + flag_path = _install_rollout_toctou_preload( + tmp_path, monkeypatch, log_path=log_path, mode=mode + ) + try: + payload, rendered_md = _run_status_cli(registry, runtime, agent_id=AGENT_ID) + finally: + restart_effect_runtime() + + assert flag_path.is_file(), f"expected {mode} TOCTOU window hook to fire" + assert payload["ok"] is True + item = payload["attention_queue"]["items"][0] + agent_todos = item["agent_todos"] + assert agent_todos["items"][0]["todo_id"] == "todo_wait_pr_41" + assert agent_todos["items"][0]["resume_ready"] is True + assert agent_todos["deferred_work_counts"]["ready"] == 1 + assert agent_todos["deferred_work_counts"]["blocked"] == 0 + frontier = item["project_asset"]["agent_scope_frontier"] + assert frontier["action"] == "successor_replan_required" + assert frontier["deferred_resume_candidates"][0]["todo_id"] == "todo_wait_pr_41" + assert frontier["deferred_resume_candidates"][0]["resume_ready"] is True + assert "todo_wait_pr_41" in rendered_md + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_status_agent_lane_recovers_when_pr_merge_lands_between_collect_status_and_batch_check( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + import loopx.cli_commands.status as status_cli_module + + registry, runtime, log_path = _write_pr_wait_status_fixture( + tmp_path, provider=provider, seed_rollout_log=True + ) + original_attach = status_cli_module.attach_agent_lane_next_actions + appended = False + + def append_before_first_attach(payload: dict[str, object], **kwargs: Any) -> dict[str, object]: + nonlocal appended + if not appended: + appended = True + append_rollout_event( + log_path, + build_rollout_event( + goal_id=GOAL_ID, + event_kind="pr_merge", + agent_id=AGENT_ID, + pr_ref=f"{REPO_SLUG}#41", + status="merged", + summary="PR 41 merged before quota batch.", + recorded_at="2026-11-24T10:05:00Z", + ), + ) + return original_attach(payload, **kwargs) + + monkeypatch.setattr(status_cli_module, "attach_agent_lane_next_actions", append_before_first_attach) + payload, _ = _run_status_cli(registry, runtime, agent_id=AGENT_ID) + + assert appended is True + assert payload["ok"] is True + item = payload["attention_queue"]["items"][0] + assert item["agent_todos"]["items"][0]["todo_id"] == "todo_wait_pr_41" + assert item["agent_todos"]["items"][0]["resume_ready"] is True + assert item["agent_todos"]["deferred_work_counts"]["ready"] == 1 + assert item["project_asset"]["agent_scope_frontier"]["action"] == "successor_replan_required" + assert item["project_asset"]["agent_scope_frontier"]["deferred_resume_candidates"][0]["resume_ready"] is True + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_status_agent_lane_fails_closed_after_exhausted_canonical_source_retries( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + import loopx.cli_commands.status as status_cli_module + + registry, runtime, log_path = _write_pr_wait_status_fixture( + tmp_path, provider=provider, seed_rollout_log=True + ) + original_attach = status_cli_module.attach_agent_lane_next_actions + propagate_flags: list[bool] = [] + + def append_twice_before_attach(payload: dict[str, object], **kwargs: Any) -> dict[str, object]: + attempt_idx = len(propagate_flags) + propagate_flags.append(bool(kwargs.get("propagate_stale_canonical_source", True))) + if attempt_idx == 0: + append_rollout_event( + log_path, + build_rollout_event( + goal_id=GOAL_ID, + event_kind="evidence_log_read", + agent_id=AGENT_ID, + status="completed", + summary="First concurrent log event before quota batch.", + recorded_at="2026-11-24T10:04:00Z", + ), + ) + elif attempt_idx == 1: + append_rollout_event( + log_path, + build_rollout_event( + goal_id=GOAL_ID, + event_kind="pr_merge", + agent_id=AGENT_ID, + pr_ref=f"{REPO_SLUG}#41", + status="merged", + summary="Second concurrent log event (PR 41 merged) during retry.", + recorded_at="2026-11-24T10:05:00Z", + ), + ) + return original_attach(payload, **kwargs) + + monkeypatch.setattr(status_cli_module, "attach_agent_lane_next_actions", append_twice_before_attach) + exit_code, payload, rendered_md = _run_status_cli_with_exit( + registry, runtime, agent_id=AGENT_ID + ) + + assert propagate_flags == [True, True] + assert exit_code == 1 + assert payload["ok"] is False + assert payload["code"] == "quota_canonical_source_changed" + assert payload["error_code"] == "quota_canonical_source_changed" + assert payload["retry_attempts"] == 2 + assert payload["registry"] == str(registry) + assert payload["runtime_root"] == str(runtime) + assert "quota canonical source changed" in str(payload.get("error") or "") + assert payload["attention_queue"]["available"] is False + assert payload["attention_queue"]["items"][0]["status"] == "status_collection_failed" + assert "agent_todos" not in payload["attention_queue"]["items"][0] + assert "- ok: `False`" in rendered_md + assert "status_collection_failed" in rendered_md + + # Subsequent clean read with no concurrent append succeeds and exposes ready frontier. + clean_payload, _ = _run_status_cli(registry, runtime, agent_id=AGENT_ID) + assert clean_payload["ok"] is True + clean_item = clean_payload["attention_queue"]["items"][0] + assert clean_item["agent_todos"]["items"][0]["resume_ready"] is True + assert clean_item["project_asset"]["agent_scope_frontier"]["action"] == "successor_replan_required" + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_review_packet_fails_closed_after_exhausted_canonical_source_retries( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + import loopx.cli_commands.status as status_cli_module + + registry, runtime, log_path = _write_pr_wait_status_fixture( + tmp_path, provider=provider, seed_rollout_log=True + ) + original_attach = status_cli_module.attach_agent_lane_next_actions + calls = 0 + + def append_twice_before_attach(payload: dict[str, object], **kwargs: Any) -> dict[str, object]: + nonlocal calls + calls += 1 + if calls <= 2: + append_rollout_event( + log_path, + build_rollout_event( + goal_id=GOAL_ID, + event_kind="evidence_log_read", + agent_id=AGENT_ID, + status="completed", + summary=f"Concurrent log event #{calls} during review packet.", + recorded_at=f"2026-11-24T10:0{calls}:00Z", + ), + ) + return original_attach(payload, **kwargs) + + monkeypatch.setattr(status_cli_module, "attach_agent_lane_next_actions", append_twice_before_attach) + captured: list[dict[str, Any]] = [] + args = argparse.Namespace( + limit=5, + handoff_only=False, + goal_id=GOAL_ID, + available_capabilities=["shell"], + agent_id=AGENT_ID, + action_kind=None, + review_url=None, + review_packet_format="json", + ) + exit_code = handle_review_packet_command( + args, + registry_path=registry, + runtime_root_arg=str(runtime), + output_format=lambda _args, _attr=None: "json", + print_payload=lambda value, _fmt, _renderer: captured.append(value), + ) + + assert calls == 2 + assert exit_code == 1 + assert len(captured) == 1 + assert captured[0]["ok"] is False + assert captured[0]["code"] == "quota_canonical_source_changed" + assert captured[0]["error_code"] == "quota_canonical_source_changed" + assert captured[0]["retry_attempts"] == 2 + assert captured[0]["goal_id"] == GOAL_ID + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_heartbeat_prequota_empty_fastpath_skips_rollout_scans_with_parity( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + registry, runtime, _ = _write_goal_fixture( + tmp_path, + provider=provider, + deferred_count=4, + include_pr_wait=False, + include_pr_review_gate=False, + capability_granted=True, + ) + _append_unrelated_rollout_events(runtime, 50) + + calls = _capture_rpc_calls(monkeypatch) + rollout_scans: list[Path] = [] + original_load = rollout_event_log_module.load_rollout_events + + def tracked_load(path: Path, **kwargs: Any) -> list[dict[str, Any]]: + rollout_scans.append(path) + return original_load(path, **kwargs) + + monkeypatch.setattr(rollout_event_log_module, "load_rollout_events", tracked_load) + + result = run_heartbeat_pre_quota( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) + methods = [method for method, _ in calls] + + assert result["ok"] is True + assert result["degraded"] is False + assert result["checks"]["acknowledged_pr_reviews"]["reconciled_count"] == 0 + assert result["checks"]["acknowledged_pr_reviews"]["ack_receipt_count"] == 0 + assert result["checks"]["pr_dependencies"]["external_read_count"] == 0 + assert len(rollout_scans) == 0 + assert methods.count("todo.read") == 1 + assert methods.count("todo.pr_wait_observation.plan") == 1 + assert "- reconciled_count: `0`" in render_heartbeat_pre_quota_markdown(result) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_heartbeat_prequota_shares_todo_read_and_preserves_active_wait_and_ack_recovery( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + registry, runtime, state = _write_goal_fixture( + tmp_path, + provider=provider, + deferred_count=2, + include_pr_wait=True, + include_pr_review_gate=True, + capability_granted=True, + ) + _append_unrelated_rollout_events(runtime, 30) + pr_url = f"https://github.com/{REPO_SLUG}/pull/41" + record_issue_fix_pr_review_ack( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + todo_id="todo_pr_review_41", + agent_id=AGENT_ID, + project=state.parent, + url=pr_url, + owner_acknowledged=True, + generated_at="2026-11-24T09:10:00Z", + ) + + # Record a recent validation event for #41 so pr_wait_reconcile uses TS rollout log readback. + append_rollout_event( + rollout_event_log_path(runtime, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="validation", + agent_id=AGENT_ID, + pr_ref=f"{REPO_SLUG}#41", + classification="pr_wait_observation", + status="OPEN", + summary="Recent check within cooldown.", + recorded_at=datetime.now(timezone.utc) + .replace(microsecond=0) + .isoformat() + .replace("+00:00", "Z"), + ), + ) + + calls = _capture_rpc_calls(monkeypatch) + # 1) Historical/unmutated parity when external PR state is still OPEN (fetch_metadata=False): + # reconcile_acknowledged_issue_fix_pr_reviews + pr_wait_reconcile share ONE todo.read. + baseline_ack = reconcile_acknowledged_issue_fix_pr_reviews( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + project=state.parent, + fetch_metadata=False, + execute=False, + ) + baseline_wait = pr_wait_reconcile.reconcile_pr_wait_dependencies( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) + baseline_read_count = sum(m == "todo.read" for m, _ in calls) + assert baseline_read_count == 3 # 2 in pr_gate/pr_review_ack + 1 in pr_wait_reconcile + + calls.clear() + all_todos_box: dict[str, Any] = {} + + def single_query_loader() -> list[dict[str, Any]]: + if "todos" not in all_todos_box: + all_todos_box["todos"] = list_goal_todos( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + role=None, + )["todos"] + return list(all_todos_box["todos"]) + + def single_agent_loader() -> list[dict[str, Any]] | None: + if "todos" not in all_todos_box: + return None + return [t for t in all_todos_box["todos"] if t.get("role") == "agent"] + + shared_ack = reconcile_acknowledged_issue_fix_pr_reviews( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + project=state.parent, + fetch_metadata=False, + execute=False, + todo_loader=single_query_loader, + ) + shared_wait = pr_wait_reconcile.reconcile_pr_wait_dependencies( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + shared_agent_todos_loader=single_agent_loader, + ) + assert _normalize_volatile(shared_ack) == _normalize_volatile(baseline_ack) + assert _normalize_volatile(shared_wait) == _normalize_volatile(baseline_wait) + assert shared_wait["plan"]["waiting_targets"][0]["pr_ref"] == f"{REPO_SLUG}#41" + assert sum(m == "todo.read" for m, _ in calls) == 1 + + # 2) Active end-to-end prequota reconciliation when external PR reaches MERGED: + def fake_fetch(reference: Any, **kwargs: Any) -> dict[str, Any]: + return { + "url": pr_url, + "number": 41, + "state": "MERGED", + "mergedAt": "2026-11-24T09:15:00Z", + "baseRepository": {"nameWithOwner": REPO_SLUG}, + "headRepository": {"nameWithOwner": REPO_SLUG}, + } + + monkeypatch.setattr(pr_lifecycle, "fetch_github_pr_lifecycle_payload", fake_fetch) + calls.clear() + active_result = run_heartbeat_pre_quota( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) + assert active_result["checks"]["acknowledged_pr_reviews"]["reconciled_count"] == 1 + assert active_result["checks"]["acknowledged_pr_reviews"]["terminal_count"] == 1 + assert active_result["checks"]["pr_dependencies"]["external_read_count"] == 0 + # After MERGED reconciliation appended pr_merge, the deferred pr_merged wait is now satisfied! + assert active_result["checks"]["pr_dependencies"]["plan"]["waiting_targets"] == [] + user_todo = list_goal_todos( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + role="user", + todo_id="todo_pr_review_41", + )["todo"] + assert user_todo["status"] == "done" + + # 3) Next clean heartbeat-prequota turn hits single-read already_reconciled path (1 todo.read total!). + calls.clear() + second_result = run_heartbeat_pre_quota( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) + assert second_result["checks"]["acknowledged_pr_reviews"]["already_reconciled_count"] == 1 + assert second_result["checks"]["acknowledged_pr_reviews"]["reconciled_count"] == 0 + assert sum(m == "todo.read" for m, _ in calls) == 1 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_heartbeat_prequota_detects_concurrent_subprocess_todo_add_drift( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + import loopx.heartbeat_prequota as heartbeat_prequota_module + + registry, runtime, state = _write_goal_fixture( + tmp_path, + provider=provider, + deferred_count=0, + include_pr_wait=False, + include_pr_review_gate=True, + capability_granted=True, + ) + pr_url_41 = f"https://github.com/{REPO_SLUG}/pull/41" + pr_url_42 = f"https://github.com/{REPO_SLUG}/pull/42" + record_issue_fix_pr_review_ack( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + todo_id="todo_pr_review_41", + agent_id=AGENT_ID, + project=state.parent, + url=pr_url_41, + owner_acknowledged=True, + generated_at="2026-11-24T09:10:00Z", + ) + + pr_wait_list_calls = 0 + original_pr_wait_list = cast( + "Callable[..., dict[str, Any]]", + getattr(pr_wait_reconcile, "list_goal_todos"), + ) + + def tracked_pr_wait_list(*args: Any, **kwargs: Any) -> dict[str, Any]: + nonlocal pr_wait_list_calls + pr_wait_list_calls += 1 + return original_pr_wait_list(*args, **kwargs) + + monkeypatch.setattr(pr_wait_reconcile, "list_goal_todos", tracked_pr_wait_list) + + concurrent_add_committed = False + observed_pr_numbers: list[int] = [] + + def fake_fetch(reference: Any, **kwargs: Any) -> dict[str, Any]: + nonlocal concurrent_add_committed + number = int(reference["number"]) + observed_pr_numbers.append(number) + if number == 41 and not concurrent_add_committed: + concurrent_add_committed = True + proc = subprocess.run( + [ + sys.executable, + "-m", + "loopx.cli", + "--registry", + str(registry), + "--runtime-root", + str(runtime), + "--format", + "json", + "todo", + "add", + "--goal-id", + GOAL_ID, + "--role", + "agent", + "--status", + "deferred", + "--priority", + "P1", + "--task-class", + "advancement_task", + "--action-kind", + "validate", + "--task-repository", + f"git:github.com/{REPO_SLUG}", + "--resume-when", + f"pr_merged:{REPO_SLUG}#42", + "--text", + "[P1] Resume follow-up after PR 42 merges", + ], + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, proc.stderr + proc.stdout + added_payload = json.loads(proc.stdout) + assert added_payload["ok"] is True + return { + "url": pr_url_42 if number == 42 else pr_url_41, + "number": number, + "state": "OPEN", + "baseRepository": {"nameWithOwner": REPO_SLUG}, + "headRepository": {"nameWithOwner": REPO_SLUG}, + } + + monkeypatch.setattr(pr_lifecycle, "fetch_github_pr_lifecycle_payload", fake_fetch) + + calls = _capture_rpc_calls(monkeypatch) + + # 1) During ACK's OPEN #41 read, another CLI subprocess commits `todo add` for #42. + # PR dependency planning must detect provider_revision/cursor drift, re-read authoritative + # Todos, plan #42, and execute 1 external observation in the SAME cycle. + drifted = run_heartbeat_pre_quota( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) + drifted_methods = [method for method, _ in calls] + assert drifted["ok"] is True + assert concurrent_add_committed is True + assert observed_pr_numbers == [41, 42] + assert drifted["checks"]["acknowledged_pr_reviews"]["reconciled_count"] == 0 + assert drifted["checks"]["pr_dependencies"]["external_read_count"] == 1 + assert [row["pr_ref"] for row in drifted["checks"]["pr_dependencies"]["results"]] == [ + f"{REPO_SLUG}#42" + ] + assert ( + drifted["checks"]["pr_dependencies"]["plan"]["waiting_targets"][0]["pr_ref"] + == f"{REPO_SLUG}#42" + ) + assert drifted_methods.count("todo.authority_head.verify") == 1 + assert pr_wait_list_calls == 1 + + # 2) Control case with NO concurrent write: shared_todo_cache witness matches live head + # so PR dependency planning reuses the cached snapshot with ZERO duplicate list_goal_todos calls. + calls.clear() + pr_wait_list_calls = 0 + observed_pr_numbers.clear() + reused = run_heartbeat_pre_quota( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) + reused_methods = [method for method, _ in calls] + assert reused["ok"] is True + assert observed_pr_numbers == [41] + assert ( + reused["checks"]["pr_dependencies"]["plan"]["waiting_targets"][0]["pr_ref"] + == f"{REPO_SLUG}#42" + ) + assert reused_methods.count("todo.authority_head.verify") == 1 + assert pr_wait_list_calls == 0 + + # 3) Fail-closed verification error: if live witness verification errors, fall back to + # an authoritative list_goal_todos read without crashing or returning stale Todos. + from loopx.control_plane.effect_runtime import EffectRuntimeStartupError + + original_witness_rpc = getattr(heartbeat_prequota_module, "effect_runtime_result") + + def failing_witness_rpc(method: str, *args: Any, **kwargs: Any) -> Any: + if method == "todo.authority_head.verify": + raise EffectRuntimeStartupError( + "witness check unavailable", + diagnostic_code="startup_failed", + ) + return original_witness_rpc(method, *args, **kwargs) + + monkeypatch.setattr( + heartbeat_prequota_module, + "effect_runtime_result", + failing_witness_rpc, + ) + pr_wait_list_calls = 0 + fail_closed = run_heartbeat_pre_quota( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + agent_id=AGENT_ID, + ) + assert fail_closed["ok"] is True + assert pr_wait_list_calls == 1 + monkeypatch.setattr( + heartbeat_prequota_module, + "effect_runtime_result", + original_witness_rpc, + ) diff --git a/tests/control_plane_ts/todo_read.test.ts b/tests/control_plane_ts/todo_read.test.ts index 0ff417a856..f01e132667 100644 --- a/tests/control_plane_ts/todo_read.test.ts +++ b/tests/control_plane_ts/todo_read.test.ts @@ -1,9 +1,13 @@ import assert from "node:assert/strict"; -import {mkdtemp, writeFile, rm} from "node:fs/promises"; +import {appendFileSync, writeFileSync} from "node:fs"; +import fsPromises, {appendFile, mkdtemp, rm, writeFile} from "node:fs/promises"; +import {syncBuiltinESMExports} from "node:module"; import {tmpdir} from "node:os"; import {join} from "node:path"; import test from "node:test"; import {readTodo, TODO_READ_REQUEST} from "../../loopx/control_plane/todos/read_projection.ts"; +import {projectCanonicalQuotaBatch, readCanonicalTodoProjection, verifyCanonicalTodoAuthorityWitness} from "../../loopx/control_plane/todos/read_transaction.ts"; +import {goalRolloutEventLogPath} from "../../loopx/control_plane/rollout_receipt_log.ts"; import {readAgent, readScope} from "../../loopx/control_plane/todos/read_codec.ts"; import type {JsonObject} from "../../loopx/control_plane/effect_program.ts"; import {openLocalAuthorityStore, selectLocalSqliteAuthority} from "../../loopx/control_plane/coordination/local_authority_provider.ts"; @@ -378,3 +382,262 @@ test("query display limits preserve complete source coverage and report the fina source: {runtime_root: root, goal_id: goal}, observed_at: Date.parse(now) / 1000, evaluated_at: now, query: {goal_id: goal, todo_id: items[0].todo_id, read_scope: "active", state_file: state}}), /invalid summary completion coordinates/); }); + +for (const provider of ["file", "sqlite"] as const) { + test(`${provider} canonical rollout_log_stat refuses mid-read pr_merge TOCTOU and binds strictly to consumed snapshot`, async t => { + const root = await mkdtemp(join(tmpdir(), "loopx-todo-rollout-toctou-")); + t.after(() => rm(root, {recursive: true, force: true})); + const state = join(root, "state.md"), goal = "goal-toctou"; + await writeFile(state, "# Synthetic Goal\n"); + if (provider === "sqlite") await selectLocalSqliteAuthority(root, goal, true); + const store = await openLocalAuthorityStore(root, goal); + const waiting = row("todo_wait_pr", { + status: "deferred", done: true, task_repository: "git:github.com/example/hotpath", + resume_when: "pr_merged:#41", + }); + const projection = { + goal_id: goal, handoff_mode: "soft_claim", todos: [waiting], leases: [], + todo_read_model: coordinationTodoReadModel([waiting], TODO_CANONICAL_READ_RECORD_SCHEMA), + }; + const committed = await store.commitAuthority({ + expected_provider_revision: null, operation_id: "seed-toctou", events: [], next_projection: projection, receipts: [], + }); + assert.equal(committed.status, "applied"); + if (committed.status !== "applied") return; + const fence = await engageLegacyCoordinationWriterFence({ + schema_version: "loopx_legacy_coordination_writer_fence_engage_request_v0", + runtime_root: root, goal_id: goal, state_path: state, + fence: { + schema_version: "loopx_legacy_coordination_writer_fence_v0", state: "engaged", + goal_id: goal, fence_id: "toctou-fixture", source_version: "fixture", + source_projection_sha256: canonicalAuthoritySha256(projection), + expected_shadow_provider_revision: committed.provider_revision, + }, + }); + assert.equal(fence.status, "applied"); + + const logPath = goalRolloutEventLogPath(root, goal); + const baseEvent = JSON.stringify({ + schema_version: "loopx_rollout_event_v0", event_kind: "evidence_log_read", + goal_id: goal, event_id: "ev-base-1", recorded_at: "2026-11-24T09:00:00Z", + }) + "\n"; + const mergeEvent = JSON.stringify({ + schema_version: "loopx_rollout_event_v0", event_kind: "pr_merge", + goal_id: goal, event_id: "ev-merge-41", pr_ref: "example/hotpath#41", + recorded_at: "2026-11-24T10:00:00Z", + }) + "\n"; + const readReq: JsonObject = { + schema_version: TODO_READ_REQUEST, kind: "canonical_fields", + source: {runtime_root: root, goal_id: goal}, + rollout_event_source: {runtime_root: root, goal_id: goal}, + rollout_events: [], observed_at: Date.parse(now) / 1000, evaluated_at: now, + }; + + const origReadFile = fsPromises.readFile.bind(fsPromises); + const origStat = fsPromises.stat.bind(fsPromises); + + // 1) Missing log (ENOENT) created with pr_merge before post-projection stat check -> refuse reuse. + { + let injected = false; + const readHook = t.mock.method(fsPromises, "readFile", async (pathArg: unknown, ...rest: unknown[]) => { + try { + return await (origReadFile as (...args: unknown[]) => Promise)(pathArg, ...rest); + } catch (error) { + if (!injected && pathArg === logPath && (error as NodeJS.ErrnoException)?.code === "ENOENT") { + injected = true; + writeFileSync(logPath, mergeEvent, "utf8"); + } + throw error; + } + }); + syncBuiltinESMExports(); + try { + const res = await readCanonicalTodoProjection(readReq); + assert.equal(injected, true); + assert.equal(res.rollout_log_stat, undefined); + } finally { + readHook.mock.restore(); + syncBuiltinESMExports(); + } + } + + // 2) Append during readFile (preStat !== postStat) -> refuse reuse. + await writeFile(logPath, baseEvent, "utf8"); + { + let injected = false; + const readHook = t.mock.method(fsPromises, "readFile", async (pathArg: unknown, ...rest: unknown[]) => { + const bytes = await (origReadFile as (...args: unknown[]) => Promise)(pathArg, ...rest); + if (!injected && pathArg === logPath) { + injected = true; + appendFileSync(logPath, mergeEvent, "utf8"); + } + return bytes; + }); + syncBuiltinESMExports(); + try { + const res = await readCanonicalTodoProjection(readReq); + assert.equal(injected, true); + assert.equal(res.rollout_log_stat, undefined); + } finally { + readHook.mock.restore(); + syncBuiltinESMExports(); + } + } + + // 3) Append strictly after readReceiptLogSnapshotWithStat post-stat and before read_transaction post-projection stat -> refuse reuse. + await writeFile(logPath, baseEvent, "utf8"); + { + let sawRead = false; + let injected = false; + const readHook = t.mock.method(fsPromises, "readFile", async (pathArg: unknown, ...rest: unknown[]) => { + const bytes = await (origReadFile as (...args: unknown[]) => Promise)(pathArg, ...rest); + if (pathArg === logPath) sawRead = true; + return bytes; + }); + const statHook = t.mock.method(fsPromises, "stat", async (pathArg: unknown, ...rest: unknown[]) => { + const info = await (origStat as (...args: unknown[]) => Promise)(pathArg, ...rest); + if (sawRead && !injected && pathArg === logPath) { + injected = true; + appendFileSync(logPath, mergeEvent, "utf8"); + } + return info; + }); + syncBuiltinESMExports(); + try { + const res = await readCanonicalTodoProjection(readReq); + assert.equal(injected, true); + assert.equal(res.rollout_log_stat, undefined); + const sourceIdentity = (res.source_projection as JsonObject).source; + await assert.rejects(() => projectCanonicalQuotaBatch({ + schema_version: "todo_quota_planning_batch_v0", + authority_checks: [{read: readReq, expected_source: sourceIdentity}], + requests: [], + }), /quota canonical source changed|requires one or two/); + await assert.rejects(() => projectCanonicalQuotaBatch({ + schema_version: "todo_quota_planning_batch_v0", + authority_checks: [{read: readReq, expected_source: sourceIdentity}], + requests: [{schema_version: "todo_quota_planning_request_v4", current_time: now}], + }), /quota canonical source changed/); + } finally { + readHook.mock.restore(); + statHook.mock.restore(); + syncBuiltinESMExports(); + } + } + + // 4) Clean read binds rollout_log_stat; subsequent pr_merge invalidates batch check; re-read observes resume_ready=true. + await writeFile(logPath, baseEvent, "utf8"); + const before = await readCanonicalTodoProjection(readReq); + assert.ok(before.rollout_log_stat, "clean read must bind rollout_log_stat"); + const beforeItems = ((before.fields as JsonObject).agent_todos as JsonObject).items as JsonObject[]; + assert.equal(beforeItems[0].resume_ready, false); + const sourceIdentity = (before.source_projection as JsonObject).source; + await appendFile(logPath, mergeEvent, "utf8"); + await assert.rejects(() => projectCanonicalQuotaBatch({ + schema_version: "todo_quota_planning_batch_v0", + authority_checks: [{read: readReq, expected_source: sourceIdentity, rollout_log_stat: before.rollout_log_stat}], + requests: [{schema_version: "todo_quota_planning_request_v4", current_time: now}], + }), /quota canonical source changed/); + const after = await readCanonicalTodoProjection(readReq); + assert.ok(after.rollout_log_stat); + const afterItems = ((after.fields as JsonObject).agent_todos as JsonObject).items as JsonObject[]; + assert.equal(afterItems[0].resume_ready, true); + }); +} + +for (const provider of ["file", "sqlite"] as const) { + test(`verifyCanonicalTodoAuthorityWitness detects ${provider} revision/cursor drift cleanly`, async t => { + const root = await mkdtemp(join(tmpdir(), `witness-${provider}-`)); + t.after(() => rm(root, {recursive: true, force: true})); + const state = join(root, "state.md"); + const goal = `witness-goal-${provider}`; + await writeFile(state, "# Synthetic Goal\n"); + if (provider === "sqlite") await selectLocalSqliteAuthority(root, goal, true); + const store = await openLocalAuthorityStore(root, goal); + const baseTodos = [row("todo_a", {index: 1})]; + const baseProjection = { + goal_id: goal, handoff_mode: "soft_claim", todos: baseTodos, leases: [], + todo_read_model: coordinationTodoReadModel(baseTodos, TODO_CANONICAL_READ_RECORD_SCHEMA), + }; + const commit1 = await store.commitAuthority({ + expected_provider_revision: null, + operation_id: "seed-witness-1", + events: [], + receipts: [], + next_projection: baseProjection, + }); + assert.equal(commit1.status, "applied"); + if (commit1.status !== "applied") return; + const fence = await engageLegacyCoordinationWriterFence({ + schema_version: "loopx_legacy_coordination_writer_fence_engage_request_v0", + runtime_root: root, goal_id: goal, state_path: state, + fence: { + schema_version: "loopx_legacy_coordination_writer_fence_v0", state: "engaged", + goal_id: goal, fence_id: `witness-fence-${provider}`, source_version: "fixture", + source_projection_sha256: canonicalAuthoritySha256(baseProjection), + expected_shadow_provider_revision: commit1.provider_revision, + }, + }); + assert.equal(fence.status, "applied"); + + const sourceAuthority = `${provider}_v0`; + const matched = await verifyCanonicalTodoAuthorityWitness({ + schema_version: "todo_authority_head_verify_v0", + runtime_root: root, + goal_id: goal, + expected_witness: { + source_authority: sourceAuthority, + provider_revision: commit1.provider_revision, + cursor: commit1.cursor, + }, + }); + assert.equal(matched.fresh, true); + assert.equal(matched.reason_code, "matched"); + + const incomplete = await verifyCanonicalTodoAuthorityWitness({ + schema_version: "todo_authority_head_verify_v0", + runtime_root: root, + goal_id: goal, + expected_witness: { + source_authority: sourceAuthority, + provider_revision: "", + cursor: commit1.cursor, + }, + }); + assert.equal(incomplete.fresh, false); + assert.equal(incomplete.reason_code, "expected_witness_incomplete"); + + const nextTodos = [ + row("todo_a", {index: 1}), + row("todo_b", {index: 2, status: "deferred", resume_when: "pr_merged:example/hotpath#42"}), + ]; + const nextProjection = { + goal_id: goal, handoff_mode: "soft_claim", todos: nextTodos, leases: [], + todo_read_model: coordinationTodoReadModel(nextTodos, TODO_CANONICAL_READ_RECORD_SCHEMA), + }; + const commit2 = await store.commitAuthority({ + expected_provider_revision: commit1.provider_revision, + operation_id: "seed-witness-2", + events: [], + receipts: [], + next_projection: nextProjection, + }); + assert.equal(commit2.status, "applied"); + if (commit2.status !== "applied") return; + + const drifted = await verifyCanonicalTodoAuthorityWitness({ + schema_version: "todo_authority_head_verify_v0", + runtime_root: root, + goal_id: goal, + expected_witness: { + source_authority: sourceAuthority, + provider_revision: commit1.provider_revision, + cursor: commit1.cursor, + }, + }); + assert.equal(drifted.fresh, false); + assert.equal(drifted.reason_code, "canonical_witness_drifted"); + assert.equal(drifted.provider_revision, commit2.provider_revision); + assert.equal(drifted.cursor, commit2.cursor); + }); +}