From b5a9e9b6382db145d9c6cbbd56e884dcd9094510 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:57:04 +0800 Subject: [PATCH] refactor(control-plane): slim quota_summary and todo_summary and eliminate all 167 Any Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/canary/module_metric_baseline.json | 10 + loopx/control_plane/todos/quota_summary.py | 645 +++++++-------- loopx/control_plane/todos/todo_summary.py | 780 +++++++----------- .../work_items/semantic_replan_writeback.py | 4 +- 4 files changed, 631 insertions(+), 808 deletions(-) diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json index 0db426467f..ab4460c7b6 100644 --- a/loopx/canary/module_metric_baseline.json +++ b/loopx/canary/module_metric_baseline.json @@ -86,6 +86,16 @@ "dict_any_count": 0, "lines": 1109 }, + "loopx/control_plane/todos/quota_summary.py": { + "any_count": 0, + "dict_any_count": 0, + "lines": 686 + }, + "loopx/control_plane/todos/todo_summary.py": { + "any_count": 0, + "dict_any_count": 0, + "lines": 691 + }, "loopx/control_plane/work_items/interaction_contract.py": { "any_count": 85, "dict_any_count": 0 diff --git a/loopx/control_plane/todos/quota_summary.py b/loopx/control_plane/todos/quota_summary.py index ea00d6ecbb..f71bf0a812 100644 --- a/loopx/control_plane/todos/quota_summary.py +++ b/loopx/control_plane/todos/quota_summary.py @@ -1,17 +1,17 @@ from __future__ import annotations -from typing import Any, Callable +from collections.abc import Callable, Mapping, Sequence from copy import deepcopy - +from typing import cast from ..goals.goal_vision_policy import COMPLETED_TODO_CHAIN_REPLAN_THRESHOLD from ..runtime.time import now_utc -from .quota_selection import project_quota_planning from .frontier_deadline import todo_summary_frontier_deadline -from .summary_item import ( - todo_planning_source_items, - todo_summary_source_items, -) +from .quota_selection import project_quota_planning +from .summary_item import todo_planning_source_items, todo_summary_source_items + +Payload = dict[str, object] +PayloadView = Mapping[str, object] MONITOR_DUE_ITEM_LIMIT = 1 QUOTA_PAYLOAD_ITEM_TEXT_LIMIT = 180 @@ -138,39 +138,65 @@ "next_due_at", ) AGENT_LANE_STATUS_TODO_LANES = { - "agent": ( - "items", - "current_agent_blocker_items", - ), - "user": ( - "items", - "gate_open_items", - "user_action_items", - "current_agent_blocker_items", - ), -} -AGENT_LANE_STATUS_TODO_LANE_LIMITS = { - "gate_open_items": 3, - "user_action_items": 3, + "agent": ("items", "current_agent_blocker_items"), + "user": ("items", "gate_open_items", "user_action_items", "current_agent_blocker_items"), } +AGENT_LANE_STATUS_TODO_LANE_LIMITS = {"gate_open_items": 3, "user_action_items": 3} +_AGENT_LANE_STATUS_DICT_FIELDS = frozenset( + {"monitor_writeback", "work_counts", "deferred_work_counts"} +) +_AGENT_LANE_STATUS_REF_FIELDS = ( + "schema_version", "source_section", "open", "done", "total", "deferred_count", + "claimed_open_count", "unclaimed_open_count", "projection_view", "detail_pointer", +) -def summarize_user_todos_for_quota( - value: Any, *, agent_identity: dict[str, Any] | None = None, - filter_user_gate_blocks_agent: bool = False, available_capabilities: Any = None, +def _as_dict(value: object) -> Payload | None: + return cast(Payload, value) if isinstance(value, dict) else None + + +def _to_dict_or_none(value: PayloadView | None) -> Payload | None: + if value is None: + return None + return cast(Payload, value) if isinstance(value, dict) else dict(value) + + +def _require_dict_list(value: object, *, error: str) -> list[Payload]: + if not isinstance(value, list) or any(not isinstance(row, dict) for row in value): + raise RuntimeError(error) + return cast(list[Payload], value) + + +def _summarize_todos_for_quota( + value: object, *, summary_kind: str, agent_identity: PayloadView | None = None, + filter_user_gate_blocks_agent: bool = False, available_capabilities: object = None, resolve_capacity: bool = False, -) -> dict[str, Any] | None: - if not isinstance(value, dict): +) -> Payload | None: + source = _as_dict(value) + if source is None: return None - return project_quota_planning( - value, all_open_items=[], source_open_count=value.get("open_count"), - agent_identity=agent_identity, filter_user_gate_blocks_agent=filter_user_gate_blocks_agent, + return cast(Payload, project_quota_planning( + source, all_open_items=[], source_open_count=source.get("open_count"), + agent_identity=_to_dict_or_none(agent_identity), + filter_user_gate_blocks_agent=filter_user_gate_blocks_agent, + available_capabilities=available_capabilities, resolve_capacity=resolve_capacity, + summary_kind=summary_kind, + )) + + +def summarize_user_todos_for_quota( + value: object, *, agent_identity: PayloadView | None = None, + filter_user_gate_blocks_agent: bool = False, available_capabilities: object = None, + resolve_capacity: bool = False, +) -> Payload | None: + return _summarize_todos_for_quota( + value, summary_kind="user", agent_identity=agent_identity, + filter_user_gate_blocks_agent=filter_user_gate_blocks_agent, available_capabilities=available_capabilities, resolve_capacity=resolve_capacity, - summary_kind="user", ) -def _truncate_quota_payload_text(value: Any, *, limit: int) -> Any: +def _truncate_quota_payload_text(value: object, *, limit: int) -> object: if not isinstance(value, str): return value text = value.strip() @@ -179,75 +205,72 @@ def _truncate_quota_payload_text(value: Any, *, limit: int) -> Any: return text[: max(0, limit - 3)].rstrip() + "..." -def _compact_quota_payload_item(item: Any) -> Any: - if not isinstance(item, dict): +def _compact_payload_item_fields(item: object, *, fields: tuple[str, ...]) -> object: + mapping = _as_dict(item) + if mapping is None: return item - compact: dict[str, Any] = {} - for key in QUOTA_PAYLOAD_ITEM_FIELDS: - value = item.get(key) + compact: Payload = {} + for key in fields: + value = mapping.get(key) if value is None: continue if key in {"text", "title"}: - value = _truncate_quota_payload_text( - value, - limit=QUOTA_PAYLOAD_ITEM_TEXT_LIMIT, - ) + value = _truncate_quota_payload_text(value, limit=QUOTA_PAYLOAD_ITEM_TEXT_LIMIT) compact[key] = value - if "text" not in compact and item.get("text") is not None: - compact["text"] = _truncate_quota_payload_text( - item.get("text"), - limit=QUOTA_PAYLOAD_ITEM_TEXT_LIMIT, + return compact + + +def _compact_quota_payload_item(item: object) -> object: + compact = _compact_payload_item_fields(item, fields=QUOTA_PAYLOAD_ITEM_FIELDS) + mapping, compact_dict = _as_dict(item), _as_dict(compact) + if mapping is not None and compact_dict is not None and "text" not in compact_dict and mapping.get("text") is not None: + compact_dict["text"] = _truncate_quota_payload_text( + mapping.get("text"), limit=QUOTA_PAYLOAD_ITEM_TEXT_LIMIT ) return compact -def _compact_quota_payload_item_list( - items: Any, - *, - limit: int, -) -> list[Any]: +def _compact_quota_payload_item_list(items: object, *, limit: int) -> list[object]: if not isinstance(items, list): return [] return [_compact_quota_payload_item(item) for item in items[:limit]] -def _compact_quota_payload_claim_scope(value: Any) -> Any: - if not isinstance(value, dict): +def _compact_nested_item_lists(value: object, *, items_suffix_only: bool = False) -> object: + mapping = _as_dict(value) + if mapping is None: return value - compact: dict[str, Any] = {} - for key, child in value.items(): - if isinstance(child, list): - compact[key] = _compact_quota_payload_item_list( - child, - limit=QUOTA_PAYLOAD_DIAGNOSTIC_LANE_LIMIT, - ) - else: - compact[key] = child - return compact + return { + key: ( + _compact_quota_payload_item_list(child, limit=QUOTA_PAYLOAD_DIAGNOSTIC_LANE_LIMIT) + if isinstance(child, list) and (not items_suffix_only or key.endswith("items")) + else child + ) + for key, child in mapping.items() + } -def _compact_quota_payload_nested_warning(value: Any) -> Any: - if not isinstance(value, dict): - return value - compact: dict[str, Any] = {} - for key, child in value.items(): - if isinstance(child, list) and key.endswith("items"): - compact[key] = _compact_quota_payload_item_list( - child, - limit=QUOTA_PAYLOAD_DIAGNOSTIC_LANE_LIMIT, - ) - else: - compact[key] = child - return compact +def _compact_quota_payload_claim_scope(value: object) -> object: + return _compact_nested_item_lists(value, items_suffix_only=False) -def compact_quota_todo_summary_for_payload(summary: dict[str, Any]) -> dict[str, Any]: +def _compact_quota_payload_nested_warning(value: object) -> object: + return _compact_nested_item_lists(value, items_suffix_only=True) + + +def _compact_lane_items( + key: str, value: Sequence[object], *, limit: int, + item_compactor: Callable[[object], object], compacted_lanes: dict[str, dict[str, int]], +) -> list[object]: + if len(value) > limit: + compacted_lanes[key] = {"shown": limit, "total": len(value)} + return [item_compactor(item) for item in value[:limit]] + + +def compact_quota_todo_summary_for_payload(summary: PayloadView) -> Payload: """Keep quota hot-path todo summaries bounded without changing decision input.""" - frontier_deadline = todo_summary_frontier_deadline( - summary, - current_time=now_utc(), - ) - compact: dict[str, Any] = {} + frontier_deadline = todo_summary_frontier_deadline(summary, current_time=now_utc()) + compact: Payload = {} compacted_lanes: dict[str, dict[str, int]] = {} for key, value in summary.items(): if key == "advancement_frontier_revision_index": @@ -258,12 +281,10 @@ def compact_quota_todo_summary_for_payload(summary: dict[str, Any]) -> dict[str, continue if isinstance(value, list): limit = QUOTA_PAYLOAD_LANE_LIMITS.get(key, QUOTA_PAYLOAD_VISIBILITY_LANE_LIMIT) - compact[key] = _compact_quota_payload_item_list(value, limit=limit) - if len(value) > limit: - compacted_lanes[key] = { - "shown": limit, - "total": len(value), - } + compact[key] = _compact_lane_items( + key, value, limit=limit, + item_compactor=_compact_quota_payload_item, compacted_lanes=compacted_lanes, + ) elif key == "claim_scope": compact[key] = _compact_quota_payload_claim_scope(value) elif isinstance(value, dict): @@ -283,30 +304,13 @@ def compact_quota_todo_summary_for_payload(summary: dict[str, Any]) -> dict[str, return compact -def _compact_agent_lane_status_todo_item(item: Any) -> Any: - if not isinstance(item, dict): - return item - compact: dict[str, Any] = {} - for key in AGENT_LANE_STATUS_TODO_ITEM_FIELDS: - value = item.get(key) - if value is None: - continue - if key in {"text", "title"}: - value = _truncate_quota_payload_text( - value, - limit=QUOTA_PAYLOAD_ITEM_TEXT_LIMIT, - ) - compact[key] = value - return compact +def _compact_agent_lane_status_todo_item(item: object) -> object: + return _compact_payload_item_fields(item, fields=AGENT_LANE_STATUS_TODO_ITEM_FIELDS) -def _compact_agent_lane_status_todo_summary( - summary: dict[str, Any], - *, - role: str, -) -> dict[str, Any]: +def _compact_agent_lane_status_todo_summary(summary: PayloadView, *, role: str) -> Payload: retained_lanes = set(AGENT_LANE_STATUS_TODO_LANES[role]) - compact: dict[str, Any] = {} + compact: Payload = {} omitted_lanes: list[str] = [] compacted_lanes: dict[str, dict[str, int]] = {} for key, value in summary.items(): @@ -317,19 +321,13 @@ def _compact_agent_lane_status_todo_summary( if value: omitted_lanes.append(key) continue - limit = AGENT_LANE_STATUS_TODO_LANE_LIMITS.get(key, 1) - compact[key] = [ - _compact_agent_lane_status_todo_item(item) - for item in value[:limit] - ] - if len(value) > limit: - compacted_lanes[key] = { - "shown": limit, - "total": len(value), - } + compact[key] = _compact_lane_items( + key, value, limit=AGENT_LANE_STATUS_TODO_LANE_LIMITS.get(key, 1), + item_compactor=_compact_agent_lane_status_todo_item, compacted_lanes=compacted_lanes, + ) continue if isinstance(value, dict): - if key in {"monitor_writeback", "work_counts", "deferred_work_counts"}: + if key in _AGENT_LANE_STATUS_DICT_FIELDS: compact[key] = _compact_quota_payload_nested_warning(value) continue compact[key] = value @@ -339,77 +337,57 @@ def _compact_agent_lane_status_todo_summary( "retained_lanes": sorted(retained_lanes), "omitted_nonempty_lane_count": len(omitted_lanes), "compacted_lanes": compacted_lanes, - "full_detail_cold_path": ( - "status without --agent-id, todo list, or active state" - ), + "full_detail_cold_path": "status without --agent-id, todo list, or active state", } return compact -def _agent_lane_status_project_asset_todo_reference( - summary: dict[str, Any], - *, - role: str, -) -> dict[str, Any]: - reference: dict[str, Any] = {} - for key in ( - "schema_version", - "source_section", - "open", - "done", - "total", - "deferred_count", - "claimed_open_count", - "unclaimed_open_count", - "projection_view", - "detail_pointer", - ): - value = summary.get(key) - if value is not None: - reference[key] = value +def _agent_lane_status_project_asset_todo_reference(summary: PayloadView, *, role: str) -> Payload: + reference: Payload = { + key: value + for key in _AGENT_LANE_STATUS_REF_FIELDS + if (value := summary.get(key)) is not None + } reference["payload_reference"] = { "schema_version": AGENT_LANE_STATUS_TODO_REFERENCE_SCHEMA_VERSION, "canonical_path": f"attention_queue.items[].{role}_todos", - "full_detail_cold_path": ( - "status without --agent-id, todo list, or active state" - ), + "full_detail_cold_path": "status without --agent-id, todo list, or active state", } return reference -def compact_agent_lane_todos_for_status_display(payload: dict[str, object]) -> None: - queue = payload.get("attention_queue") - if not isinstance(queue, dict): - return - items = queue.get("items") +def _compact_role_todos( + container: Payload, *, transform: Callable[[PayloadView, str], Payload] +) -> int: + count = 0 + for key, role in (("user_todos", "user"), ("agent_todos", "agent")): + summary = _as_dict(container.get(key)) + if summary is not None: + container[key] = transform(summary, role) + count += 1 + return count + + +def compact_agent_lane_todos_for_status_display(payload: Payload) -> None: + queue = _as_dict(payload.get("attention_queue")) + items = queue.get("items") if queue is not None else None if not isinstance(items, list): return - compacted = 0 - references = 0 + compacted = references = 0 for item in items: - if not isinstance(item, dict): - continue - for key, role in (("user_todos", "user"), ("agent_todos", "agent")): - summary = item.get(key) - if not isinstance(summary, dict): - continue - item[key] = _compact_agent_lane_status_todo_summary( - summary, - role=role, - ) - compacted += 1 - project_asset = item.get("project_asset") - if not isinstance(project_asset, dict): + item_dict = _as_dict(item) + if item_dict is None: continue - for key, role in (("user_todos", "user"), ("agent_todos", "agent")): - summary = project_asset.get(key) - if not isinstance(summary, dict): - continue - project_asset[key] = _agent_lane_status_project_asset_todo_reference( - summary, - role=role, + compacted += _compact_role_todos( + item_dict, + transform=lambda summary, role: _compact_agent_lane_status_todo_summary(summary, role=role), + ) + project_asset = _as_dict(item_dict.get("project_asset")) + if project_asset is not None: + references += _compact_role_todos( + project_asset, + transform=lambda summary, role: _agent_lane_status_project_asset_todo_reference(summary, role=role), ) - references += 1 if compacted: payload["agent_lane_todo_summary_compaction"] = { "schema_version": AGENT_LANE_STATUS_TODO_COMPACTION_SCHEMA_VERSION, @@ -423,40 +401,35 @@ def compact_agent_lane_todos_for_status_display(payload: dict[str, object]) -> N def summarize_project_asset_todos_for_quota( - value: Any, *, agent_identity: dict[str, Any] | None = None, - filter_user_gate_blocks_agent: bool = False, available_capabilities: Any = None, + value: object, *, agent_identity: PayloadView | None = None, + filter_user_gate_blocks_agent: bool = False, available_capabilities: object = None, resolve_capacity: bool = False, -) -> dict[str, Any] | None: - if not isinstance(value, dict): - return None - return project_quota_planning( - value, all_open_items=[], source_open_count=value.get("open_count"), - agent_identity=agent_identity, filter_user_gate_blocks_agent=filter_user_gate_blocks_agent, +) -> Payload | None: + return _summarize_todos_for_quota( + value, summary_kind="project_asset", agent_identity=agent_identity, + filter_user_gate_blocks_agent=filter_user_gate_blocks_agent, available_capabilities=available_capabilities, resolve_capacity=resolve_capacity, - summary_kind="project_asset", ) -def is_canonical_attention_todo_summary(value: Any) -> bool: - if not isinstance(value, dict): +def is_canonical_attention_todo_summary(value: object) -> bool: + mapping = _as_dict(value) + if mapping is None: return False - if value.get("schema_version") == "todo_summary_v0": + if mapping.get("schema_version") == "todo_summary_v0": return True - source_section = str(value.get("source_section") or "").strip().lower() + source_section = str(mapping.get("source_section") or "").strip().lower() if source_section.startswith("raw "): return False return source_section in {"agent todo", "user todo"} def select_quota_todo_summary( - canonical_value: Any, - project_asset_value: Any, - *, - agent_identity: dict[str, Any] | None = None, - filter_user_gate_blocks_agent: bool = False, - available_capabilities: Any = None, -) -> dict[str, Any] | None: - sources: tuple[tuple[Callable[..., dict[str, Any] | None], Any], ...] = ( + canonical_value: object, project_asset_value: object, *, + agent_identity: PayloadView | None = None, filter_user_gate_blocks_agent: bool = False, + available_capabilities: object = None, +) -> Payload | None: + sources: tuple[tuple[Callable[..., Payload | None], object], ...] = ( (summarize_user_todos_for_quota, canonical_value), (summarize_project_asset_todos_for_quota, project_asset_value), ) @@ -466,189 +439,224 @@ def select_quota_todo_summary( # The fallback is needed only when the preferred source has no summary. for summarize, value in sources: summary = summarize( - value, - agent_identity=agent_identity, + value, agent_identity=agent_identity, filter_user_gate_blocks_agent=filter_user_gate_blocks_agent, - available_capabilities=available_capabilities, - resolve_capacity=True, + available_capabilities=available_capabilities, resolve_capacity=True, ) if summary: return summary - return summary + return None + + +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, +) -> Payload: + return cast(Payload, project_quota_planning( + source, all_open_items=[], source_open_count=source.get("open_count"), + agent_identity=_to_dict_or_none(agent_identity), + filter_user_gate_blocks_agent=filter_user_gate_blocks_agent, + 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, + )) + + +def _project_quota_wires(requests: list[Payload], *, error: str) -> list[object]: + from .goal_todo_projection import project_todo_read + + result = project_todo_read({"kind": "quota_projection", "requests": requests}) + wires = result.get("quota_wires") + if not isinstance(wires, list) or len(wires) != len(requests): + raise RuntimeError(error) + return cast(list[object], wires) def select_quota_todo_summaries( - user_source: Any, agent_source: Any, *, agent_identity: dict[str, Any] | None, -) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: + user_source: object, agent_source: object, *, agent_identity: PayloadView | None, +) -> tuple[Payload | None, Payload | None]: """Compose the refresh caller's two native summaries in one transaction. Supplied and expired source references retain the standalone adapters. The native owner still validates every source and independent request. """ + from .quota_selection import _decode_quota_summary_wire from .summary_item import _CanonicalTodoSummary if isinstance(user_source, _CanonicalTodoSummary) and isinstance(agent_source, _CanonicalTodoSummary): - requests = [project_quota_planning(source, all_open_items=[], - source_open_count=source.get("open_count"), agent_identity=agent_identity, - filter_user_gate_blocks_agent=index == 0, available_capabilities=None, - summary_kind="user", request_only=True) - for index, source in enumerate((user_source, agent_source))] - if all("source_reference" in request["summary_request"] for request in requests): - from .goal_todo_projection import project_todo_read - from .quota_selection import _decode_quota_summary_wire - - result = project_todo_read({"kind": "quota_projection", "requests": requests}) - wires = result.get("quota_wires") - if not isinstance(wires, list) or len(wires) != 2: - raise RuntimeError("invalid complete quota summary response") - return (_decode_quota_summary_wire(wires[0], user_source), - _decode_quota_summary_wire(wires[1], agent_source)) - return (select_quota_todo_summary(user_source, None, agent_identity=agent_identity, - filter_user_gate_blocks_agent=True), - select_quota_todo_summary(agent_source, None, agent_identity=agent_identity)) + requests = [ + _quota_projection_request( + source, agent_identity=agent_identity, filter_user_gate_blocks_agent=index == 0 + ) + for index, source in enumerate((user_source, agent_source)) + ] + if all( + (summary_req := _as_dict(request.get("summary_request"))) is not None + and "source_reference" in summary_req + for request in requests + ): + wires = _project_quota_wires(requests, error="invalid complete quota summary response") + return ( + cast(Payload, _decode_quota_summary_wire(wires[0], user_source)), + cast(Payload, _decode_quota_summary_wire(wires[1], agent_source)), + ) + return ( + select_quota_todo_summary( + user_source, None, agent_identity=agent_identity, filter_user_gate_blocks_agent=True + ), + select_quota_todo_summary(agent_source, None, agent_identity=agent_identity), + ) def select_quota_todo_summaries_with_terminal( - user_source: Any, agent_source: Any, *, agent_identity: dict[str, Any] | None, -) -> tuple[dict[str, Any] | None, dict[str, Any] | None, list[dict[str, Any]]]: + user_source: object, agent_source: object, *, agent_identity: PayloadView | None, +) -> tuple[Payload | None, Payload | None, list[Payload]]: """Read two summaries and complete Agent terminal rows in one transaction. Reuse the typed quota and display owners while requesting only consumed views. Ordinary quota retains its own full displays and prepared wait facts. """ from .quota_selection import _decode_quota_summary_wire - from .goal_todo_projection import project_todo_read - sources = [(role, value) for role, value in (("user", user_source), ("agent", agent_source)) - if isinstance(value, dict)] - requests = [project_quota_planning(value, all_open_items=[], - source_open_count=value.get("open_count"), agent_identity=agent_identity, - filter_user_gate_blocks_agent=role == "user", available_capabilities=None, - summary_kind="user", consume_display_views=role == "agent", request_only=True, - display_view_names=["terminal"] if role == "agent" else None) - for role, value in sources] - summaries: dict[str, dict[str, Any]] = {} - terminal: list[dict[str, Any]] = [] + sources: list[tuple[str, Payload]] = [ + (role, cast(Payload, value)) + for role, value in (("user", user_source), ("agent", agent_source)) + if isinstance(value, dict) + ] + requests = [ + _quota_projection_request( + value, agent_identity=agent_identity, filter_user_gate_blocks_agent=role == "user", + consume_display_views=role == "agent", + display_view_names=["terminal"] if role == "agent" else None, + ) + for role, value in sources + ] + summaries: dict[str, Payload] = {} + terminal: list[Payload] = [] if requests: - result = project_todo_read({"kind": "quota_projection", "requests": requests}) - wires = result.get("quota_wires") - if not isinstance(wires, list) or len(wires) != len(requests): - raise RuntimeError("invalid complete quota projection response") + wires = _project_quota_wires(requests, error="invalid complete quota projection response") for (role, source), wire in zip(sources, wires, strict=True): - summaries[role] = _decode_quota_summary_wire(wire, source) + summaries[role] = cast(Payload, _decode_quota_summary_wire(wire, source)) if role == "agent": - views = wire.get("display_views") - if not isinstance(views, dict) or set(views) != {"terminal"}: + wire_dict = _as_dict(wire) + views = _as_dict(wire_dict.get("display_views")) if wire_dict is not None else None + if views is None or set(views) != {"terminal"}: raise RuntimeError("invalid consumed Agent terminal view") - terminal = views["terminal"] - if not isinstance(terminal, list) or any(not isinstance(row, dict) for row in terminal): - raise RuntimeError("invalid Agent terminal source rows") + terminal = _require_dict_list( + views["terminal"], error="invalid Agent terminal source rows" + ) return summaries.get("user"), summaries.get("agent"), terminal def select_quota_todo_contexts( - user_canonical: Any, user_asset: Any, agent_canonical: Any, agent_asset: Any, - *, agent_identity: dict[str, Any] | None, available_capabilities: Any, -) -> tuple[dict[str, Any] | None, dict[str, Any] | None, dict[str, list[dict[str, Any]]], list[dict[str, Any]]]: + user_canonical: object, user_asset: object, agent_canonical: object, agent_asset: object, + *, agent_identity: PayloadView | None, available_capabilities: object, +) -> 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 .goal_todo_projection import project_todo_read + from .summary_item import _QuotaProjectedSummary - values: list[dict[str, Any]] = [] + values: list[Payload] = [] roles: list[str] = [] - requests: list[dict[str, Any]] = [] - for role, canonical, asset in (("user", user_canonical, user_asset), ("agent", agent_canonical, agent_asset)): + 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) - requests.append(project_quota_planning(source, all_open_items=[], source_open_count=source.get("open_count"), - agent_identity=agent_identity, filter_user_gate_blocks_agent=role == "user", + 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", request_only=True)) - requests[-1]["summary_request"]["consume_source_summary"] = role == "user" - requests[-1]["summary_request"]["consume_vision_wait_basis"] = role == "agent" - summaries: dict[str, dict[str, Any]] = {} - views: dict[str, list[dict[str, Any]]] = {"summary": [], "planning": [], "terminal": []} - user_rows: list[dict[str, Any]] = [] + summary_kind=kind, consume_display_views=role == "agent", + ) + summary_req = _as_dict(request.get("summary_request")) + if summary_req is not None: + summary_req["consume_source_summary"] = role == "user" + summary_req["consume_vision_wait_basis"] = role == "agent" + requests.append(request) + summaries: dict[str, Payload] = {} + views: dict[str, list[Payload]] = {"summary": [], "planning": [], "terminal": []} + user_rows: list[Payload] = [] if requests: - result = project_todo_read({"kind": "quota_projection", "requests": requests}) - wires = result.get("quota_wires") - if not isinstance(wires, list) or len(wires) != len(requests): - raise RuntimeError("invalid complete quota projection response") + wires = _project_quota_wires(requests, error="invalid complete quota projection response") for role, source, wire in zip(roles, values, wires, strict=True): - summaries[role] = _decode_quota_summary_wire(wire, source) + summaries[role] = cast(Payload, _decode_quota_summary_wire(wire, source)) + wire_dict = _as_dict(wire) if role == "user": - user_rows = wire.get("source_summary") - if not isinstance(user_rows, list) or any(not isinstance(row, dict) for row in user_rows): - raise RuntimeError("invalid User quota source display") + user_rows = _require_dict_list( + wire_dict.get("source_summary") if wire_dict is not None else None, + error="invalid User quota source display", + ) if role == "agent": - raw = wire.get("display_views") if isinstance(wire, dict) else None - if not isinstance(raw, dict) or set(raw) != set(views) or any( - not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows) - for rows in raw.values() - ): + raw = _as_dict(wire_dict.get("display_views")) if wire_dict is not None else None + if raw is None or set(raw) != set(views): raise RuntimeError("invalid explicit Agent quota display views") - views = raw - from .summary_item import _QuotaProjectedSummary - basis = wire.get("vision_wait_basis") - if not isinstance(basis, dict): + views = { + name: _require_dict_list( + rows, error="invalid explicit Agent quota display views" + ) + for name, rows in raw.items() + } + basis = _as_dict(wire_dict.get("vision_wait_basis")) if wire_dict is not None else None + if basis is None: raise RuntimeError("invalid prepared quota vision wait basis") - summaries[role] = _QuotaProjectedSummary(summaries[role], basis, views["terminal"], - (agent_identity or {}).get("agent_id")) + summaries[role] = cast(Payload, _QuotaProjectedSummary( + summaries[role], basis, views["terminal"], + (agent_identity or {}).get("agent_id"), + )) return summaries.get("user"), summaries.get("agent"), views, user_rows -def _select_todo_source( - canonical_value: Any, - project_asset_value: Any, -) -> tuple[str, dict[str, Any]] | None: +def _select_todo_source(canonical_value: object, project_asset_value: object) -> tuple[str, Payload] | None: """Keep the projection kind selected by precedence, including aliased values.""" - sources: tuple[tuple[str, Any], ...] = (("user", canonical_value), ("project_asset", project_asset_value)) + sources: tuple[tuple[str, object], ...] = ( + ("user", canonical_value), + ("project_asset", project_asset_value), + ) if not is_canonical_attention_todo_summary(canonical_value): sources = tuple(reversed(sources)) - return next(((kind, source) for kind, source in sources if isinstance(source, dict)), None) + return next( + ((kind, cast(Payload, source)) for kind, source in sources if isinstance(source, dict)), + None, + ) -def select_quota_todo_source_items( - canonical_value: Any, - project_asset_value: Any, -) -> list[dict[str, Any]]: +def select_quota_todo_source_items(canonical_value: object, project_asset_value: object) -> list[Payload]: """Return the authoritative pre-hot-path todo source for semantic checks.""" - selected = _select_todo_source(canonical_value, project_asset_value) - return todo_summary_source_items(selected[1]) if selected is not None else [] + return cast(list[Payload], todo_summary_source_items(selected[1])) if selected is not None else [] def select_planning_inventory_source_items( - canonical_value: Any, - project_asset_value: Any, - *, - include_terminal: bool = False, -) -> list[dict[str, Any]]: + canonical_value: object, project_asset_value: object, *, include_terminal: bool = False, +) -> list[Payload]: """Select the canonical non-terminal rows shared by planning read models.""" - selected = _select_todo_source(canonical_value, project_asset_value) - return (todo_planning_source_items(selected[1], include_terminal=include_terminal) - if selected is not None else []) + return ( + cast(list[Payload], todo_planning_source_items(selected[1], include_terminal=include_terminal)) + if selected is not None + else [] + ) -def _task_orchestration_authority_items( - value: Any, - *, - role: str, -) -> list[dict[str, Any]] | None: - if not isinstance(value, dict): +def _task_orchestration_authority_items(value: object, *, role: str) -> list[Payload] | None: + mapping = _as_dict(value) + if mapping is None: return None - authority = value.get("task_orchestration_authority") + authority = _as_dict(mapping.get("task_orchestration_authority")) if ( - not isinstance(authority, dict) + authority is None or authority.get("schema_version") != "task_orchestration_authority_v0" or authority.get("role") != role ): @@ -657,32 +665,19 @@ def _task_orchestration_authority_items( items = authority.get(key) if not isinstance(items, list): return None - return [item for item in items if isinstance(item, dict)] + return [cast(Payload, item) for item in items if isinstance(item, dict)] def select_task_orchestration_authority_items( - canonical_value: Any, - project_asset_value: Any, - *, - role: str, - fallback_source_items: list[dict[str, Any]] | None = None, -) -> list[dict[str, Any]]: - canonical_items = _task_orchestration_authority_items( - canonical_value, - role=role, - ) - project_asset_items = _task_orchestration_authority_items( - project_asset_value, - role=role, - ) + canonical_value: object, project_asset_value: object, *, role: str, + fallback_source_items: list[Payload] | None = None, +) -> list[Payload]: + canonical_items = _task_orchestration_authority_items(canonical_value, role=role) + project_asset_items = _task_orchestration_authority_items(project_asset_value, role=role) if is_canonical_attention_todo_summary(canonical_value): - selected = ( - canonical_items if canonical_items is not None else project_asset_items - ) + selected = canonical_items if canonical_items is not None else project_asset_items else: - selected = ( - project_asset_items if project_asset_items is not None else canonical_items - ) + selected = project_asset_items if project_asset_items is not None else canonical_items if selected is not None: return selected if fallback_source_items is not None: diff --git a/loopx/control_plane/todos/todo_summary.py b/loopx/control_plane/todos/todo_summary.py index 3561c4cfd4..fa0ecee6ed 100644 --- a/loopx/control_plane/todos/todo_summary.py +++ b/loopx/control_plane/todos/todo_summary.py @@ -1,69 +1,71 @@ from __future__ import annotations -from typing import Any, Callable, Optional, cast - +from collections.abc import Callable, Mapping, Sequence from datetime import datetime import re +from typing import cast +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, +) from ..goals.goal_vision_wait_projection import attach_active_vision_waits +from ..work_items.project_asset import build_project_asset_todo_summary +from .completion_validation_projection import project_completion_validation_authority from .contract import ( 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_target_capabilities, normalize_todo_action_kind, - normalize_todo_capability_binding_ref, - normalize_todo_task_repository, 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_global_gate, normalize_todo_generation, + normalize_todo_global_gate, normalize_todo_goal_bound, normalize_todo_id, normalize_todo_no_followup, - normalize_removed_todo_continuation_policy, normalize_todo_required_decision_scopes, normalize_todo_resume_when, normalize_todo_status, - normalize_todo_task_domain, normalize_todo_task_class, + normalize_todo_task_domain, + normalize_todo_task_repository, todo_done_for_status, ) -from .summary_item import todo_text_content_revision -from .completion_validation_projection import project_completion_validation_authority from .handoff_note import attach_todo_handoff_notes +from .summary_item import todo_text_content_revision from .todo_semantics import ( + todo_item_expires_at as projection_todo_item_expires_at, todo_item_is_actionable_open as projection_todo_item_is_actionable_open, todo_item_is_deferred as projection_todo_item_is_deferred, todo_item_is_due_monitor as projection_todo_item_is_due_monitor, todo_item_missing_monitor_schedule as projection_todo_item_missing_monitor_schedule, - todo_item_task_class as projection_todo_item_task_class, todo_item_next_due_at as projection_todo_item_next_due_at, - todo_item_expires_at as projection_todo_item_expires_at, + todo_item_task_class as projection_todo_item_task_class, + todo_presentation_sort_key as projection_todo_presentation_sort_key, todo_priority_parts as projection_todo_priority_parts, todo_priority_rank as projection_todo_priority_rank, - todo_presentation_sort_key as projection_todo_presentation_sort_key, todo_projection_sort_key as projection_todo_projection_sort_key, ) -from ..work_items.project_asset import build_project_asset_todo_summary from .user_gate import open_user_gate_todo_items -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, -) +Payload = dict[str, object] +PayloadView = Mapping[str, object] MAX_STATUS_TODOS_PER_ROLE = 12 MAX_PROJECT_ASSET_TODO_ITEMS = 3 @@ -77,12 +79,11 @@ TASK_ORCHESTRATION_AUTHORITY_SCHEMA_VERSION = "task_orchestration_authority_v0" TODO_ARCHIVE_STATE_ACTIVE = "active" -AttentionItemBuilder = Callable[..., dict[str, Any]] -GoalLifecycleFields = Callable[[dict[str, Any], Optional[dict[str, Any]]], dict[str, Any]] -PublicSafeText = Callable[..., Optional[str]] -TodoOpenCount = Callable[[Optional[dict[str, Any]]], int] -FirstOpenTodoText = Callable[[Optional[dict[str, Any]]], Optional[str]] - +AttentionItemBuilder = Callable[..., Payload] +GoalLifecycleFields = Callable[[Payload, Payload | None], Payload] +PublicSafeText = Callable[..., str | None] +TodoOpenCount = Callable[[Payload | None], int] +FirstOpenTodoText = Callable[[Payload | None], str | None] TASK_ORCHESTRATION_CANDIDATE_FIELDS = ( "todo_id", @@ -112,6 +113,48 @@ "unblocks_todo_id", ) +_STRUCTURED_PRE_ACTOR_FIELDS: tuple[tuple[str, Callable[[object], object]], ...] = ( + ("action_kind", normalize_todo_action_kind), + ("task_domain", normalize_todo_task_domain), + ("capability_binding_ref", normalize_todo_capability_binding_ref), + ("task_repository", normalize_todo_task_repository), + ("continuation_policy", normalize_todo_continuation_policy), + ("removed_continuation_policy", normalize_removed_todo_continuation_policy), + ("required_write_scopes", normalize_required_write_scopes), + ("required_capabilities", normalize_required_capabilities), + ("target_capabilities", normalize_target_capabilities), + ("explore_result_node_refs", normalize_explore_result_node_refs), + ("decision_scope", normalize_todo_decision_scope), + ("required_decision_scopes", normalize_todo_required_decision_scopes), + ("decision_outcome", normalize_todo_decision_outcome), + ("decision_scope_outcomes", normalize_todo_decision_scope_outcomes), +) +_STRUCTURED_POST_ACTOR_FIELDS: tuple[ + tuple[str, Callable[[object], object], bool], ... +] = ( + ("goal_bound", normalize_todo_goal_bound, False), + ("blocks_agent", normalize_todo_blocks_agent, True), + ("excluded_agents", normalize_todo_excluded_agents, True), + ("global_gate", normalize_todo_global_gate, False), + ("unblocks_todo_id", normalize_todo_id, True), + ("resume_when", normalize_todo_resume_when, True), + ("resume_monitor_generation", normalize_todo_generation, False), + ("material_change_generation", normalize_todo_generation, False), +) +_ACTIVE_NEXT_ACTION_OMIT_FIELDS = ( + "note", "evidence", "reason", "completed_at", "updated_at", "superseded_by", +) + + +def _as_dict(value: object) -> Payload | None: + return cast(Payload, value) if isinstance(value, dict) else None + + +def _as_dict_list(value: object) -> list[Payload]: + if not isinstance(value, list): + return [] + return [cast(Payload, item) for item in value if isinstance(item, dict)] + def normalize_todo_text(text: object, *, limit: int | None = 500) -> str: """Normalize whitespace; source codecs explicitly opt out of display limits.""" @@ -122,91 +165,68 @@ def normalize_todo_text(text: object, *, limit: int | None = 500) -> str: def _structured_todo_text_fields( - item: dict[str, Any], - *, - text_limit: int | None, - include_content_revision: bool, + item: PayloadView, *, text_limit: int | None, include_content_revision: bool, ) -> tuple[str, str | None]: source_text = str(item.get("text") or "") - content_revision = ( - todo_text_content_revision(source_text) - if include_content_revision else None - ) + content_revision = todo_text_content_revision(source_text) if include_content_revision else None return normalize_todo_text(source_text, limit=text_limit), content_revision -def todo_archive_state(item: dict[str, Any]) -> str: +def todo_archive_state(item: PayloadView) -> str: value = str(item.get("archive_state") or TODO_ARCHIVE_STATE_ACTIVE).strip() return value or TODO_ARCHIVE_STATE_ACTIVE def active_state_todo_attention_item( - goal: dict[str, Any], - fields: dict[str, Any], - current_run: dict[str, Any] | None, + goal: PayloadView, + fields: PayloadView, + current_run: Payload | None, *, public_safe_compact_text: PublicSafeText, first_open_todo_text: FirstOpenTodoText, todo_summary_open_count: TodoOpenCount, goal_lifecycle_fields: GoalLifecycleFields, attention_item: AttentionItemBuilder, -) -> dict[str, Any] | None: +) -> Payload | None: """Surface active-state todos even when the latest run classification is passive.""" - - user_todos = cast(dict[str, Any], fields.get("user_todos")) if isinstance(fields.get("user_todos"), dict) else None - agent_todos = cast(dict[str, Any], fields.get("agent_todos")) if isinstance(fields.get("agent_todos"), dict) else None - active_next_action = public_safe_compact_text( - fields.get("active_state_next_action"), - limit=320, - ) + user_todos = _as_dict(fields.get("user_todos")) + agent_todos = _as_dict(fields.get("agent_todos")) + active_next_action = public_safe_compact_text(fields.get("active_state_next_action"), limit=320) user_gate_items = open_user_gate_todo_items(user_todos) user_gate_action = public_safe_compact_text( - user_gate_items[0].get("text") if user_gate_items else None, - limit=320, + user_gate_items[0].get("text") if user_gate_items else None, limit=320 ) user_action = public_safe_compact_text(first_open_todo_text(user_todos), limit=320) agent_action = public_safe_compact_text(first_open_todo_text(agent_todos), limit=320) agent_has_open = bool(agent_action or todo_summary_open_count(agent_todos) > 0) - lifecycle_fields = goal_lifecycle_fields(goal, current_run) + goal_dict = cast(Payload, goal) if isinstance(goal, dict) else dict(goal) + lifecycle_fields = goal_lifecycle_fields(goal_dict, current_run) goal_id = str(goal.get("id") or "unknown-goal") - state_incomplete = fields.get("state_incomplete") - if isinstance(state_incomplete, dict): - item = attention_item( - goal_id=goal_id, - status="state_incomplete", - waiting_on="user_or_controller", - severity="high", - recommended_action=str( - state_incomplete.get("recommended_action") - or "restore the missing active-state Agent Todo section" - ), - source="active_state", - **lifecycle_fields, + def emit(status: str, waiting_on: str, severity: str, recommended_action: str) -> Payload: + return attention_item( + goal_id=goal_id, status=status, waiting_on=waiting_on, severity=severity, + recommended_action=recommended_action, source="active_state", **lifecycle_fields, + ) + + state_incomplete = _as_dict(fields.get("state_incomplete")) + if state_incomplete is not None: + item = emit( + "state_incomplete", "user_or_controller", "high", + str(state_incomplete.get("recommended_action") or "restore the missing active-state Agent Todo section"), ) item["state_incomplete"] = state_incomplete return item - if user_gate_action or user_gate_items: - return attention_item( - goal_id=goal_id, - status="active_state_user_gate", - waiting_on="controller", - severity="action", - recommended_action=( - user_gate_action - or active_next_action - or "resolve the open user_gate todo from the active goal state" - ), - source="active_state", - **lifecycle_fields, + return emit( + "active_state_user_gate", "controller", "action", + user_gate_action or active_next_action or "resolve the open user_gate todo from the active goal state", ) - if user_action or todo_summary_open_count(user_todos) > 0: user_items = [ item - for item in (user_todos.get("first_open_items") if user_todos else []) or [] - if isinstance(item, dict) and item.get("done") is not True + for item in _as_dict_list(user_todos.get("first_open_items") if user_todos else None) + if item.get("done") is not True ] explicit_user_actions_only = bool(user_items) and all( str(item.get("task_class") or "").strip() @@ -214,82 +234,40 @@ def active_state_todo_attention_item( for item in user_items ) if not explicit_user_actions_only: - return attention_item( - goal_id=goal_id, - status="active_state_user_todo", - waiting_on="controller", - severity="action", - recommended_action=( - user_action - or active_next_action - or "resolve the open user todo from the active goal state" - ), - source="active_state", - **lifecycle_fields, + return emit( + "active_state_user_todo", "controller", "action", + user_action or active_next_action or "resolve the open user todo from the active goal state", ) - if agent_has_open: - return attention_item( - goal_id=goal_id, - status="active_state_agent_todo", - waiting_on="codex", - severity="action", - recommended_action=( - agent_action - or active_next_action - or "run the open agent todo from the active goal state" - ), - source="active_state", - **lifecycle_fields, + return emit( + "active_state_agent_todo", "codex", "action", + agent_action or active_next_action or "run the open agent todo from the active goal state", ) - - projection_gap = fields.get("state_projection_gap") - if isinstance(projection_gap, dict): - return attention_item( - goal_id=goal_id, - status="state_projection_gap", - waiting_on="codex", - severity="action", - recommended_action=str( - projection_gap.get("recommended_action") - or "expand the active-state Next Action into parseable todos" - ), - source="active_state", - **lifecycle_fields, + projection_gap = _as_dict(fields.get("state_projection_gap")) + if projection_gap is not None: + return emit( + "state_projection_gap", "codex", "action", + str(projection_gap.get("recommended_action") or "expand the active-state Next Action into parseable todos"), ) - return None def sync_connected_attention_action_from_todos( - item: dict[str, Any], - *, - first_open_todo_text: FirstOpenTodoText, + item: Payload, *, first_open_todo_text: FirstOpenTodoText, ) -> None: if item.get("status") != "connected_without_run": return - agent_lane_action = ( - cast(dict[str, Any], item.get("agent_lane_next_action")) - if isinstance(item.get("agent_lane_next_action"), dict) - else None - ) - if agent_lane_action is None and isinstance(item.get("project_asset"), dict): - project_asset = item["project_asset"] - agent_lane_action = ( - cast(dict[str, Any], project_asset.get("agent_lane_next_action")) - if isinstance(project_asset.get("agent_lane_next_action"), dict) - else None - ) + project_asset = _as_dict(item.get("project_asset")) + agent_lane_action = _as_dict(item.get("agent_lane_next_action")) + if agent_lane_action is None and project_asset is not None: + agent_lane_action = _as_dict(project_asset.get("agent_lane_next_action")) agent_action = normalize_todo_text(agent_lane_action.get("text")) if agent_lane_action else None if not agent_action: - agent_action = first_open_todo_text( - cast(dict[str, Any], item.get("agent_todos")) if isinstance(item.get("agent_todos"), dict) else None - ) + agent_action = first_open_todo_text(_as_dict(item.get("agent_todos"))) if not agent_action: return item["recommended_action"] = agent_action - project_asset = item.get("project_asset") - if isinstance(project_asset, dict): + if project_asset is not None: project_asset["next_action"] = agent_action @@ -297,12 +275,14 @@ def todo_priority_parts(text: str) -> tuple[str | None, str]: return projection_todo_priority_parts(text) -def _structured_todo_agent_fields(item: dict[str, Any]) -> dict[str, str]: +def _structured_todo_agent_fields(item: PayloadView) -> dict[str, str]: """Keep request authorship, execution claim and recipient as distinct actors.""" - actors = {} - for field, normalize in (("created_by", normalize_todo_claimed_by), - ("claimed_by", normalize_todo_claimed_by), - ("bound_agent", normalize_todo_bound_agent)): + actors: dict[str, str] = {} + for field, normalize in ( + ("created_by", normalize_todo_claimed_by), + ("claimed_by", normalize_todo_claimed_by), + ("bound_agent", normalize_todo_bound_agent), + ): actor = normalize(item.get(field)) if actor: actors[field] = actor @@ -310,18 +290,12 @@ def _structured_todo_agent_fields(item: dict[str, Any]) -> dict[str, str]: def structured_todo_item( - item: dict[str, Any], - *, - role: str | None, - source_section: str | None, - archive_state: str = "active", - text_limit: int | None = 500, + item: Payload, *, role: str | None, source_section: str | None, + archive_state: str = "active", text_limit: int | None = 500, include_content_revision: bool = False, -) -> dict[str, Any]: +) -> Payload: text, content_revision = _structured_todo_text_fields( - item, - text_limit=text_limit, - include_content_revision=include_content_revision, + item, text_limit=text_limit, include_content_revision=include_content_revision ) priority, title = todo_priority_parts(text) index = item.get("index") @@ -329,114 +303,28 @@ def structured_todo_item( status = explicit_status or ("done" if item.get("done") else "open") done = todo_done_for_status(status) if explicit_status else bool(item.get("done")) todo_id = item.get("todo_id") or build_todo_id( - role=role, - source_section=source_section, - index=index, - text=text, - ) - normalized = project_completion_validation_authority(item) - normalized.update( - { - "schema_version": TODO_ITEM_SCHEMA_VERSION, - "todo_id": todo_id, - "role": role, - "status": status, - "done": done, - "archive_state": archive_state, - "source_section": source_section, - "text": text, - "task_class": normalize_todo_task_class( - item.get("task_class"), - text=text, - action_kind=item.get("action_kind"), - ), - } + role=role, source_section=source_section, index=index, text=text ) + normalized = cast(Payload, project_completion_validation_authority(item)) + normalized.update({ + "schema_version": TODO_ITEM_SCHEMA_VERSION, "todo_id": todo_id, "role": role, + "status": status, "done": done, "archive_state": archive_state, + "source_section": source_section, "text": text, + "task_class": normalize_todo_task_class( + item.get("task_class"), text=text, action_kind=item.get("action_kind") + ), + }) if content_revision: normalized["content_revision"] = content_revision - action_kind = normalize_todo_action_kind(item.get("action_kind")) - if action_kind: - normalized["action_kind"] = action_kind - task_domain = normalize_todo_task_domain(item.get("task_domain")) - if task_domain: - normalized["task_domain"] = task_domain - capability_binding_ref = normalize_todo_capability_binding_ref( - item.get("capability_binding_ref") - ) - if capability_binding_ref: - normalized["capability_binding_ref"] = capability_binding_ref - task_repository = normalize_todo_task_repository(item.get("task_repository")) - if task_repository: - normalized["task_repository"] = task_repository - continuation_policy = normalize_todo_continuation_policy( - item.get("continuation_policy") - ) - if continuation_policy: - normalized["continuation_policy"] = continuation_policy - removed_continuation_policy = normalize_removed_todo_continuation_policy( - item.get("removed_continuation_policy") - ) - if removed_continuation_policy: - normalized["removed_continuation_policy"] = removed_continuation_policy - required_write_scopes = normalize_required_write_scopes(item.get("required_write_scopes")) - if required_write_scopes: - normalized["required_write_scopes"] = required_write_scopes - required_capabilities = normalize_required_capabilities(item.get("required_capabilities")) - if required_capabilities: - normalized["required_capabilities"] = required_capabilities - target_capabilities = normalize_target_capabilities(item.get("target_capabilities")) - if target_capabilities: - normalized["target_capabilities"] = target_capabilities - explore_result_node_refs = normalize_explore_result_node_refs( - item.get("explore_result_node_refs") - ) - if explore_result_node_refs: - normalized["explore_result_node_refs"] = explore_result_node_refs - decision_scope = normalize_todo_decision_scope(item.get("decision_scope")) - if decision_scope: - normalized["decision_scope"] = decision_scope - required_decision_scopes = normalize_todo_required_decision_scopes( - item.get("required_decision_scopes") - ) - if required_decision_scopes: - normalized["required_decision_scopes"] = required_decision_scopes - decision_outcome = normalize_todo_decision_outcome(item.get("decision_outcome")) - if decision_outcome: - normalized["decision_outcome"] = decision_outcome - decision_scope_outcomes = normalize_todo_decision_scope_outcomes( - item.get("decision_scope_outcomes") - ) - if decision_scope_outcomes: - normalized["decision_scope_outcomes"] = decision_scope_outcomes + for field, normalizer in _STRUCTURED_PRE_ACTOR_FIELDS: + normalized_value = normalizer(item.get(field)) + if normalized_value: + normalized[field] = normalized_value normalized.update(_structured_todo_agent_fields(item)) - goal_bound = normalize_todo_goal_bound(item.get("goal_bound")) - if goal_bound is not None: - normalized["goal_bound"] = goal_bound - blocks_agent = normalize_todo_blocks_agent(item.get("blocks_agent")) - if blocks_agent: - normalized["blocks_agent"] = blocks_agent - excluded_agents = normalize_todo_excluded_agents(item.get("excluded_agents")) - if excluded_agents: - normalized["excluded_agents"] = excluded_agents - global_gate = normalize_todo_global_gate(item.get("global_gate")) - if global_gate is not None: - normalized["global_gate"] = global_gate - unblocks_todo_id = normalize_todo_id(item.get("unblocks_todo_id")) - if unblocks_todo_id: - normalized["unblocks_todo_id"] = unblocks_todo_id - resume_when = normalize_todo_resume_when(item.get("resume_when")) - if resume_when: - normalized["resume_when"] = resume_when - resume_monitor_generation = normalize_todo_generation( - item.get("resume_monitor_generation") - ) - if resume_monitor_generation is not None: - normalized["resume_monitor_generation"] = resume_monitor_generation - material_change_generation = normalize_todo_generation( - item.get("material_change_generation") - ) - if material_change_generation is not None: - normalized["material_change_generation"] = material_change_generation + for field, normalizer, require_truthy in _STRUCTURED_POST_ACTOR_FIELDS: + normalized_value = normalizer(item.get(field)) + if normalized_value if require_truthy else normalized_value is not None: + normalized[field] = normalized_value for field in ("material_change_scope", "material_change_scope_generations"): value = str(item.get(field) or "").strip() if value: @@ -450,16 +338,12 @@ def structured_todo_item( return normalized -def _compact_todo_item_record(item: dict[str, Any]) -> dict[str, Any]: - compact: dict[str, Any] = { - "index": item.get("index"), - "done": bool(item.get("done")), - "text": item.get("text"), +def _compact_todo_item_record(item: PayloadView) -> Payload: + compact: Payload = { + "index": item.get("index"), "done": bool(item.get("done")), "text": item.get("text") } for key in TODO_CANONICAL_READ_RECORD_FIELDS: - if key in compact: - continue - if item.get(key) is not None: + if key not in compact and item.get(key) is not None: compact[key] = item.get(key) if item.get("content_revision"): compact["content_revision"] = item["content_revision"] @@ -468,20 +352,16 @@ def _compact_todo_item_record(item: dict[str, Any]) -> dict[str, Any]: return compact -def compact_todo_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]: - return attach_todo_handoff_notes([_compact_todo_item_record(item) for item in items]) +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_item(item: dict[str, Any]) -> dict[str, Any]: +def compact_todo_item(item: PayloadView) -> Payload: """Singleton adapter; whole-source consumers use the batch owner.""" return compact_todo_items([item])[0] -def canonical_todo_read_record( - item: dict[str, Any], - *, - reject_unknown: bool = False, -) -> dict[str, Any]: +def canonical_todo_read_record(item: PayloadView, *, reject_unknown: bool = False) -> Payload: """Copy one already-normalized Todo consumer record without re-deriving it.""" # Read-policy evaluations are recomputed from a complete source. They must @@ -495,87 +375,79 @@ def canonical_todo_read_record( ) if ( record["schema_version"] != TODO_ITEM_SCHEMA_VERSION - or not isinstance(record["role"], str) - or record["role"] not in {"user", "agent"} - or not isinstance(record["status"], str) - or not record["status"] + or not isinstance(record["role"], str) or record["role"] not in {"user", "agent"} + or not isinstance(record["status"], str) or not record["status"] or not isinstance(record["done"], bool) or not isinstance(record["text"], str) - or not isinstance(record["archive_state"], str) - or not record["archive_state"] - or not isinstance(record["source_section"], str) - or not record["source_section"] + or not isinstance(record["archive_state"], str) or not record["archive_state"] + or not isinstance(record["source_section"], str) or not record["source_section"] ): raise ValueError("canonical Todo read record has invalid required semantics") return record -def _task_orchestration_authority(lanes: dict[str, list[dict[str, Any]]], *, role: str | None) -> dict[str, Any]: +def _task_orchestration_authority(lanes: Mapping[str, Sequence[PayloadView]], *, role: str | None) -> Payload: """Materialize the typed selection using the existing public field allowlist.""" - return {"schema_version": TASK_ORCHESTRATION_AUTHORITY_SCHEMA_VERSION, "role": role, - **{name: [{key: compact[key] for key in fields if key in compact} - for compact in lanes[name]] - for name, fields in (("candidate_items", TASK_ORCHESTRATION_CANDIDATE_FIELDS), - ("user_blocker_items", TASK_ORCHESTRATION_USER_BLOCKER_FIELDS))}} + return { + "schema_version": TASK_ORCHESTRATION_AUTHORITY_SCHEMA_VERSION, + "role": role, + **{ + name: [{key: compact[key] for key in fields if key in compact} for compact in lanes[name]] + for name, fields in ( + ("candidate_items", TASK_ORCHESTRATION_CANDIDATE_FIELDS), + ("user_blocker_items", TASK_ORCHESTRATION_USER_BLOCKER_FIELDS), + ) + }, + } -def todo_item_task_class(item: dict[str, Any]) -> str: +def todo_item_task_class(item: PayloadView) -> str: return projection_todo_item_task_class(item) -def todo_item_is_actionable_open(item: dict[str, Any]) -> bool: +def todo_item_is_actionable_open(item: Payload) -> bool: return projection_todo_item_is_actionable_open(item) -def todo_item_next_due_at(item: dict[str, Any]) -> datetime | None: +def todo_item_next_due_at(item: Payload) -> datetime | None: return projection_todo_item_next_due_at(item) -def todo_item_expires_at(item: dict[str, Any]) -> datetime | None: +def todo_item_expires_at(item: Payload) -> datetime | None: return projection_todo_item_expires_at(item) -def todo_item_is_due_monitor( - item: dict[str, Any], *, now: datetime | None = None -) -> bool: +def todo_item_is_due_monitor(item: Payload, *, now: datetime | None = None) -> bool: return projection_todo_item_is_due_monitor(item, now=now, task_text_keys=("text",)) -def todo_item_missing_monitor_schedule( - item: dict[str, Any], *, now: datetime | None = None -) -> bool: +def todo_item_missing_monitor_schedule(item: Payload, *, now: datetime | None = None) -> bool: return projection_todo_item_missing_monitor_schedule(item, now=now, task_text_keys=("text",)) -def todo_priority_rank(priority: Any) -> int: +def todo_priority_rank(priority: object) -> int: return projection_todo_priority_rank(priority) -def todo_projection_sort_key(item: dict[str, Any]) -> tuple[int, int]: +def todo_projection_sort_key(item: Payload) -> tuple[int, int]: return projection_todo_projection_sort_key(item, text_mode="prefix") -def todo_item_is_deferred(item: dict[str, Any]) -> bool: +def todo_item_is_deferred(item: Payload) -> bool: return projection_todo_item_is_deferred(item) def open_todo_items( - todos: dict[str, Any] | None, - *, - limit: int = MAX_PROJECT_ASSET_TODO_ITEMS, - text_limit: int = 220, - source_keys: tuple[str, ...] = ("first_open_items", "items"), -) -> list[dict[str, Any]]: - if not isinstance(todos, dict): + todos: PayloadView | None, *, limit: int = MAX_PROJECT_ASSET_TODO_ITEMS, + text_limit: int = 220, source_keys: tuple[str, ...] = ("first_open_items", "items"), +) -> list[Payload]: + if not isinstance(todos, Mapping): return [] - result: list[dict[str, Any]] = [] - seen: set[tuple[Any, str]] = set() + result: list[Payload] = [] + seen: set[tuple[object, str]] = set() for source_key in source_keys: - source_items = todos.get(source_key) - if not isinstance(source_items, list): - continue - for item in source_items: - if not isinstance(item, dict) or item.get("done"): + for item in _as_dict_list(todos.get(source_key)): + if item.get("done"): continue text = normalize_todo_text(str(item.get("text") or ""), limit=text_limit) if not text: @@ -585,34 +457,25 @@ def open_todo_items( continue seen.add(key) compact = _compact_todo_item_record(item) - compact["done"] = False - compact["text"] = text + compact["done"], compact["text"] = False, text result.append(compact) if len(result) >= limit: - return sorted(attach_todo_handoff_notes(result), key=projection_todo_presentation_sort_key) - return sorted(attach_todo_handoff_notes(result), key=projection_todo_presentation_sort_key) + break + if len(result) >= limit: + break + return cast(list[Payload], sorted( + attach_todo_handoff_notes(result), key=projection_todo_presentation_sort_key + )) def todo_lane_items( - todos: dict[str, Any] | None, - lane: str, - *, - limit: int = MAX_STATUS_TODOS_PER_ROLE, - text_limit: int = 220, -) -> list[dict[str, Any]]: - return open_todo_items( - todos, - limit=limit, - text_limit=text_limit, - source_keys=(lane,), - ) + todos: PayloadView | None, lane: str, *, + limit: int = MAX_STATUS_TODOS_PER_ROLE, text_limit: int = 220, +) -> list[Payload]: + return open_todo_items(todos, limit=limit, text_limit=text_limit, source_keys=(lane,)) -def first_open_todo_text( - todos: dict[str, Any] | None, - *, - item_limit: int = 220, -) -> str | None: +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) if not items: return None @@ -620,96 +483,69 @@ def first_open_todo_text( def first_open_todo_item( - todos: dict[str, Any] | None, - *, - item_limit: int = MAX_PROJECT_ASSET_TODO_ITEMS, - text_limit: int = 220, -) -> dict[str, Any] | None: + todos: PayloadView | None, *, + item_limit: int = MAX_PROJECT_ASSET_TODO_ITEMS, text_limit: int = 220, +) -> Payload | None: for todo in open_todo_items(todos, limit=item_limit, text_limit=text_limit): - if not isinstance(todo, dict) or todo.get("done"): - continue - return todo + if not todo.get("done"): + return todo return None def project_asset_todo_summary( - todos: dict[str, Any] | None, - *, - role: str | None = None, + todos: Payload | None, *, role: str | None = None, item_limit: int = MAX_PROJECT_ASSET_TODO_ITEMS, deferred_item_limit: int = MAX_DEFERRED_TODO_VISIBILITY_ITEMS, advancement_task_class: str = TODO_TASK_CLASS_ADVANCEMENT, -) -> dict[str, Any] | None: - return build_project_asset_todo_summary( - todos, - role=role, - item_limit=item_limit, - deferred_item_limit=deferred_item_limit, +) -> Payload | None: + return cast(Payload | None, build_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), + value, limit=kwargs.get("limit", item_limit), text_limit=kwargs.get("text_limit", 220), source_keys=kwargs.get("source_keys", ("first_open_items", "items")), ), compact_todo_item=compact_todo_item, todo_lane_items=lambda value, lane, **kwargs: todo_lane_items( - value, - lane, - limit=kwargs.get("limit", MAX_STATUS_TODOS_PER_ROLE), + value, lane, limit=kwargs.get("limit", MAX_STATUS_TODOS_PER_ROLE), text_limit=kwargs.get("text_limit", 220), ), todo_item_is_actionable_open=todo_item_is_actionable_open, todo_item_task_class=todo_item_task_class, - ) + )) def dependency_blocker_summary( - items: list[dict[str, Any]], - *, - current_goal_id: str, - limit: int = MAX_DEPENDENCY_BLOCKERS, -) -> dict[str, Any] | None: - blockers: list[dict[str, Any]] = [] + items: Sequence[PayloadView], *, current_goal_id: str, limit: int = MAX_DEPENDENCY_BLOCKERS, +) -> Payload | None: + blockers: list[Payload] = [] for item in items: - if not isinstance(item, dict): + if not isinstance(item, Mapping): continue goal_id = str(item.get("goal_id") or "") if not goal_id or goal_id == current_goal_id: continue - raw_user_todos = item.get("user_todos") - user_todos = raw_user_todos if isinstance(raw_user_todos, dict) else {} - for todo in user_todos.get("items") or []: - if not isinstance(todo, dict) or todo.get("done"): + user_todos = _as_dict(item.get("user_todos")) + for todo in _as_dict_list(user_todos.get("items") if user_todos else None): + if todo.get("done"): continue text = normalize_todo_text(str(todo.get("text") or ""), limit=220) if not text: continue - blockers.append( - { - "goal_id": goal_id, - "status": item.get("status"), - "waiting_on": item.get("waiting_on"), - "severity": item.get("severity"), - "index": todo.get("index"), - "text": text, - "source": "user_todos", - } - ) + blockers.append({ + "goal_id": goal_id, "status": item.get("status"), + "waiting_on": item.get("waiting_on"), "severity": item.get("severity"), + "index": todo.get("index"), "text": text, "source": "user_todos", + }) if not blockers: return None return { - "source": "attention_queue.user_todos", - "open_count": len(blockers), - "items": blockers[:limit], + "source": "attention_queue.user_todos", "open_count": len(blockers), "items": blockers[:limit] } -def attach_dependency_blockers( - items: list[dict[str, Any]], - *, - limit: int = MAX_DEPENDENCY_BLOCKERS, -) -> None: +def attach_dependency_blockers(items: Sequence[Payload], *, limit: int = MAX_DEPENDENCY_BLOCKERS) -> None: for item in items: if not isinstance(item, dict): continue @@ -721,9 +557,7 @@ def attach_dependency_blockers( item["dependency_blockers"] = blockers - - -def active_next_action_todo_ids(value: Any) -> set[str]: +def active_next_action_todo_ids(value: object) -> set[str]: todo_ids: set[str] = set() for match in re.findall(r"\btodo_[A-Za-z0-9_-]+\b", str(value or "")): todo_id = normalize_todo_id(match) @@ -732,56 +566,42 @@ def active_next_action_todo_ids(value: Any) -> set[str]: return todo_ids -def todo_successor_todo_ids(item: dict[str, Any], *, items: list[dict[str, Any]]) -> list[str]: +def todo_successor_todo_ids(item: PayloadView, *, items: Sequence[Payload]) -> list[str]: """Compatibility call site for repair-delta; the typed graph owns links.""" from .succession_warning import evaluate_succession selected = dict(item) - evaluation = evaluate_succession([selected], items)[0] + evaluation = evaluate_succession([selected], list(items))[0] return list(evaluation["successor_todo_ids"]) def _structured_todo_group_items( - items: list[dict[str, Any]], - *, - source_section: str | None, - role: str | None, - text_limit: int | None, - include_content_revision: bool, -) -> list[dict[str, Any]]: + items: Sequence[Payload], *, source_section: str | None, role: str | None, + text_limit: int | None, include_content_revision: bool, +) -> list[Payload]: return [ structured_todo_item( - item, - role=role, - source_section=source_section, - archive_state=todo_archive_state(item), - text_limit=text_limit, + item, role=role, source_section=source_section, + archive_state=todo_archive_state(item), text_limit=text_limit, include_content_revision=include_content_revision, ) - if isinstance(item, dict) - else item + if isinstance(item, dict) else item for item in items ] def _structured_resume_source_items( - items: list[dict[str, Any]] | None, - *, - source_section: str | None, -) -> list[dict[str, Any]]: + items: Sequence[PayloadView] | None, *, source_section: str | None, +) -> list[Payload]: return [ structured_todo_item( - item, + cast(Payload, item), role=item.get("role") if isinstance(item.get("role"), str) else None, source_section=( - item.get("source_section") - if isinstance(item.get("source_section"), str) - else source_section + item.get("source_section") if isinstance(item.get("source_section"), str) else source_section ), archive_state=( - str(item.get("archive_state")) - if item.get("archive_state") is not None - else TODO_ARCHIVE_STATE_ACTIVE + str(item.get("archive_state")) if item.get("archive_state") is not None else TODO_ARCHIVE_STATE_ACTIVE ), include_content_revision=True, ) @@ -790,86 +610,82 @@ def _structured_resume_source_items( ] - - - - +def _finalize_projected_todo_group( + projected: PayloadView, *, role: str | None, include_empty_source: bool, + include_task_orchestration_authority: bool, vision_runs: list[Payload] | None, + lineage_items: list[Payload] | None, +) -> Payload | None: + if not projected["selected_count"] and not include_empty_source: + return None + summary = _as_dict(projected["summary"]) + if summary is None: + return None + items = _as_dict_list(projected.get("items", summary["items"])) + attach_active_vision_waits(summary, vision_runs, role=role, items=items, lineage_items=lineage_items) + if include_task_orchestration_authority: + orchestration = cast(Mapping[str, Sequence[PayloadView]], projected["orchestration"]) + summary["task_orchestration_authority"] = _task_orchestration_authority(orchestration, role=role) + return summary def compact_todo_group( - items: list[dict[str, Any]], - *, - source_section: str | None, - role: str | None = None, - include_empty_source: bool = False, - preferred_todo_ids: set[str] | None = None, - resume_source_items: list[dict[str, Any]] | None = None, - rollout_events: list[dict[str, Any]] | None = None, - available_capabilities: Any = None, - item_limit: int | None = MAX_STATUS_TODOS_PER_ROLE, - text_limit: int | None = 500, - include_content_revision: bool = True, - include_task_orchestration_authority: bool = False, - vision_runs: list[dict[str, Any]] | None = None, + items: Sequence[Payload], *, source_section: str | None, role: str | None = None, + include_empty_source: bool = False, preferred_todo_ids: set[str] | None = None, + resume_source_items: list[Payload] | None = None, rollout_events: list[Payload] | None = None, + available_capabilities: object = None, item_limit: int | None = MAX_STATUS_TODOS_PER_ROLE, + text_limit: int | None = 500, include_content_revision: bool = True, + include_task_orchestration_authority: bool = False, vision_runs: list[Payload] | None = None, evaluated_at: str | None = None, -) -> dict[str, Any] | None: +) -> Payload | None: from .goal_todo_projection import project_todo_read_group if not items and not include_empty_source: return None - items = _structured_todo_group_items(items, source_section=source_section, role=role, - text_limit=text_limit, include_content_revision=include_content_revision) - resume_lineage = (_structured_resume_source_items(resume_source_items, source_section=source_section) - if any(normalize_todo_resume_when(item.get("resume_when")) for item in items) else None) - projected = project_todo_read_group(items, source_section=source_section, role=role, + structured_items = _structured_todo_group_items( + items, source_section=source_section, role=role, + text_limit=text_limit, include_content_revision=include_content_revision, + ) + resume_lineage = ( + _structured_resume_source_items(resume_source_items, source_section=source_section) + if any(normalize_todo_resume_when(item.get("resume_when")) for item in structured_items) + else None + ) + projected = project_todo_read_group( + structured_items, source_section=source_section, role=role, preferred_todo_ids=preferred_todo_ids, lineage=resume_source_items, resume_lineage=resume_lineage, item_limit=item_limit, rollout_events=rollout_events, available_capabilities=available_capabilities, evaluated_at=evaluated_at, include_full_source=bool(vision_runs), - include_task_orchestration_authority=include_task_orchestration_authority) - items = projected.get("items", projected["summary"]["items"]) - if not projected["selected_count"] and not include_empty_source: - return None - summary = projected["summary"] - attach_active_vision_waits(summary, vision_runs, role=role, items=items, - lineage_items=resume_source_items) - if include_task_orchestration_authority: - summary["task_orchestration_authority"] = _task_orchestration_authority( - projected["orchestration"], role=role) - return cast(dict[str, Any] | None, summary) - + include_task_orchestration_authority=include_task_orchestration_authority, + ) + return _finalize_projected_todo_group( + projected, role=role, include_empty_source=include_empty_source, + include_task_orchestration_authority=include_task_orchestration_authority, + vision_runs=vision_runs, lineage_items=resume_source_items, + ) def compact_evaluated_todo_group( - items: list[dict[str, Any]], - *, - source_section: str | None, - role: str | None = None, - include_empty_source: bool = False, - preferred_todo_ids: set[str] | None = None, + items: Sequence[Payload], *, source_section: str | None, role: str | None = None, + include_empty_source: bool = False, preferred_todo_ids: set[str] | None = None, item_limit: int | None = MAX_STATUS_TODOS_PER_ROLE, - include_task_orchestration_authority: bool = False, - vision_runs: list[dict[str, Any]] | None = None, - lineage_items: list[dict[str, Any]] | None = None, - full_selection: bool = True, - selection: dict[str, Any] | None = None, -) -> dict[str, Any] | None: + include_task_orchestration_authority: bool = False, vision_runs: list[Payload] | None = None, + lineage_items: list[Payload] | None = None, full_selection: bool = True, + selection: PayloadView | None = None, +) -> Payload | None: from .goal_todo_projection import project_todo_read_group if not items and not include_empty_source: return None - lineage = lineage_items - projected = project_todo_read_group(items, source_section=source_section, role=role, - preferred_todo_ids=preferred_todo_ids, lineage=lineage, item_limit=item_limit, - evaluated=True, selection=selection, full_selection=full_selection, - include_full_source=bool(vision_runs), include_task_orchestration_authority=include_task_orchestration_authority) - items = projected.get("items", projected["summary"]["items"]) - if not projected["selected_count"] and not include_empty_source: - return None - summary = projected["summary"] - attach_active_vision_waits(summary, vision_runs, role=role, items=items, - lineage_items=lineage_items) - if include_task_orchestration_authority: - summary["task_orchestration_authority"] = _task_orchestration_authority( - projected["orchestration"], role=role) - return cast(dict[str, Any] | None, summary) + projected = project_todo_read_group( + items, source_section=source_section, role=role, + preferred_todo_ids=preferred_todo_ids, lineage=lineage_items, + item_limit=item_limit, evaluated=True, selection=selection, full_selection=full_selection, + include_full_source=bool(vision_runs), + include_task_orchestration_authority=include_task_orchestration_authority, + ) + return _finalize_projected_todo_group( + projected, role=role, include_empty_source=include_empty_source, + include_task_orchestration_authority=include_task_orchestration_authority, + vision_runs=vision_runs, lineage_items=lineage_items, + ) diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index 22eee62fda..79f6517096 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -396,7 +396,9 @@ def qualify_replan_writeback( obligation, None, goal_id=goal_id, agent_id=safe_agent_id, source_status=status_payload, stride_strategy=context["stride_strategy"], explore_reader=replan_explore_reader, - goal_acceptance_contract=(agent_todos or {}).get("goal_acceptance_contract"), + goal_acceptance_contract=( + contract if isinstance(contract := (agent_todos or {}).get("goal_acceptance_contract"), Mapping) else None + ), todo_items=agent_todo_source_items, ) if not obligation: