diff --git a/loopx/control_plane/work_items/attention_queue.py b/loopx/control_plane/work_items/attention_queue.py index 11b9fcc9e2..b1d6271cba 100644 --- a/loopx/control_plane/work_items/attention_queue.py +++ b/loopx/control_plane/work_items/attention_queue.py @@ -1,84 +1,80 @@ +"""Attention queue projection builder for global Goal and health work items.""" from __future__ import annotations -from dataclasses import dataclass +from collections.abc import Sequence, Set as AbstractSet from pathlib import Path -from typing import AbstractSet, Any, Callable, Optional +from typing import cast -from .replan_history_codec import effective_turn_cadence_context - -from ..goals.legacy_event_source import RetiredTodoEventSourceError from ..coordination.local_authority import LocalCoordinationAuthorityUnavailable from ..effect_runtime import effect_runtime_result +from ..goals.legacy_event_source import RetiredTodoEventSourceError +from .attention_queue_types import ( + ACTIONABLE_REGISTRY_SEVERITIES as ACTIONABLE_REGISTRY_SEVERITIES, + USER_OR_CONTROLLER_WAIT_STATES as USER_OR_CONTROLLER_WAIT_STATES, + ActiveStateProjectAssetAttacher as ActiveStateProjectAssetAttacher, + ActiveStateTodoAttentionBuilder as ActiveStateTodoAttentionBuilder, + ActiveStateTodoFieldsBuilder as ActiveStateTodoFieldsBuilder, + AttentionItemBuilder as AttentionItemBuilder, + AttentionQueueContext as AttentionQueueContext, + AttentionQueueCounts as AttentionQueueCounts, + AttentionQueueProjection as AttentionQueueProjection, + AttentionWaitingOn as AttentionWaitingOn, + EnrichProjectAssetFn as EnrichProjectAssetFn, + ExternalProgressReviewLoader as ExternalProgressReviewLoader, + GlobalRegistryFindingSeverity as GlobalRegistryFindingSeverity, + GlobalRegistryShadowAttacher as GlobalRegistryShadowAttacher, + GoalChannelProjectionAttacher as GoalChannelProjectionAttacher, + LatestRunRecommendedActionBuilder as LatestRunRecommendedActionBuilder, + QuotaHandoffFloorBuilder as QuotaHandoffFloorBuilder, + QuotaStatusBuilder as QuotaStatusBuilder, + TaskGraphProjectionBuilder as TaskGraphProjectionBuilder, +) +from .replan_history_codec import effective_turn_cadence_context -AttentionItemBuilder = Callable[..., dict[str, Any]] -GlobalRegistryShadowAttacher = Callable[[dict[str, Any], dict[str, Any]], None] - - -@dataclass(frozen=True) -class AttentionQueueContext: - active_state_todo_fields: Callable[..., dict[str, Any]] - active_state_todo_attention_item: Callable[..., dict[str, Any] | None] - latest_run: Callable[[dict[str, Any]], dict[str, Any] | None] - goal_attention: Callable[[dict[str, Any]], dict[str, Any] | None] - compact_agent_lane_recommendation: Callable[[dict[str, Any] | None], dict[str, Any] | None] - latest_agent_lane_run: Callable[[dict[str, Any]], dict[str, Any] | None] - latest_run_recommended_action_for_projection: Callable[..., tuple[str | None, str | None]] - compact_autonomous_replan_ack: Callable[[dict[str, Any] | None], dict[str, Any] | None] - latest_autonomous_replan_ack_for_projection: Callable[[list[dict[str, Any]] | None], dict[str, Any] | None] - compact_control_plane_policy: Callable[[Any], dict[str, Any]] - subagent_activity_for_goal: Callable[[dict[str, Any]], dict[str, Any] | None] - interface_budget_cadence_for_runs: Callable[[list[dict[str, Any]]], dict[str, Any] | None] - active_state_projection_warning: Callable[[dict[str, Any], dict[str, Any] | None], dict[str, Any] | None] - enrich_project_asset: Callable[..., None] - project_asset_latest_validation: Callable[[dict[str, Any] | None], dict[str, Any] | None] - attach_active_state_project_asset_fields: Callable[..., object] - sync_connected_attention_action_from_todos: Callable[[dict[str, Any]], None] - quota_status: Callable[..., dict[str, Any]] - quota_with_handoff_outcome_floor: Callable[..., dict[str, Any]] - normalize_monitor_quiet_attention_display: Callable[[dict[str, Any]], None] - build_task_graph_projection: Callable[..., dict[str, Any] | None] - attach_goal_channel_projection: Callable[..., None] - attach_dependency_blockers: Callable[[list[dict[str, Any]]], None] - autonomous_backlog_candidates: Callable[[list[dict[str, Any]]], dict[str, Any] | None] - autonomous_monitor_candidates: Callable[[list[dict[str, Any]]], dict[str, Any] | None] - attention_item: AttentionItemBuilder - attach_global_registry_shadow_finding: GlobalRegistryShadowAttacher - next_action_projection_warning: Callable[..., dict[str, Any] | None] - autonomous_replan_obligation_from_runs: Callable[..., dict[str, Any] | None] - source_registry_shadow_findings: AbstractSet[str] - monitor_signal_waiting_on: str - registry_path: Path | None = None - external_progress_review_context: Optional[Callable[..., dict[str, Any] | None]] = None - tolerate_malformed_settlement_history: bool = False +def _sequence_or_empty(raw: object, *, field_name: str) -> Sequence[object]: + """Accept valid sequences and legacy empty containers; fail closed on bad scalars.""" + + if raw is None or raw == [] or raw == {} or raw == (): + return () + if isinstance(raw, Sequence) and not isinstance(raw, (str, bytes, bytearray)): + return raw + raise TypeError(f"{field_name} must be a sequence") + + +def _optional_dict(value: object) -> dict[str, object] | None: + return cast(dict[str, object], value) if isinstance(value, dict) else None def merge_global_registry_findings( *, - health_items: list[dict[str, Any]], - history_items: list[dict[str, Any]], - findings: list[Any], - goal_id_filter: Optional[str], + health_items: list[dict[str, object]], + history_items: list[dict[str, object]], + findings: Sequence[object], + goal_id_filter: str | None, source_registry_shadow_findings: AbstractSet[str], attention_item: AttentionItemBuilder, attach_global_registry_shadow_finding: GlobalRegistryShadowAttacher, ) -> None: - live_quota_items_by_goal: dict[str, list[dict[str, Any]]] = {} + live_quota_items_by_goal: dict[str, list[dict[str, object]]] = {} for item in history_items: if isinstance(item.get("quota"), dict): - live_quota_items_by_goal.setdefault(str(item.get("goal_id") or ""), []).append(item) + live_quota_items_by_goal.setdefault( + str(item.get("goal_id") or ""), [] + ).append(item) for finding in findings: if not isinstance(finding, dict): continue - if finding.get("severity") not in {"high", "action"}: + if finding.get("severity") not in ACTIONABLE_REGISTRY_SEVERITIES: continue goal_id = str(finding.get("goal_id") or "global-registry") if goal_id_filter: + raw_goal_ids = _sequence_or_empty( + finding.get("goal_ids"), field_name="finding.goal_ids" + ) finding_goal_ids = [ - str(item) - for item in (finding.get("goal_ids") or []) - if str(item or "").strip() + str(item) for item in raw_goal_ids if str(item or "").strip() ] if goal_id != goal_id_filter and goal_id_filter not in finding_goal_ids: continue @@ -93,7 +89,9 @@ def merge_global_registry_findings( status=str(finding.get("kind") or "global_registry_finding"), waiting_on="codex", severity=str(finding.get("severity") or "action"), - recommended_action=str(finding.get("recommended_action") or "inspect global registry health"), + recommended_action=str( + finding.get("recommended_action") or "inspect global registry health" + ), source="global_registry", ) ) @@ -101,22 +99,38 @@ def merge_global_registry_findings( def build_attention_queue_projection( *, - items: list[dict[str, Any]], - goal_id_filter: Optional[str], - autonomous_backlog_candidates: Optional[dict[str, Any]], - autonomous_monitor_candidates: Optional[dict[str, Any]], + items: list[dict[str, object]], + goal_id_filter: str | None, + autonomous_backlog_candidates: dict[str, object] | None, + autonomous_monitor_candidates: dict[str, object] | None, monitor_signal_waiting_on: str, -) -> dict[str, Any]: - queue: dict[str, Any] = { +) -> dict[str, object]: + needs_user_or_controller = 0 + needs_controller = 0 + needs_codex = 0 + watching_external_evidence = 0 + watching_monitor = 0 + for item in items: + waiting_on = item["waiting_on"] + if waiting_on in USER_OR_CONTROLLER_WAIT_STATES: + needs_user_or_controller += 1 + if waiting_on == "controller": + needs_controller += 1 + elif waiting_on == "codex": + needs_codex += 1 + elif waiting_on == "external_evidence": + watching_external_evidence += 1 + if waiting_on == monitor_signal_waiting_on: + watching_monitor += 1 + + queue: dict[str, object] = { "available": True, "item_count": len(items), - "needs_user_or_controller": sum( - 1 for item in items if item["waiting_on"] in {"user_or_controller", "controller"} - ), - "needs_controller": sum(1 for item in items if item["waiting_on"] == "controller"), - "needs_codex": sum(1 for item in items if item["waiting_on"] == "codex"), - "watching_external_evidence": sum(1 for item in items if item["waiting_on"] == "external_evidence"), - "watching_monitor": sum(1 for item in items if item["waiting_on"] == monitor_signal_waiting_on), + "needs_user_or_controller": needs_user_or_controller, + "needs_controller": needs_controller, + "needs_codex": needs_codex, + "watching_external_evidence": watching_external_evidence, + "watching_monitor": watching_monitor, "items": items, } if goal_id_filter: @@ -130,28 +144,44 @@ def build_attention_queue_projection( def _reconcile_active_state_item( - goal: dict[str, Any], - current_run: dict[str, Any] | None, - item: dict[str, Any], - active_state_item: dict[str, Any] | None, + goal: dict[str, object], + current_run: dict[str, object] | None, + item: dict[str, object], + active_state_item: dict[str, object] | None, context: AttentionQueueContext, -) -> tuple[dict[str, Any], dict[str, Any] | None]: +) -> tuple[dict[str, object], dict[str, object] | None]: warning = context.active_state_projection_warning(goal, current_run) if not warning: return item, None - reconciled = effect_runtime_result("presentation.goal_attention.reconcile", { - "item": item, "active_state_item": active_state_item, - "warning": warning, "historical_run": current_run, - }) - return reconciled["item"], reconciled["warning"] + reconciled = effect_runtime_result( + "presentation.goal_attention.reconcile", + { + "item": item, + "active_state_item": active_state_item, + "warning": warning, + "historical_run": current_run, + }, + ) + reconciled_item = reconciled["item"] + reconciled_warning = reconciled["warning"] + if not isinstance(reconciled_item, dict): + raise TypeError("presentation.goal_attention.reconcile item must be a dict") + if reconciled_warning is not None and not isinstance(reconciled_warning, dict): + raise TypeError( + "presentation.goal_attention.reconcile warning must be a dict or None" + ) + return ( + cast(dict[str, object], reconciled_item), + cast(dict[str, object] | None, reconciled_warning), + ) def _active_state_goal_context( - goal: dict[str, Any], - current_run: dict[str, Any] | None, + goal: dict[str, object], + current_run: dict[str, object] | None, context: AttentionQueueContext, runtime_root: Path | None, -) -> tuple[dict[str, Any], dict[str, Any] | None]: +) -> tuple[dict[str, object], dict[str, object] | None]: fields = context.active_state_todo_fields(goal, runtime_root=runtime_root) # Goal content survives even when no work creates an attention item. goal["goal_objective"] = fields.get("goal_objective") @@ -159,14 +189,17 @@ def _active_state_goal_context( def _unavailable_todo_source_item( - goal: dict[str, Any], + goal: dict[str, object], error: RetiredTodoEventSourceError | LocalCoordinationAuthorityUnavailable, context: AttentionQueueContext, -) -> dict[str, Any]: +) -> dict[str, object]: item = context.attention_item( goal_id=str(goal.get("id") or ""), - status=(error.code if isinstance(error, LocalCoordinationAuthorityUnavailable) - else error.reason_code), + status=( + error.code + if isinstance(error, LocalCoordinationAuthorityUnavailable) + else error.reason_code + ), waiting_on="user_or_controller", severity="high", recommended_action=str(error), @@ -180,11 +213,247 @@ def _unavailable_todo_source_item( return item +def _select_goal_attention_item( + goal: dict[str, object], + current_status_run: dict[str, object] | None, + active_state_item: dict[str, object] | None, + context: AttentionQueueContext, +) -> dict[str, object] | None: + if ( + active_state_item + and active_state_item.get("waiting_on") in USER_OR_CONTROLLER_WAIT_STATES + ): + return active_state_item + item = context.goal_attention(goal) + if not item or ( + current_status_run is None + and item.get("status") == "unknown" + and active_state_item + ): + return active_state_item + return item + + +def _enrich_registry_member_item( + item: dict[str, object], + *, + goal: dict[str, object], + active_state_fields: dict[str, object] | None, + goal_latest_runs: list[dict[str, object]], + subagent_activity: dict[str, object] | None, + interface_budget_cadence: dict[str, object] | None, + context: AttentionQueueContext, + runtime_root: Path | None, + agent_lane_id: str | None, +) -> None: + if active_state_fields is None: + active_state_fields = context.active_state_todo_fields( + goal, runtime_root=runtime_root + ) + item.update( + { + key: value + for key, value in active_state_fields.items() + if key != "goal_objective" + } + ) + context.sync_connected_attention_action_from_todos(item) + external_progress_review = ( + context.external_progress_review_context(goal, runtime_root) + if context.external_progress_review_context is not None + else None + ) + context.attach_active_state_project_asset_fields( + item, + latest_runs=goal_latest_runs, + next_action_projection_warning=context.next_action_projection_warning, + autonomous_replan_obligation_from_runs=( + context.autonomous_replan_obligation_from_runs + ), + external_progress_review=external_progress_review, + effective_turn_cadence=effective_turn_cadence_context( + goal, + runtime_root, + registry_path=context.registry_path, + tolerate_malformed_history=context.tolerate_malformed_settlement_history, + ), + agent_lane_id=agent_lane_id, + ) + item["quota"] = context.quota_status( + goal, + waiting_on=str(item.get("waiting_on") or ""), + severity=str(item.get("severity") or ""), + lifecycle_phase=item.get("lifecycle_phase"), + lifecycle_flags=item.get("lifecycle_flags"), + status=item.get("status"), + ) + context.enrich_project_asset( + item, + user_todos=_optional_dict(item.get("user_todos")), + agent_todos=_optional_dict(item.get("agent_todos")), + quota=_optional_dict(item.get("quota")), + latest_runs=goal_latest_runs, + subagent_activity=subagent_activity, + interface_budget_cadence=interface_budget_cadence, + ) + guarded_quota = context.quota_with_handoff_outcome_floor( + _optional_dict(item.get("quota")) or {}, + waiting_on=str(item.get("waiting_on") or ""), + project_asset=_optional_dict(item.get("project_asset")), + handoff_readiness=_optional_dict(item.get("handoff_readiness")), + ) + if guarded_quota != item.get("quota"): + item["quota"] = guarded_quota + context.enrich_project_asset( + item, + user_todos=_optional_dict(item.get("user_todos")), + agent_todos=_optional_dict(item.get("agent_todos")), + quota=guarded_quota, + latest_runs=goal_latest_runs, + subagent_activity=subagent_activity, + interface_budget_cadence=interface_budget_cadence, + ) + context.sync_connected_attention_action_from_todos(item) + context.normalize_monitor_quiet_attention_display(item) + + +def _build_goal_attention_item( + goal: dict[str, object], + *, + context: AttentionQueueContext, + runtime_root: Path | None, + include_task_graph: bool, + goal_id_filter: str | None, + include_goal_channel_projection: bool, + agent_lane_id: str | None, +) -> dict[str, object] | None: + active_state_fields: dict[str, object] | None = None + active_state_item: dict[str, object] | None = None + current_status_run = context.latest_run(goal) + raw_latest_runs = goal.get("latest_runs") + goal_latest_runs: list[dict[str, object]] = ( + cast(list[dict[str, object]], raw_latest_runs) + if isinstance(raw_latest_runs, list) + else [] + ) + if goal.get("registry_member"): + try: + active_state_fields, active_state_item = _active_state_goal_context( + goal, current_status_run, context, runtime_root + ) + except (RetiredTodoEventSourceError, LocalCoordinationAuthorityUnavailable) as error: + if isinstance(error, LocalCoordinationAuthorityUnavailable) and goal_id_filter: + raise + # Refuse this source without hiding independent Goals or turning + # stale Todo/run projections into executable fallback work. + return _unavailable_todo_source_item(goal, error, context) + + selected = _select_goal_attention_item( + goal, current_status_run, active_state_item, context + ) + if not selected: + return None + item, projection_warning = _reconcile_active_state_item( + goal, current_status_run, selected, active_state_item, context + ) + item["activation_state"] = str(goal.get("activation_state") or "active") + agent_lane_recommendation = context.compact_agent_lane_recommendation( + context.latest_agent_lane_run(goal) + ) + active_state_next_action = ( + active_state_fields.get("active_state_next_action") + if isinstance(active_state_fields, dict) + else None + ) + latest_run_action, latest_run_action_source = ( + context.latest_run_recommended_action_for_projection( + current_status_run=current_status_run, + agent_lane_recommendation=agent_lane_recommendation, + active_state_next_action=active_state_next_action, + preferred_agent_id=None, + ) + ) + pre_enrich_asset = _optional_dict(item.get("project_asset")) + if latest_run_action: + item["latest_run_recommended_action"] = latest_run_action + if latest_run_action_source: + item["latest_run_recommended_action_source"] = latest_run_action_source + if pre_enrich_asset is not None: + pre_enrich_asset["latest_run_recommended_action"] = latest_run_action + if latest_run_action_source: + pre_enrich_asset[ + "latest_run_recommended_action_source" + ] = latest_run_action_source + replan_ack = context.compact_autonomous_replan_ack( + current_status_run + ) or context.latest_autonomous_replan_ack_for_projection(goal_latest_runs) + if replan_ack: + item["autonomous_replan_ack"] = replan_ack + if pre_enrich_asset is not None: + pre_enrich_asset["autonomous_replan_ack"] = replan_ack + control_plane = context.compact_control_plane_policy(goal.get("control_plane")) + if control_plane: + item["control_plane"] = control_plane + if agent_lane_recommendation: + item["agent_lane_recommendation"] = agent_lane_recommendation + subagent_activity = context.subagent_activity_for_goal(goal) + interface_budget_cadence = context.interface_budget_cadence_for_runs( + goal_latest_runs + ) + context.enrich_project_asset( + item, + latest_validation=context.project_asset_latest_validation(current_status_run), + latest_runs=goal_latest_runs, + execution_profile=_optional_dict(goal.get("execution_profile")), + orchestration=_optional_dict(goal.get("spawn_policy")), + subagent_activity=subagent_activity, + interface_budget_cadence=interface_budget_cadence, + ) + post_enrich_asset = _optional_dict(item.get("project_asset")) + if post_enrich_asset is not None: + if control_plane: + post_enrich_asset["control_plane"] = control_plane + if agent_lane_recommendation: + post_enrich_asset["agent_lane_recommendation"] = agent_lane_recommendation + if projection_warning: + item["stale_latest_run_warning"] = projection_warning + if post_enrich_asset is not None: + post_enrich_asset["stale_latest_run_warning"] = projection_warning + if goal.get("registry_member"): + _enrich_registry_member_item( + item, + goal=goal, + active_state_fields=active_state_fields, + goal_latest_runs=goal_latest_runs, + subagent_activity=subagent_activity, + interface_budget_cadence=interface_budget_cadence, + context=context, + runtime_root=runtime_root, + agent_lane_id=agent_lane_id, + ) + if include_task_graph: + task_graph_projection = context.build_task_graph_projection( + item, + goal=goal, + goal_latest_runs=goal_latest_runs, + ) + if task_graph_projection: + item["task_graph_projection"] = task_graph_projection + if include_goal_channel_projection: + context.attach_goal_channel_projection( + item, + goal=goal, + goal_latest_runs=goal_latest_runs, + runtime_root=runtime_root, + ) + return item + + def build_attention_queue( *, - contract: dict[str, Any], - history: dict[str, Any], - global_registry: dict[str, Any], + contract: dict[str, object], + history: dict[str, object], + global_registry: dict[str, object], context: AttentionQueueContext, runtime_root: Path | None = None, include_task_graph: bool = False, @@ -192,7 +461,7 @@ def build_attention_queue( include_stopped_goal_context: bool = False, include_goal_channel_projection: bool = True, agent_lane_id: str | None = None, -) -> dict[str, Any]: +) -> dict[str, object]: """Build the executable attention queue or a stopped-Goal archive view. Normal callers omit stopped Goals because they must never become runnable @@ -200,8 +469,8 @@ def build_attention_queue( Todo and run context so opening a stopped Goal remains informative; that opt-in does not change lifecycle authority or make the Goal executable. """ - health_items: list[dict[str, Any]] = [] - history_items: list[dict[str, Any]] = [] + health_items: list[dict[str, object]] = [] + history_items: list[dict[str, object]] = [] if contract.get("ok") is False: health_items.append( context.attention_item( @@ -214,7 +483,7 @@ def build_attention_queue( ) ) - for goal in history.get("goals") or []: + for goal in _sequence_or_empty(history.get("goals"), field_name="history.goals"): if not isinstance(goal, dict): continue if ( @@ -222,192 +491,25 @@ def build_attention_queue( and not include_stopped_goal_context ): continue - active_state_fields: dict[str, Any] | None = None - active_state_item: dict[str, Any] | None = None - current_status_run = context.latest_run(goal) - goal_latest_runs = goal.get("latest_runs") if isinstance(goal.get("latest_runs"), list) else [] - if goal.get("registry_member"): - try: - active_state_fields, active_state_item = _active_state_goal_context( - goal, current_status_run, context, runtime_root, - ) - except (RetiredTodoEventSourceError, LocalCoordinationAuthorityUnavailable) as error: - if isinstance(error, LocalCoordinationAuthorityUnavailable) and goal_id_filter: - raise - # Refuse this source without hiding independent Goals or turning - # stale Todo/run projections into executable fallback work. - history_items.append(_unavailable_todo_source_item(goal, error, context)) - continue - if active_state_item and active_state_item.get("waiting_on") in {"controller", "user_or_controller"}: - item = active_state_item - else: - item = context.goal_attention(goal) - if not item or ( - current_status_run is None - and item.get("status") == "unknown" - and active_state_item - ): - item = active_state_item - if item: - item, projection_warning = _reconcile_active_state_item( - goal, current_status_run, item, active_state_item, context, - ) - item["activation_state"] = str( - goal.get("activation_state") or "active" - ) - agent_lane_recommendation = context.compact_agent_lane_recommendation( - context.latest_agent_lane_run(goal) - ) - active_state_next_action = ( - active_state_fields.get("active_state_next_action") - if isinstance(active_state_fields, dict) - else None - ) - latest_run_action, latest_run_action_source = ( - context.latest_run_recommended_action_for_projection( - current_status_run=current_status_run, - agent_lane_recommendation=agent_lane_recommendation, - active_state_next_action=active_state_next_action, - preferred_agent_id=None, - ) - ) - if latest_run_action: - item["latest_run_recommended_action"] = latest_run_action - if latest_run_action_source: - item["latest_run_recommended_action_source"] = latest_run_action_source - if isinstance(item.get("project_asset"), dict): - item["project_asset"]["latest_run_recommended_action"] = latest_run_action - if latest_run_action_source: - item["project_asset"][ - "latest_run_recommended_action_source" - ] = latest_run_action_source - replan_ack = context.compact_autonomous_replan_ack( - current_status_run - ) or context.latest_autonomous_replan_ack_for_projection(goal_latest_runs) - if replan_ack: - item["autonomous_replan_ack"] = replan_ack - if isinstance(item.get("project_asset"), dict): - item["project_asset"]["autonomous_replan_ack"] = replan_ack - control_plane = context.compact_control_plane_policy(goal.get("control_plane")) - if control_plane: - item["control_plane"] = control_plane - if agent_lane_recommendation: - item["agent_lane_recommendation"] = agent_lane_recommendation - subagent_activity = context.subagent_activity_for_goal(goal) - interface_budget_cadence = context.interface_budget_cadence_for_runs(goal_latest_runs) - context.enrich_project_asset( - item, - latest_validation=context.project_asset_latest_validation(context.latest_run(goal)), - latest_runs=goal_latest_runs, - execution_profile=( - goal.get("execution_profile") - if isinstance(goal.get("execution_profile"), dict) - else None - ), - orchestration=( - goal.get("spawn_policy") - if isinstance(goal.get("spawn_policy"), dict) - else None - ), - subagent_activity=subagent_activity, - interface_budget_cadence=interface_budget_cadence, - ) - if control_plane and isinstance(item.get("project_asset"), dict): - item["project_asset"]["control_plane"] = control_plane - if agent_lane_recommendation and isinstance(item.get("project_asset"), dict): - item["project_asset"]["agent_lane_recommendation"] = agent_lane_recommendation - if projection_warning: - item["stale_latest_run_warning"] = projection_warning - if isinstance(item.get("project_asset"), dict): - item["project_asset"]["stale_latest_run_warning"] = projection_warning - if goal.get("registry_member"): - if active_state_fields is None: - active_state_fields = context.active_state_todo_fields(goal, runtime_root=runtime_root) - item.update({key: value for key, value in active_state_fields.items() - if key != "goal_objective"}) - context.sync_connected_attention_action_from_todos(item) - external_progress_review = ( - context.external_progress_review_context(goal, runtime_root) - if context.external_progress_review_context is not None - else None - ) - context.attach_active_state_project_asset_fields( - item, - latest_runs=goal_latest_runs, - next_action_projection_warning=context.next_action_projection_warning, - autonomous_replan_obligation_from_runs=context.autonomous_replan_obligation_from_runs, - external_progress_review=external_progress_review, - effective_turn_cadence=effective_turn_cadence_context( - goal, - runtime_root, - registry_path=context.registry_path, - tolerate_malformed_history=( - context.tolerate_malformed_settlement_history - ), - ), - agent_lane_id=agent_lane_id, - ) - item["quota"] = context.quota_status( - goal, - waiting_on=str(item.get("waiting_on") or ""), - severity=str(item.get("severity") or ""), - lifecycle_phase=item.get("lifecycle_phase"), - lifecycle_flags=item.get("lifecycle_flags"), - status=item.get("status"), - ) - context.enrich_project_asset( - item, - user_todos=item.get("user_todos") if isinstance(item.get("user_todos"), dict) else None, - agent_todos=item.get("agent_todos") if isinstance(item.get("agent_todos"), dict) else None, - quota=item.get("quota") if isinstance(item.get("quota"), dict) else None, - latest_runs=goal_latest_runs, - subagent_activity=subagent_activity, - interface_budget_cadence=interface_budget_cadence, - ) - guarded_quota = context.quota_with_handoff_outcome_floor( - item.get("quota") if isinstance(item.get("quota"), dict) else {}, - waiting_on=str(item.get("waiting_on") or ""), - project_asset=item.get("project_asset") - if isinstance(item.get("project_asset"), dict) - else None, - handoff_readiness=item.get("handoff_readiness") - if isinstance(item.get("handoff_readiness"), dict) - else None, - ) - if guarded_quota != item.get("quota"): - item["quota"] = guarded_quota - context.enrich_project_asset( - item, - user_todos=item.get("user_todos") if isinstance(item.get("user_todos"), dict) else None, - agent_todos=item.get("agent_todos") if isinstance(item.get("agent_todos"), dict) else None, - quota=guarded_quota, - latest_runs=goal_latest_runs, - subagent_activity=subagent_activity, - interface_budget_cadence=interface_budget_cadence, - ) - context.sync_connected_attention_action_from_todos(item) - context.normalize_monitor_quiet_attention_display(item) - if include_task_graph: - task_graph_projection = context.build_task_graph_projection( - item, - goal=goal, - goal_latest_runs=goal_latest_runs, - ) - if task_graph_projection: - item["task_graph_projection"] = task_graph_projection - if include_goal_channel_projection: - context.attach_goal_channel_projection( - item, - goal=goal, - goal_latest_runs=goal_latest_runs, - runtime_root=runtime_root, - ) - history_items.append(item) + typed_goal = cast(dict[str, object], goal) + built_item = _build_goal_attention_item( + typed_goal, + context=context, + runtime_root=runtime_root, + include_task_graph=include_task_graph, + goal_id_filter=goal_id_filter, + include_goal_channel_projection=include_goal_channel_projection, + agent_lane_id=agent_lane_id, + ) + if built_item is not None: + history_items.append(built_item) merge_global_registry_findings( health_items=health_items, history_items=history_items, - findings=global_registry.get("findings") or [], + findings=_sequence_or_empty( + global_registry.get("findings"), field_name="global_registry.findings" + ), goal_id_filter=goal_id_filter, source_registry_shadow_findings=context.source_registry_shadow_findings, attention_item=context.attention_item, diff --git a/loopx/control_plane/work_items/attention_queue_types.py b/loopx/control_plane/work_items/attention_queue_types.py new file mode 100644 index 0000000000..4a1e36100c --- /dev/null +++ b/loopx/control_plane/work_items/attention_queue_types.py @@ -0,0 +1,242 @@ +"""Typed contracts and dependency context for the Work Items attention queue.""" +from __future__ import annotations + +from collections.abc import Callable, Set as AbstractSet +from dataclasses import dataclass +from pathlib import Path +from typing import Literal, Protocol, TypedDict + +AttentionWaitingOn = Literal[ + "user_or_controller", + "controller", + "codex", + "external_evidence", +] +GlobalRegistryFindingSeverity = Literal["high", "action"] + +USER_OR_CONTROLLER_WAIT_STATES: frozenset[str] = frozenset( + {"user_or_controller", "controller"} +) +ACTIONABLE_REGISTRY_SEVERITIES: frozenset[str] = frozenset({"high", "action"}) + + +class AttentionQueueCounts(TypedDict): + """Bucket counts emitted alongside attention queue items.""" + + item_count: int + needs_user_or_controller: int + needs_controller: int + needs_codex: int + watching_external_evidence: int + watching_monitor: int + + +class AttentionQueueProjection(AttentionQueueCounts, total=False): + """Structured shape of the serialized ``attention_queue`` projection.""" + + available: bool + items: list[dict[str, object]] + goal_filter: str + goal_filter_applied: bool + autonomous_backlog_candidates: dict[str, object] + autonomous_monitor_candidates: dict[str, object] + + +class AttentionItemBuilder(Protocol): + def __call__( + self, + *, + goal_id: str, + status: str, + waiting_on: str, + severity: str, + recommended_action: str, + source: str, + ) -> dict[str, object]: ... + + +class GlobalRegistryShadowAttacher(Protocol): + def __call__( + self, + item: dict[str, object], + finding: dict[str, object], + /, + ) -> None: ... + + +class ActiveStateTodoFieldsBuilder(Protocol): + def __call__( + self, + goal: dict[str, object], + /, + *, + runtime_root: Path | None = None, + ) -> dict[str, object]: ... + + +class ActiveStateTodoAttentionBuilder(Protocol): + def __call__( + self, + goal: dict[str, object], + fields: dict[str, object], + current_run: dict[str, object] | None, + /, + ) -> dict[str, object] | None: ... + + +class LatestRunRecommendedActionBuilder(Protocol): + def __call__( + self, + *, + current_status_run: dict[str, object] | None, + agent_lane_recommendation: dict[str, object] | None, + active_state_next_action: object = None, + preferred_agent_id: str | None = None, + ) -> tuple[str | None, str | None]: ... + + +class EnrichProjectAssetFn(Protocol): + def __call__( + self, + item: dict[str, object], + /, + *, + user_todos: dict[str, object] | None = None, + agent_todos: dict[str, object] | None = None, + quota: dict[str, object] | None = None, + latest_validation: dict[str, object] | None = None, + latest_runs: list[dict[str, object]] | None = None, + execution_profile: dict[str, object] | None = None, + orchestration: dict[str, object] | None = None, + subagent_activity: dict[str, object] | None = None, + interface_budget_cadence: dict[str, object] | None = None, + ) -> None: ... + + +class ActiveStateProjectAssetAttacher(Protocol): + def __call__( + self, + item: dict[str, object], + /, + *, + latest_runs: list[dict[str, object]] | None = None, + next_action_projection_warning: Callable[..., dict[str, object] | None], + autonomous_replan_obligation_from_runs: Callable[ + ..., dict[str, object] | None + ], + external_progress_review: dict[str, object] | None = None, + effective_turn_cadence: dict[str, object] | None = None, + agent_lane_id: str | None = None, + ) -> object: ... + + +class QuotaStatusBuilder(Protocol): + def __call__( + self, + goal: dict[str, object], + /, + *, + waiting_on: str, + severity: str, + lifecycle_phase: object = None, + lifecycle_flags: object = None, + status: object = None, + ) -> dict[str, object]: ... + + +class QuotaHandoffFloorBuilder(Protocol): + def __call__( + self, + quota: dict[str, object], + /, + *, + waiting_on: str, + project_asset: dict[str, object] | None = None, + handoff_readiness: dict[str, object] | None = None, + ) -> dict[str, object]: ... + + +class TaskGraphProjectionBuilder(Protocol): + def __call__( + self, + item: dict[str, object], + /, + *, + goal: dict[str, object], + goal_latest_runs: list[dict[str, object]] | None = None, + ) -> dict[str, object] | None: ... + + +class GoalChannelProjectionAttacher(Protocol): + def __call__( + self, + item: dict[str, object], + /, + *, + goal: dict[str, object], + goal_latest_runs: list[dict[str, object]], + runtime_root: Path | None = None, + ) -> None: ... + + +class ExternalProgressReviewLoader(Protocol): + def __call__( + self, + goal: dict[str, object], + runtime_root: Path | None, + /, + ) -> dict[str, object] | None: ... + + +@dataclass(frozen=True) +class AttentionQueueContext: + active_state_todo_fields: ActiveStateTodoFieldsBuilder + active_state_todo_attention_item: ActiveStateTodoAttentionBuilder + latest_run: Callable[[dict[str, object]], dict[str, object] | None] + goal_attention: Callable[[dict[str, object]], dict[str, object] | None] + compact_agent_lane_recommendation: Callable[ + [dict[str, object] | None], dict[str, object] | None + ] + latest_agent_lane_run: Callable[[dict[str, object]], dict[str, object] | None] + latest_run_recommended_action_for_projection: LatestRunRecommendedActionBuilder + compact_autonomous_replan_ack: Callable[ + [dict[str, object] | None], dict[str, object] | None + ] + latest_autonomous_replan_ack_for_projection: Callable[ + [list[dict[str, object]] | None], dict[str, object] | None + ] + compact_control_plane_policy: Callable[[object], dict[str, object]] + subagent_activity_for_goal: Callable[[dict[str, object]], dict[str, object] | None] + interface_budget_cadence_for_runs: Callable[ + [list[dict[str, object]]], dict[str, object] | None + ] + active_state_projection_warning: Callable[ + [dict[str, object], dict[str, object] | None], dict[str, object] | None + ] + enrich_project_asset: EnrichProjectAssetFn + project_asset_latest_validation: Callable[ + [dict[str, object] | None], dict[str, object] | None + ] + attach_active_state_project_asset_fields: ActiveStateProjectAssetAttacher + sync_connected_attention_action_from_todos: Callable[[dict[str, object]], None] + quota_status: QuotaStatusBuilder + quota_with_handoff_outcome_floor: QuotaHandoffFloorBuilder + normalize_monitor_quiet_attention_display: Callable[[dict[str, object]], None] + build_task_graph_projection: TaskGraphProjectionBuilder + attach_goal_channel_projection: GoalChannelProjectionAttacher + attach_dependency_blockers: Callable[[list[dict[str, object]]], None] + autonomous_backlog_candidates: Callable[ + [list[dict[str, object]]], dict[str, object] | None + ] + autonomous_monitor_candidates: Callable[ + [list[dict[str, object]]], dict[str, object] | None + ] + attention_item: AttentionItemBuilder + attach_global_registry_shadow_finding: GlobalRegistryShadowAttacher + next_action_projection_warning: Callable[..., dict[str, object] | None] + autonomous_replan_obligation_from_runs: Callable[..., dict[str, object] | None] + source_registry_shadow_findings: AbstractSet[str] + monitor_signal_waiting_on: str + registry_path: Path | None = None + external_progress_review_context: ExternalProgressReviewLoader | None = None + tolerate_malformed_settlement_history: bool = False diff --git a/loopx/status.py b/loopx/status.py index 2bf348200d..3e47daa17b 100644 --- a/loopx/status.py +++ b/loopx/status.py @@ -1109,7 +1109,7 @@ def request_active_state_todo_fields( agent_lane_id=agent_lane_id, ) if runtime_root is not None: - for item in queue.get("items") or []: + for item in (raw_items if isinstance((raw_items := queue.get("items")), list) else ()): if not isinstance(item, dict): continue goal_id = str(item.get("goal_id") or "").strip() diff --git a/tests/control_plane/test_attention_queue_contract.py b/tests/control_plane/test_attention_queue_contract.py new file mode 100644 index 0000000000..11a6bdbc23 --- /dev/null +++ b/tests/control_plane/test_attention_queue_contract.py @@ -0,0 +1,596 @@ +"""Contract and edge-case tests for the Work Items attention queue.""" + +from __future__ import annotations + +import ast +from collections.abc import Callable +from dataclasses import dataclass, field, replace +import io +from pathlib import Path +import tokenize + +import pytest + +from loopx.control_plane.coordination.local_authority import ( + LocalCoordinationAuthorityUnavailable, +) +from loopx.control_plane.goals.legacy_event_source import RetiredTodoEventSourceError +from loopx.control_plane.work_items import attention_queue as aq +from loopx.control_plane.work_items import attention_queue_types as aqt + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _comment_type_ignore_count(source: str) -> int: + tokens = tokenize.generate_tokens(io.StringIO(source).readline) + return sum( + 1 + for tok in tokens + if tok.type == tokenize.COMMENT and "type: ignore" in tok.string + ) + + +def _any_count(source: str) -> int: + tree = ast.parse(source) + return sum( + 1 + for node in ast.walk(tree) + if (isinstance(node, ast.Name) and node.id == "Any") + or (isinstance(node, ast.Attribute) and node.attr == "Any") + or ( + isinstance(node, ast.ImportFrom) + and any(alias.name == "Any" for alias in node.names) + ) + ) + + +def _attention_item( + *, + goal_id: str, + status: str, + waiting_on: str, + severity: str, + recommended_action: str, + source: str, +) -> dict[str, object]: + return { + "goal_id": goal_id, + "status": status, + "waiting_on": waiting_on, + "severity": severity, + "recommended_action": recommended_action, + "source": source, + } + + +@dataclass +class _FakeRecorder: + latest_run_calls: list[str] = field(default_factory=list) + validation_inputs: list[dict[str, object] | None] = field(default_factory=list) + replan_ack_inputs: list[dict[str, object] | None] = field(default_factory=list) + enrich_quotas: list[dict[str, object] | None] = field(default_factory=list) + external_review_calls: list[tuple[str, Path | None]] = field(default_factory=list) + goal_channel_calls: list[str] = field(default_factory=list) + shadow_attachments: list[tuple[str, str]] = field(default_factory=list) + raise_active_state: Exception | None = None + guarded_quota_floor: dict[str, object] | None = None + + +def _build_context( + recorder: _FakeRecorder, + *, + goal_items: dict[str, dict[str, object]] | None = None, + active_items: dict[str, dict[str, object]] | None = None, + active_fields: dict[str, dict[str, object]] | None = None, + latest_runs_map: dict[str, dict[str, object]] | None = None, + monitor_signal_waiting_on: str = "external_evidence", + external_review: dict[str, object] | None = None, +) -> aq.AttentionQueueContext: + def _todo_fields( + goal: dict[str, object], *, runtime_root: Path | None = None + ) -> dict[str, object]: + del runtime_root + if recorder.raise_active_state is not None: + raise recorder.raise_active_state + gid = str(goal.get("id") or "") + return dict( + (active_fields or {}).get( + gid, + { + "goal_objective": f"objective:{gid}", + "user_todos": {"open_count": 0}, + "agent_todos": {"open_count": 1}, + }, + ) + ) + + def _todo_attention( + goal: dict[str, object], + fields: dict[str, object], + current_run: dict[str, object] | None, + /, + ) -> dict[str, object] | None: + del fields, current_run + gid = str(goal.get("id") or "") + item = (active_items or {}).get(gid) + return dict(item) if item is not None else None + + def _latest_run(goal: dict[str, object]) -> dict[str, object] | None: + gid = str(goal.get("id") or "") + recorder.latest_run_calls.append(gid) + run = (latest_runs_map or {}).get(gid) + return dict(run) if run is not None else None + + def _goal_attention(goal: dict[str, object]) -> dict[str, object] | None: + gid = str(goal.get("id") or "") + item = (goal_items or {}).get(gid) + return dict(item) if item is not None else None + + def _enrich_asset( + item: dict[str, object], + /, + *, + quota: dict[str, object] | None = None, + user_todos: dict[str, object] | None = None, + agent_todos: dict[str, object] | None = None, + latest_validation: dict[str, object] | None = None, + latest_runs: list[dict[str, object]] | None = None, + execution_profile: dict[str, object] | None = None, + orchestration: dict[str, object] | None = None, + subagent_activity: dict[str, object] | None = None, + interface_budget_cadence: dict[str, object] | None = None, + ) -> None: + del user_todos, agent_todos, latest_validation, latest_runs + del execution_profile, orchestration, subagent_activity, interface_budget_cadence + recorder.enrich_quotas.append(dict(quota) if quota is not None else None) + asset = item.get("project_asset") + if not isinstance(asset, dict): + asset = {} + item["project_asset"] = asset + if quota is not None: + asset["quota_state"] = quota.get("state") + + def _attach_project_asset( + item: dict[str, object], + /, + *, + latest_runs: list[dict[str, object]] | None = None, + next_action_projection_warning: Callable[..., dict[str, object] | None], + autonomous_replan_obligation_from_runs: Callable[ + ..., dict[str, object] | None + ], + external_progress_review: dict[str, object] | None = None, + effective_turn_cadence: dict[str, object] | None = None, + agent_lane_id: str | None = None, + ) -> object: + del latest_runs, next_action_projection_warning + del autonomous_replan_obligation_from_runs, effective_turn_cadence + if external_progress_review is not None: + item["external_progress_review"] = external_progress_review + if agent_lane_id is not None: + item["agent_lane_id"] = agent_lane_id + return None + + def _quota_status( + goal: dict[str, object], + /, + *, + waiting_on: str, + severity: str, + lifecycle_phase: object = None, + lifecycle_flags: object = None, + status: object = None, + ) -> dict[str, object]: + del lifecycle_phase, lifecycle_flags, status + return { + "goal_id": goal.get("id"), + "waiting_on": waiting_on, + "severity": severity, + "state": "base", + } + + def _quota_floor( + quota: dict[str, object], + /, + *, + waiting_on: str, + project_asset: dict[str, object] | None = None, + handoff_readiness: dict[str, object] | None = None, + ) -> dict[str, object]: + del waiting_on, project_asset, handoff_readiness + if recorder.guarded_quota_floor is not None: + return dict(recorder.guarded_quota_floor) + return dict(quota) + + def _latest_validation( + run: dict[str, object] | None, + ) -> dict[str, object] | None: + recorder.validation_inputs.append(run) + return {"run_id": run.get("id")} if run is not None else None + + def _compact_replan(run: dict[str, object] | None) -> dict[str, object] | None: + recorder.replan_ack_inputs.append(run) + if run and run.get("replan_ack"): + return {"ack": run["replan_ack"]} + return None + + def _ext_review( + goal: dict[str, object], runtime_root: Path | None, / + ) -> dict[str, object] | None: + recorder.external_review_calls.append((str(goal.get("id") or ""), runtime_root)) + return dict(external_review) if external_review is not None else None + + def _attach_channel( + item: dict[str, object], + /, + *, + goal: dict[str, object], + goal_latest_runs: list[dict[str, object]], + runtime_root: Path | None = None, + ) -> None: + del item, goal_latest_runs, runtime_root + recorder.goal_channel_calls.append(str(goal.get("id") or "")) + + def _attach_shadow(item: dict[str, object], finding: dict[str, object], /) -> None: + recorder.shadow_attachments.append( + (str(item.get("goal_id") or ""), str(finding.get("kind") or "")) + ) + item["shadow_finding"] = finding.get("kind") + + return aq.AttentionQueueContext( + active_state_todo_fields=_todo_fields, + active_state_todo_attention_item=_todo_attention, + latest_run=_latest_run, + goal_attention=_goal_attention, + compact_agent_lane_recommendation=lambda run: ( + dict(run) if run is not None else None + ), + latest_agent_lane_run=lambda goal: None, + latest_run_recommended_action_for_projection=lambda **kwargs: ( + "continue-work", + "latest_run", + ), + compact_autonomous_replan_ack=_compact_replan, + latest_autonomous_replan_ack_for_projection=lambda runs: None, + compact_control_plane_policy=lambda policy: ( + dict(policy) if isinstance(policy, dict) else {} + ), + subagent_activity_for_goal=lambda goal: None, + interface_budget_cadence_for_runs=lambda runs: None, + active_state_projection_warning=lambda goal, run: None, + enrich_project_asset=_enrich_asset, + project_asset_latest_validation=_latest_validation, + attach_active_state_project_asset_fields=_attach_project_asset, + sync_connected_attention_action_from_todos=lambda item: None, + quota_status=_quota_status, + quota_with_handoff_outcome_floor=_quota_floor, + normalize_monitor_quiet_attention_display=lambda item: None, + build_task_graph_projection=lambda item, **kwargs: None, + attach_goal_channel_projection=_attach_channel, + attach_dependency_blockers=lambda items: None, + autonomous_backlog_candidates=lambda items: None, + autonomous_monitor_candidates=lambda items: None, + attention_item=_attention_item, + attach_global_registry_shadow_finding=_attach_shadow, + next_action_projection_warning=lambda *args, **kwargs: None, + autonomous_replan_obligation_from_runs=lambda *args, **kwargs: None, + source_registry_shadow_findings=frozenset({"source_registry_shadow"}), + monitor_signal_waiting_on=monitor_signal_waiting_on, + external_progress_review_context=_ext_review, + ) + + +def test_attention_queue_static_hygiene_and_exports() -> None: + aq_path = REPO_ROOT / "loopx/control_plane/work_items/attention_queue.py" + types_path = REPO_ROOT / "loopx/control_plane/work_items/attention_queue_types.py" + test_path = Path(__file__).resolve() + + aq_src = aq_path.read_text(encoding="utf-8") + types_src = types_path.read_text(encoding="utf-8") + test_src = test_path.read_text(encoding="utf-8") + + assert len(aq_src.splitlines()) <= 550 + assert len(types_src.splitlines()) < 750 + assert len(test_src.splitlines()) < 600 + for src in (aq_src, types_src, test_src): + assert _any_count(src) == 0 + assert _comment_type_ignore_count(src) == 0 + + assert aq.AttentionQueueContext is aqt.AttentionQueueContext + assert aq.AttentionQueueProjection is aqt.AttentionQueueProjection + assert aq.USER_OR_CONTROLLER_WAIT_STATES is aqt.USER_OR_CONTROLLER_WAIT_STATES + assert aq.ACTIONABLE_REGISTRY_SEVERITIES is aqt.ACTIONABLE_REGISTRY_SEVERITIES + + +def test_build_attention_queue_projection_counts_and_optional_keys() -> None: + items: list[dict[str, object]] = [ + {"goal_id": "g1", "waiting_on": "user_or_controller"}, + {"goal_id": "g2", "waiting_on": "controller"}, + {"goal_id": "g3", "waiting_on": "codex"}, + {"goal_id": "g4", "waiting_on": "external_evidence"}, + {"goal_id": "g5", "waiting_on": "other"}, + ] + projection = aq.build_attention_queue_projection( + items=items, + goal_id_filter=None, + autonomous_backlog_candidates={}, + autonomous_monitor_candidates=None, + monitor_signal_waiting_on="codex", + ) + assert projection == { + "available": True, + "item_count": 5, + "needs_user_or_controller": 2, + "needs_controller": 1, + "needs_codex": 1, + "watching_external_evidence": 1, + "watching_monitor": 1, + "items": items, + } + assert "goal_filter" not in projection + assert "autonomous_backlog_candidates" not in projection + + with pytest.raises(KeyError): + aq.build_attention_queue_projection( + items=[{"goal_id": "missing"}], + goal_id_filter=None, + autonomous_backlog_candidates=None, + autonomous_monitor_candidates=None, + monitor_signal_waiting_on="external_evidence", + ) + + +def test_merge_global_registry_findings_shadow_filter_and_validation() -> None: + health_items: list[dict[str, object]] = [] + history_items: list[dict[str, object]] = [ + {"goal_id": "g1", "quota": {"state": "ok"}}, + {"goal_id": "g2"}, + ] + attached: list[tuple[str, str]] = [] + aq.merge_global_registry_findings( + health_items=health_items, + history_items=history_items, + findings=[ + "ignored-non-dict", + {"kind": "minor", "severity": "info", "goal_id": "g1"}, + {"kind": "source_registry_shadow", "severity": "high", "goal_id": "g1"}, + { + "kind": "registry_conflict", + "severity": "action", + "goal_id": "global", + "goal_ids": {}, + }, + { + "kind": "linked_blocker", + "severity": "high", + "goal_id": "other", + "goal_ids": ["g1"], + }, + ], + goal_id_filter="g1", + source_registry_shadow_findings=frozenset({"source_registry_shadow"}), + attention_item=_attention_item, + attach_global_registry_shadow_finding=lambda item, finding: attached.append( + (str(item["goal_id"]), str(finding["kind"])) + ), + ) + assert attached == [("g1", "source_registry_shadow")] + assert [item["status"] for item in health_items] == ["linked_blocker"] + + with pytest.raises(TypeError, match="finding.goal_ids must be a sequence"): + aq.merge_global_registry_findings( + health_items=[], + history_items=[], + findings=[{"kind": "bad", "severity": "high", "goal_ids": "g1"}], + goal_id_filter="g1", + source_registry_shadow_findings=frozenset(), + attention_item=_attention_item, + attach_global_registry_shadow_finding=lambda item, finding: None, + ) + + +def test_build_attention_queue_single_latest_run_and_stopped_goal_opt_in() -> None: + recorder = _FakeRecorder( + guarded_quota_floor={"goal_id": "g-reg", "state": "guarded"}, + ) + ctx = _build_context( + recorder, + goal_items={ + "g-reg": _attention_item( + goal_id="g-reg", + status="ready", + waiting_on="codex", + severity="medium", + recommended_action="run", + source="goal", + ), + "g-stopped": _attention_item( + goal_id="g-stopped", + status="stopped", + waiting_on="codex", + severity="low", + recommended_action="archive", + source="goal", + ), + }, + latest_runs_map={"g-reg": {"id": "run-1", "replan_ack": "acked"}}, + external_review={"reviewed": True}, + ) + history: dict[str, object] = { + "goals": [ + {"id": "g-reg", "registry_member": True, "activation_state": "active"}, + {"id": "g-stopped", "registry_member": False, "activation_state": "stopped"}, + ] + } + default_queue = aq.build_attention_queue( + contract={"ok": True}, + history=history, + global_registry={"findings": {}}, + context=ctx, + ) + assert recorder.latest_run_calls == ["g-reg"] + assert recorder.validation_inputs == [{"id": "run-1", "replan_ack": "acked"}] + assert recorder.replan_ack_inputs == [{"id": "run-1", "replan_ack": "acked"}] + assert [state["state"] if state else None for state in recorder.enrich_quotas] == [ + None, + "base", + "guarded", + ] + assert default_queue["item_count"] == 1 + items = default_queue["items"] + assert isinstance(items, list) + assert items[0]["external_progress_review"] == {"reviewed": True} + assert items[0]["quota"] == {"goal_id": "g-reg", "state": "guarded"} + assert recorder.goal_channel_calls == ["g-reg"] + + recorder.latest_run_calls.clear() + archive_queue = aq.build_attention_queue( + contract={"ok": True}, + history=history, + global_registry={"findings": []}, + context=ctx, + include_stopped_goal_context=True, + include_goal_channel_projection=False, + ) + assert archive_queue["item_count"] == 2 + assert recorder.latest_run_calls == ["g-reg", "g-stopped"] + + # When current_status_run is None and goal_attention yields status="unknown", + # selection falls back to active_state_item; user/controller wait overrides. + fallback_ctx = _build_context( + _FakeRecorder(), + goal_items={ + "g-unk": _attention_item( + goal_id="g-unk", status="unknown", waiting_on="codex", + severity="low", recommended_action="fallback", source="goal", + ), + "g-gate": _attention_item( + goal_id="g-gate", status="ready", waiting_on="codex", + severity="low", recommended_action="run", source="goal", + ), + }, + active_items={ + "g-unk": _attention_item( + goal_id="g-unk", status="todo_waiting", waiting_on="codex", + severity="medium", recommended_action="use-active", source="active_state", + ), + "g-gate": _attention_item( + goal_id="g-gate", status="gate_open", waiting_on="controller", + severity="high", recommended_action="approve", source="active_state", + ), + }, + latest_runs_map={"g-gate": {"id": "run-gate"}}, + ) + fallback_queue = aq.build_attention_queue( + contract={"ok": True}, + history={"goals": [ + {"id": "g-unk", "registry_member": True}, + {"id": "g-gate", "registry_member": True}, + ]}, + global_registry={"findings": []}, + context=fallback_ctx, + ) + fallback_items = fallback_queue["items"] + assert isinstance(fallback_items, list) + assert [(row["source"], row["status"]) for row in fallback_items] == [ + ("active_state", "todo_waiting"), + ("active_state", "gate_open"), + ] + + +def test_build_attention_queue_unavailable_sources_and_malformed_inputs( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorder = _FakeRecorder(raise_active_state=RetiredTodoEventSourceError("retired")) + ctx = _build_context(recorder) + retired_queue = aq.build_attention_queue( + contract={"ok": False}, + history={"goals": [{"id": "g1", "registry_member": True}]}, + global_registry={"findings": []}, + context=ctx, + goal_id_filter="g1", + ) + assert retired_queue["goal_filter"] == "g1" + retired_items = retired_queue["items"] + assert isinstance(retired_items, list) + assert [item["status"] for item in retired_items] == [ + "contract_check_failed", + "legacy_todo_event_source_retired", + ] + assert retired_items[1]["todo_source"] == "unavailable" + + recorder.raise_active_state = LocalCoordinationAuthorityUnavailable( + "pg unreachable", + code="coordination_unavailable", + payload={"ok": False}, + ) + unfiltered = aq.build_attention_queue( + contract={"ok": True}, + history={"goals": [{"id": "g1", "registry_member": True}]}, + global_registry={"findings": {}}, + context=ctx, + ) + unfiltered_items = unfiltered["items"] + assert isinstance(unfiltered_items, list) + assert unfiltered_items[0]["error_code"] == "coordination_unavailable" + assert unfiltered_items[0]["authority_read"] == {"ok": False} + + with pytest.raises(LocalCoordinationAuthorityUnavailable): + aq.build_attention_queue( + contract={"ok": True}, + history={"goals": [{"id": "g1", "registry_member": True}]}, + global_registry={"findings": []}, + context=ctx, + goal_id_filter="g1", + ) + + with pytest.raises(TypeError, match="history.goals must be a sequence"): + aq.build_attention_queue( + contract={"ok": True}, + history={"goals": "bad-scalar"}, + global_registry={"findings": []}, + context=ctx, + ) + + monkeypatch.setattr( + aq, + "effect_runtime_result", + lambda op, payload: {"item": "not-a-dict", "warning": None}, + ) + bad_warning_ctx = _build_context( + _FakeRecorder(), + goal_items={ + "g1": _attention_item( + goal_id="g1", + status="ready", + waiting_on="codex", + severity="low", + recommended_action="go", + source="goal", + ) + }, + ) + bad_warning_ctx = replace( + bad_warning_ctx, + active_state_projection_warning=lambda goal, run: {"code": "stale"}, + ) + with pytest.raises(TypeError, match="item must be a dict"): + aq.build_attention_queue( + contract={"ok": True}, + history={"goals": [{"id": "g1", "registry_member": False}]}, + global_registry={"findings": []}, + context=bad_warning_ctx, + ) + + monkeypatch.setattr( + aq, + "effect_runtime_result", + lambda op, payload: {"item": dict(payload["item"]), "warning": "bad-warning"}, + ) + with pytest.raises(TypeError, match="warning must be a dict or None"): + aq.build_attention_queue( + contract={"ok": True}, + history={"goals": [{"id": "g1", "registry_member": False}]}, + global_registry={"findings": []}, + context=bad_warning_ctx, + )