From fef253aeab56aec86a5fad6fac0fd11133b73558 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:54:54 +0800 Subject: [PATCH] refactor(control-plane): modularize todo_semantics with zero-Any types and hot-path optimizations Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../todos/todo_item_semantics.py | 343 +++++++ loopx/control_plane/todos/todo_semantics.py | 922 ++++-------------- .../todos/todo_summary_semantics.py | 501 ++++++++++ .../test_todo_semantics_contract.py | 508 ++++++++++ 4 files changed, 1523 insertions(+), 751 deletions(-) create mode 100644 loopx/control_plane/todos/todo_item_semantics.py create mode 100644 loopx/control_plane/todos/todo_summary_semantics.py create mode 100644 tests/control_plane/test_todo_semantics_contract.py diff --git a/loopx/control_plane/todos/todo_item_semantics.py b/loopx/control_plane/todos/todo_item_semantics.py new file mode 100644 index 0000000000..dad23efbda --- /dev/null +++ b/loopx/control_plane/todos/todo_item_semantics.py @@ -0,0 +1,343 @@ +from __future__ import annotations + +from collections.abc import Mapping +from datetime import datetime +import re +from typing import cast + +from ..coordination.coordination_state_contract_generated import ( + COORDINATION_STATE_CONTRACT, +) +from ..runtime.public_safety import public_safe_compact_text +from ..scheduler.monitor_todo import ( + monitor_todo_expires_at, + monitor_todo_is_actionable_open, + monitor_todo_is_due, + monitor_todo_is_expired, + monitor_todo_missing_schedule, + monitor_todo_next_due_at, + monitor_todo_task_class, +) +from .contract import ( + TODO_STATUS_BLOCKED, + TODO_STATUS_DEFERRED, + TODO_TASK_CLASS_BLOCKER, + TODO_TASK_CLASS_MONITOR, + normalize_removed_todo_continuation_policy, + normalize_todo_claimed_by, + normalize_todo_excluded_agents, + normalize_todo_status, + normalize_todo_watch_only, +) + +TodoObject = dict[str, object] +TodoMapping = Mapping[str, object] + +_CONTRACT_MAP = cast(Mapping[str, object], COORDINATION_STATE_CONTRACT) +_PRIORITY_CONTRACT = cast(Mapping[str, object], _CONTRACT_MAP["todo_priority"]) +_READ_RECORD_CONTRACT = cast(Mapping[str, object], _CONTRACT_MAP["todo_read_record"]) +_DOMAIN_RECORD_CONTRACT = cast(Mapping[str, object], _CONTRACT_MAP["todo_domain_record"]) +_PRIORITY_VALUES = cast(tuple[object, ...], _PRIORITY_CONTRACT["values"]) +_PRIORITY_RANK_BY_VALUE: dict[str, int] = { + str(label): index for index, label in enumerate(_PRIORITY_VALUES) +} + +TODO_MISSING_PRIORITY_RANK = int(cast(int, _PRIORITY_CONTRACT["missing_rank"])) +TODO_MISSING_INDEX = 999999 +TODO_PRIORITY_PREFIX_PATTERN = re.compile( + str(_PRIORITY_CONTRACT["legacy_prefix_pattern"]), re.IGNORECASE +) +TODO_PRIORITY_LABEL_PATTERN = re.compile( + str(_PRIORITY_CONTRACT["legacy_label_pattern"]), re.IGNORECASE +) +TODO_PRESENTATION_METADATA_SCHEMA = "loopx_todo_presentation_metadata_v0" +TODO_LEGACY_ITEM_SCHEMA = str(_READ_RECORD_CONTRACT["item_schema_version"]) +TODO_NATIVE_ITEM_SCHEMA = str(_DOMAIN_RECORD_CONTRACT["item_schema_version"]) + + +def _object_dict(item: TodoMapping) -> TodoObject: + return cast(TodoObject, item) if isinstance(item, dict) else dict(item) + + +def _non_bool_non_negative_int(value: object) -> int | None: + return ( + int(value) + if isinstance(value, int) and not isinstance(value, bool) and value >= 0 + else None + ) + + +def _has_source_section(item: TodoMapping) -> bool: + source_section = item.get("source_section") + return isinstance(source_section, str) and bool(source_section.strip()) + + +def positive_int(value: object) -> int: + try: + parsed = int(cast(int | float | str | bytes, value)) + except (TypeError, ValueError): + return 0 + return max(0, parsed) + + +def todo_blocker_reason(item: TodoMapping) -> str | None: + """Project a bounded, public-safe cause for blocked work of any task class.""" + + if ( + normalize_todo_status(item.get("status")) != TODO_STATUS_BLOCKED + and todo_item_task_class(item) != TODO_TASK_CLASS_BLOCKER + ): + return None + return public_safe_compact_text(item.get("reason"), limit=220) + + +def todo_item_is_watch_only_monitor(item: TodoMapping) -> bool: + return bool( + todo_item_task_class(item) == TODO_TASK_CLASS_MONITOR + and normalize_todo_watch_only(item.get("watch_only")) is True + ) + + +def todo_priority_parts(text: str) -> tuple[str | None, str]: + match = TODO_PRIORITY_PREFIX_PATTERN.match(text) + if not match: + return None, text + return match.group(1).strip().upper(), match.group(2).strip() + + +def todo_priority_label( + item: TodoMapping, + *, + text_mode: str = "label", +) -> str | None: + # Read compatibility codec only. Vocabulary/grammar/rank are generated + # from the shared contract; mutations are planned by todos/priority.ts. + # text_mode remains an import/API compatibility argument, not another rule. + if "priority" in item: + value = item["priority"] + else: + value, _ = todo_priority_parts(str(item.get("text") or item.get("title") or "")) + match = TODO_PRIORITY_LABEL_PATTERN.match(value.strip()) if isinstance(value, str) else None + return match.group(1).upper() if match else None + + +def todo_priority_rank(value: object, *, text_mode: str = "label") -> int: + mapping = cast(TodoMapping, value) if isinstance(value, Mapping) else {"priority": value} + priority = todo_priority_label(mapping, text_mode=text_mode) + return _PRIORITY_RANK_BY_VALUE.get(priority, TODO_MISSING_PRIORITY_RANK) if priority else TODO_MISSING_PRIORITY_RANK + + +def todo_index_rank(item: TodoMapping) -> int: + raw_index = item.get("index") + if raw_index is None: + return TODO_MISSING_INDEX + try: + return int(cast(int | float | str | bytes, raw_index)) + except (TypeError, ValueError): + return TODO_MISSING_INDEX + + +def todo_presentation_metadata(item: TodoMapping) -> TodoObject: + """Project one Todo's display address without making it domain state. + + The v0 ``source_section``/``index`` pair is the wire shape's canonical + presentation coordinate. Native domain records derive a section from role + and archival state and intentionally receive no synthetic persisted index. + """ + + if not isinstance(item, Mapping): + raise ValueError("Todo presentation input must be an object") + schema = item.get("schema_version") + if schema not in {None, TODO_LEGACY_ITEM_SCHEMA, TODO_NATIVE_ITEM_SCHEMA}: + raise ValueError(f"unsupported Todo presentation schema: {schema!r}") + has_section = _has_source_section(item) + legacy = schema == TODO_LEGACY_ITEM_SCHEMA or (schema is None and has_section) + if legacy: + section: object = item.get("source_section") if has_section else None + display_order = _non_bool_non_negative_int(item.get("index")) + order_source = "source_index" if display_order is not None else "todo_id" + else: + section = None + display_order = None + order_source = "todo_id" + if not section: + section = ( + "Completed Work Archive" + if item.get("archive_state") == "archive" + else "Agent Todo" + if item.get("role") == "agent" + else "User Todo" + ) + return { + "schema_version": TODO_PRESENTATION_METADATA_SCHEMA, + "todo_id": str(item.get("todo_id") or ""), + "display_section": section, + "display_order": display_order, + "order_source": order_source, + } + + +def _presentation_display_order(item: TodoMapping) -> int | None: + if not isinstance(item, Mapping): + raise ValueError("Todo presentation input must be an object") + schema = item.get("schema_version") + if schema == TODO_NATIVE_ITEM_SCHEMA: + return None + if schema is None and not _has_source_section(item): + return None + return _non_bool_non_negative_int(item.get("index")) + + +def todo_presentation_sort_key( + item: TodoMapping, + *, + text_mode: str = "label", +) -> tuple[int, int, str, str]: + """Sort display rows while preserving source coordinates and native determinism. + + Legacy rows with an equal priority/index retain Python's stable input order. + Native rows have no fabricated index, so timestamp and Todo identity provide + a deterministic tie-break that matches the TypeScript presentation adapter. + """ + + priority = todo_priority_rank(item, text_mode=text_mode) + display_order = _presentation_display_order(item) + if display_order is not None: + return (priority, display_order, "", "") + timestamp = str(item.get("completed_at") or item.get("updated_at") or "") + todo_id = str(item.get("todo_id") or "") + return (priority, TODO_MISSING_INDEX, timestamp, todo_id) + + +def todo_projection_sort_key( + item: TodoMapping, + *, + text_mode: str = "label", +) -> tuple[int, int]: + return (todo_priority_rank(item, text_mode=text_mode), todo_index_rank(item)) + + +def todo_item_task_text( + item: TodoMapping, + *, + keys: tuple[str, ...] = ("title", "text"), +) -> str: + parts: list[str] = [] + for key in keys: + text = str(item.get(key) or "") + if text.strip(): + parts.append(text) + return " ".join(parts) + + +def todo_item_task_class( + item: TodoMapping, + *, + task_text_keys: tuple[str, ...] = ("title", "text"), +) -> str: + return monitor_todo_task_class( + item, + task_text=todo_item_task_text(item, keys=task_text_keys), + ) + + +def todo_item_is_actionable_open(item: TodoMapping) -> bool: + guard = item.get("goal_acceptance_guard") + if isinstance(guard, Mapping) and guard.get("allowed") is False: + return False + return monitor_todo_is_actionable_open(_object_dict(item)) + + +def todo_item_is_deferred(item: TodoMapping) -> bool: + return (normalize_todo_status(item.get("status")) or "") == TODO_STATUS_DEFERRED + + +def todo_item_next_due_at(item: TodoMapping) -> datetime | None: + return monitor_todo_next_due_at(_object_dict(item)) + + +def todo_item_expires_at(item: TodoMapping) -> datetime | None: + return monitor_todo_expires_at(_object_dict(item)) + + +def todo_item_is_expired_monitor( + item: TodoMapping, *, now: datetime | None = None +) -> bool: + return monitor_todo_is_expired(_object_dict(item), now=now) + + +def todo_item_is_due_monitor( + item: TodoMapping, + *, + now: datetime | None = None, + task_text_keys: tuple[str, ...] = ("title", "text"), +) -> bool: + return monitor_todo_is_due( + _object_dict(item), + now=now, + task_text=todo_item_task_text(item, keys=task_text_keys), + ) + + +def todo_item_missing_monitor_schedule( + item: TodoMapping, + *, + now: datetime | None = None, + task_text_keys: tuple[str, ...] = ("title", "text"), +) -> bool: + return monitor_todo_missing_schedule( + _object_dict(item), + now=now, + task_text=todo_item_task_text(item, keys=task_text_keys), + ) + + +def todo_item_has_removed_continuation_policy(item: TodoMapping) -> bool: + return bool( + normalize_removed_todo_continuation_policy( + item.get("removed_continuation_policy") + ) + ) + + +def todo_item_excludes_agent( + item: TodoMapping, + *, + agent_id: str | None, +) -> bool: + normalized_agent_id = normalize_todo_claimed_by(agent_id) + return bool( + normalized_agent_id + and normalized_agent_id + in normalize_todo_excluded_agents(item.get("excluded_agents")) + ) + + +def todo_item_allows_normalized_agent( + item: TodoMapping, + *, + normalized_agent_id: str | None, +) -> bool: + """Check claim and exclusion boundaries when agent_id is pre-normalized.""" + + if todo_item_has_removed_continuation_policy(item): + return False + if not normalized_agent_id: + return True + if normalized_agent_id in normalize_todo_excluded_agents( + item.get("excluded_agents") + ): + return False + claimed_by = normalize_todo_claimed_by(item.get("claimed_by")) + return not claimed_by or claimed_by == normalized_agent_id + + +def todo_item_claimed_by_agent_or_unclaimed( + item: TodoMapping, + *, + agent_id: str | None, +) -> bool: + return todo_item_allows_normalized_agent( + item, + normalized_agent_id=normalize_todo_claimed_by(agent_id), + ) diff --git a/loopx/control_plane/todos/todo_semantics.py b/loopx/control_plane/todos/todo_semantics.py index 104f65e723..4e8f6869fa 100644 --- a/loopx/control_plane/todos/todo_semantics.py +++ b/loopx/control_plane/todos/todo_semantics.py @@ -1,816 +1,236 @@ from __future__ import annotations -from typing import Any, Mapping, cast - - -from datetime import datetime +from collections.abc import Mapping import re +from typing import cast -from ..scheduler.monitor_todo import ( - monitor_todo_expires_at, - monitor_todo_is_actionable_open, - monitor_todo_is_due, - monitor_todo_is_expired, - monitor_todo_missing_schedule, - monitor_todo_next_due_at, - monitor_todo_task_class, -) -from ..runtime.public_safety import public_safe_compact_text -from ..coordination.coordination_state_contract_generated import ( - COORDINATION_STATE_CONTRACT, -) from .contract import ( - TODO_STATUS_BLOCKED, - TODO_STATUS_DEFERRED, - TODO_TASK_CLASS_ADVANCEMENT, - TODO_TASK_CLASS_BLOCKER, - TODO_TASK_CLASS_MONITOR, + TODO_STATUS_BLOCKED as TODO_STATUS_BLOCKED, + TODO_STATUS_DEFERRED as TODO_STATUS_DEFERRED, + TODO_TASK_CLASS_ADVANCEMENT as TODO_TASK_CLASS_ADVANCEMENT, + TODO_TASK_CLASS_BLOCKER as TODO_TASK_CLASS_BLOCKER, + TODO_TASK_CLASS_MONITOR as TODO_TASK_CLASS_MONITOR, normalize_todo_claimed_by, normalize_todo_excluded_agents, - normalize_removed_todo_continuation_policy, normalize_todo_id, - normalize_todo_status, - normalize_todo_watch_only, ) - - -_PRIORITY_CONTRACT = COORDINATION_STATE_CONTRACT["todo_priority"] -TODO_MISSING_PRIORITY_RANK = int(_PRIORITY_CONTRACT["missing_rank"]) -TODO_MISSING_INDEX = 999999 -TODO_PRIORITY_PREFIX_PATTERN = re.compile(_PRIORITY_CONTRACT["legacy_prefix_pattern"], re.IGNORECASE) -TODO_PRIORITY_LABEL_PATTERN = re.compile(_PRIORITY_CONTRACT["legacy_label_pattern"], re.IGNORECASE) -TODO_PRESENTATION_METADATA_SCHEMA = "loopx_todo_presentation_metadata_v0" -TODO_LEGACY_ITEM_SCHEMA = str( - COORDINATION_STATE_CONTRACT["todo_read_record"]["item_schema_version"] +from .todo_item_semantics import ( + TODO_LEGACY_ITEM_SCHEMA as TODO_LEGACY_ITEM_SCHEMA, + TODO_MISSING_INDEX as TODO_MISSING_INDEX, + TODO_MISSING_PRIORITY_RANK as TODO_MISSING_PRIORITY_RANK, + TODO_NATIVE_ITEM_SCHEMA as TODO_NATIVE_ITEM_SCHEMA, + TODO_PRESENTATION_METADATA_SCHEMA as TODO_PRESENTATION_METADATA_SCHEMA, + TODO_PRIORITY_LABEL_PATTERN as TODO_PRIORITY_LABEL_PATTERN, + TODO_PRIORITY_PREFIX_PATTERN as TODO_PRIORITY_PREFIX_PATTERN, + TodoMapping, + TodoObject, + positive_int as _positive_int, + todo_blocker_reason as todo_blocker_reason, + todo_index_rank as todo_index_rank, + todo_item_claimed_by_agent_or_unclaimed as todo_item_claimed_by_agent_or_unclaimed, + todo_item_excludes_agent as todo_item_excludes_agent, + todo_item_expires_at as todo_item_expires_at, + todo_item_has_removed_continuation_policy as todo_item_has_removed_continuation_policy, + todo_item_is_actionable_open as todo_item_is_actionable_open, + todo_item_is_deferred as todo_item_is_deferred, + todo_item_is_due_monitor as todo_item_is_due_monitor, + todo_item_is_expired_monitor as todo_item_is_expired_monitor, + todo_item_is_watch_only_monitor as todo_item_is_watch_only_monitor, + todo_item_missing_monitor_schedule as todo_item_missing_monitor_schedule, + todo_item_next_due_at as todo_item_next_due_at, + todo_item_task_class as todo_item_task_class, + todo_item_task_text as todo_item_task_text, + todo_presentation_metadata as todo_presentation_metadata, + todo_presentation_sort_key as todo_presentation_sort_key, + todo_priority_label as todo_priority_label, + todo_priority_parts as todo_priority_parts, + todo_priority_rank as todo_priority_rank, + todo_projection_sort_key as todo_projection_sort_key, ) -TODO_NATIVE_ITEM_SCHEMA = str( - COORDINATION_STATE_CONTRACT["todo_domain_record"]["item_schema_version"] +from .todo_summary_semantics import ( + _summary_monitor_items as _summary_monitor_items, + todo_summary_claim_scope_agent_id as todo_summary_claim_scope_agent_id, + todo_summary_first_executable_item as todo_summary_first_executable_item, + todo_summary_has_only_future_scoped_monitor_work as todo_summary_has_only_future_scoped_monitor_work, + todo_summary_monitor_due_count as todo_summary_monitor_due_count, + todo_summary_monitor_due_items as todo_summary_monitor_due_items, + todo_summary_monitor_items as todo_summary_monitor_items, + todo_summary_monitor_schedule_gap_count as todo_summary_monitor_schedule_gap_count, + todo_summary_monitor_schedule_gap_items as todo_summary_monitor_schedule_gap_items, + todo_summary_monitor_writeback_contract as todo_summary_monitor_writeback_contract, + todo_summary_monitor_writeback_supported as todo_summary_monitor_writeback_supported, + todo_summary_non_watch_only_monitor_due_items as todo_summary_non_watch_only_monitor_due_items, + todo_summary_open_count as todo_summary_open_count, + todo_summary_open_task_counts as todo_summary_open_task_counts, + todo_summary_watch_only_monitor_due_items as todo_summary_watch_only_monitor_due_items, ) +_FRONTIER_GROUP_KEYS = ( + "current_agent_claimed_items", + "unclaimed_items", + "other_agent_claimed_items", +) +_FRONTIER_COUNT_KEYS = { + "current_agent_claimed_advancement_count", + "unclaimed_advancement_count", + "other_agent_claimed_advancement_count", +} -def todo_blocker_reason(item: dict[str, Any]) -> str | None: - """Project a bounded, public-safe cause for blocked work of any task class.""" - - if ( - todo_item_task_class(item) != TODO_TASK_CLASS_BLOCKER - and normalize_todo_status(item.get("status")) != TODO_STATUS_BLOCKED - ): - return None - return public_safe_compact_text(item.get("reason"), limit=220) - - -def todo_item_is_watch_only_monitor(item: dict[str, Any]) -> bool: - return bool( - todo_item_task_class(item) == TODO_TASK_CLASS_MONITOR - and normalize_todo_watch_only(item.get("watch_only")) is True - ) - - -def todo_priority_parts(text: str) -> tuple[str | None, str]: - match = TODO_PRIORITY_PREFIX_PATTERN.match(text) - if not match: - return None, text - return match.group(1).strip().upper(), match.group(2).strip() - - -def todo_priority_label( - item: dict[str, Any], - *, - text_mode: str = "label", -) -> str | None: - # Read compatibility codec only. Vocabulary/grammar/rank are generated - # from the shared contract; mutations are planned by todos/priority.ts. - # text_mode remains an import/API compatibility argument, not another rule. - if "priority" in item: - value = item["priority"] - else: - value, _ = todo_priority_parts(str(item.get("text") or item.get("title") or "")) - match = TODO_PRIORITY_LABEL_PATTERN.match(value.strip()) if isinstance(value, str) else None - return match.group(1).upper() if match else None - - -def todo_priority_rank(value: Any, *, text_mode: str = "label") -> int: - priority = todo_priority_label(value if isinstance(value, dict) else {"priority": value}, text_mode=text_mode) - return int(_PRIORITY_CONTRACT["values"].index(priority)) if priority else TODO_MISSING_PRIORITY_RANK - - -def todo_index_rank(item: dict[str, Any]) -> int: - raw_index = item.get("index") - try: - return int(raw_index) if raw_index is not None else TODO_MISSING_INDEX - except (TypeError, ValueError): - return TODO_MISSING_INDEX - - -def todo_presentation_metadata(item: dict[str, Any]) -> dict[str, Any]: - """Project one Todo's display address without making it domain state. - - The v0 ``source_section``/``index`` pair is the wire shape's canonical - presentation coordinate. Native domain records derive a section from role - and archival state and intentionally receive no synthetic persisted index. - """ - - if not isinstance(item, dict): - raise ValueError("Todo presentation input must be an object") - schema = item.get("schema_version") - has_section = isinstance(item.get("source_section"), str) and bool( - item["source_section"].strip() - ) - if schema not in {None, TODO_LEGACY_ITEM_SCHEMA, TODO_NATIVE_ITEM_SCHEMA}: - raise ValueError(f"unsupported Todo presentation schema: {schema!r}") - legacy = schema == TODO_LEGACY_ITEM_SCHEMA or (schema is None and has_section) - if legacy: - section = item.get("source_section") if has_section else None - raw_index = item.get("index") - display_order = ( - int(raw_index) - if isinstance(raw_index, int) and not isinstance(raw_index, bool) and raw_index >= 0 - else None - ) - order_source = "source_index" if display_order is not None else "todo_id" - else: - section = None - display_order = None - order_source = "todo_id" - if not section: - section = ( - "Completed Work Archive" - if item.get("archive_state") == "archive" - else "Agent Todo" - if item.get("role") == "agent" - else "User Todo" - ) - return { - "schema_version": TODO_PRESENTATION_METADATA_SCHEMA, - "todo_id": str(item.get("todo_id") or ""), - "display_section": section, - "display_order": display_order, - "order_source": order_source, - } +def _dict_items(raw: object) -> list[TodoObject]: + if not isinstance(raw, list): + return [] + return [cast(TodoObject, item) for item in raw if isinstance(item, dict)] -def todo_presentation_sort_key( - item: dict[str, Any], - *, - text_mode: str = "label", -) -> tuple[int, int, str, str]: - """Sort display rows while preserving source coordinates and native determinism. - Legacy rows with an equal priority/index retain Python's stable input order. - Native rows have no fabricated index, so timestamp and Todo identity provide - a deterministic tie-break that matches the TypeScript presentation adapter. - """ - - priority = todo_priority_rank(item, text_mode=text_mode) - try: - metadata = todo_presentation_metadata(item) - except ValueError: - # Compact display envelopes can carry their own outer schema marker. - # They are not authority records, so ordering may use the untyped - # compatibility fields without weakening the strict boundary helper. - metadata = { - "display_order": ( - int(item["index"]) - if isinstance(item.get("index"), int) - and not isinstance(item.get("index"), bool) - and item["index"] >= 0 - else None - ), +def _encode_frontier_items(items: list[TodoObject] | None) -> list[TodoObject] | None: + if items is None: + return None + return [ + { + "claim": normalize_todo_claimed_by(item.get("claimed_by")), + "excluded": normalize_todo_excluded_agents(item.get("excluded_agents")), + "advancement": todo_item_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT, + "actionable": todo_item_is_actionable_open(item), } - display_order = metadata["display_order"] - if display_order is not None: - return (priority, display_order, "", "") - timestamp = str(item.get("completed_at") or item.get("updated_at") or "") - todo_id = str(item.get("todo_id") or "") - return (priority, TODO_MISSING_INDEX, timestamp, todo_id) - - -def todo_projection_sort_key( - item: dict[str, Any], - *, - text_mode: str = "label", -) -> tuple[int, int]: - return (todo_priority_rank(item, text_mode=text_mode), todo_index_rank(item)) - - - -def todo_item_task_text( - item: Mapping[str, Any], - *, - keys: tuple[str, ...] = ("title", "text"), -) -> str: - return " ".join( - str(item.get(key) or "") for key in keys if str(item.get(key) or "").strip() - ) - - -def todo_item_task_class( - item: Mapping[str, Any], - *, - task_text_keys: tuple[str, ...] = ("title", "text"), -) -> str: - return monitor_todo_task_class( - item, - task_text=todo_item_task_text(item, keys=task_text_keys), - ) - - -def todo_item_is_actionable_open(item: dict[str, Any]) -> bool: - guard = item.get("goal_acceptance_guard") - if isinstance(guard, dict) and guard.get("allowed") is False: - return False - return monitor_todo_is_actionable_open(item) - - -def todo_item_is_deferred(item: dict[str, Any]) -> bool: - return (normalize_todo_status(item.get("status")) or "") == TODO_STATUS_DEFERRED - - -def todo_item_next_due_at(item: dict[str, Any]) -> datetime | None: - return monitor_todo_next_due_at(item) - - -def todo_item_expires_at(item: dict[str, Any]) -> datetime | None: - return monitor_todo_expires_at(item) - - -def todo_item_is_expired_monitor( - item: dict[str, Any], *, now: datetime | None = None -) -> bool: - return monitor_todo_is_expired(item, now=now) - - -def todo_item_is_due_monitor( - item: dict[str, Any], - *, - now: datetime | None = None, - task_text_keys: tuple[str, ...] = ("title", "text"), -) -> bool: - return monitor_todo_is_due( - item, - now=now, - task_text=todo_item_task_text(item, keys=task_text_keys), - ) - - -def todo_item_missing_monitor_schedule( - item: dict[str, Any], - *, - now: datetime | None = None, - task_text_keys: tuple[str, ...] = ("title", "text"), -) -> bool: - return monitor_todo_missing_schedule( - item, - now=now, - task_text=todo_item_task_text(item, keys=task_text_keys), - ) + for item in items + ] -def todo_item_claimed_by_agent_or_unclaimed( - item: dict[str, Any], +def _advancement_frontier_projection( + summary: TodoMapping, *, agent_id: str | None, -) -> bool: - if todo_item_has_removed_continuation_policy(item): - return False - normalized_agent_id = normalize_todo_claimed_by(agent_id) - if not normalized_agent_id: - return True - if normalized_agent_id in normalize_todo_excluded_agents( - item.get("excluded_agents") - ): - return False - claimed_by = normalize_todo_claimed_by(item.get("claimed_by")) - return not claimed_by or claimed_by == normalized_agent_id - - -def _advancement_frontier_projection( - summary: dict[str, Any], *, agent_id: str | None, -) -> tuple[dict[str, list[dict[str, Any]]], dict[str, int]]: +) -> tuple[dict[str, list[TodoObject]], dict[str, int]]: """Legacy fact codec; TS owns precedence, claim lanes and count floors.""" from ..effect_runtime import effect_runtime_result - keys = ("executable_backlog_items", "unclaimed_priority_open_items", - "claimed_advancement_open_items") - sources = { - key: [item for item in summary.get(key, []) if isinstance(item, dict)] - if isinstance(summary.get(key), list) else None for key in keys + keys = ( + "executable_backlog_items", + "unclaimed_priority_open_items", + "claimed_advancement_open_items", + ) + sources: dict[str, list[TodoObject] | None] = { + key: _dict_items(raw) if isinstance(raw := summary.get(key), list) else None + for key in keys } claim_scope = summary.get("claim_scope") - diagnostic = claim_scope.get("other_agent_claimed_items") if isinstance(claim_scope, dict) else None - - def encode(items: list[dict[str, Any]] | None) -> list[dict[str, Any]] | None: - return [{"claim": normalize_todo_claimed_by(item.get("claimed_by")), - "excluded": normalize_todo_excluded_agents(item.get("excluded_agents")), - "advancement": todo_item_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT, - "actionable": todo_item_is_actionable_open(item)} for item in items] if items is not None else None - - result = effect_runtime_result("todo.frontier_revision.project", { - "schema_version": "todo_frontier_revision_request_v0", "operation": "classify", - "agent_id": normalize_todo_claimed_by(agent_id), - "sources": {key: encode(items) for key, items in sources.items()}, - "diagnostic_peers": encode([item for item in diagnostic if isinstance(item, dict)]) - if isinstance(diagnostic, list) else None, - "claimed_count_floor": str(_positive_int(summary.get("current_agent_claimed_advancement_count"))), - }) - if not isinstance(result, dict) or not isinstance(result.get("groups"), dict) or not isinstance(result.get("counts"), dict): + diagnostic = ( + claim_scope.get("other_agent_claimed_items") + if isinstance(claim_scope, Mapping) + else None + ) + result = effect_runtime_result( + "todo.frontier_revision.project", + { + "schema_version": "todo_frontier_revision_request_v0", + "operation": "classify", + "agent_id": normalize_todo_claimed_by(agent_id), + "sources": { + key: _encode_frontier_items(items) for key, items in sources.items() + }, + "diagnostic_peers": _encode_frontier_items(_dict_items(diagnostic)) + if isinstance(diagnostic, list) + else None, + "claimed_count_floor": str( + _positive_int(summary.get("current_agent_claimed_advancement_count")) + ), + }, + ) + if ( + not isinstance(result, Mapping) + or not isinstance(result.get("groups"), Mapping) + or not isinstance(result.get("counts"), Mapping) + ): raise TypeError("invalid typed advancement frontier projection") - groups: dict[str, list[dict[str, Any]]] = {} - for key in ("current_agent_claimed_items", "unclaimed_items", "other_agent_claimed_items"): - group = result["groups"].get(key) - if not isinstance(group, dict) or group.get("source") not in sources or not isinstance(group.get("indices"), list): + raw_groups = cast(Mapping[str, object], result["groups"]) + groups: dict[str, list[TodoObject]] = {} + for key in _FRONTIER_GROUP_KEYS: + group = raw_groups.get(key) + if not isinstance(group, Mapping): raise TypeError("invalid typed advancement frontier source") - source = sources[group["source"]] or [] - indices = group["indices"] - if any(type(index) is not int or index < 0 or index >= len(source) for index in indices): + source_name = group.get("source") + indices = group.get("indices") + if ( + not isinstance(source_name, str) + or source_name not in sources + or not isinstance(indices, list) + ): + raise TypeError("invalid typed advancement frontier source") + source = sources[source_name] or [] + if any( + type(index) is not int or index < 0 or index >= len(source) + for index in indices + ): raise TypeError("invalid typed advancement frontier index") groups[key] = [source[index] for index in indices] - counts = result["counts"] + raw_counts = dict(cast(Mapping[str, object], result["counts"])) current_key = "current_agent_claimed_advancement_count" - encoded_count = counts.get(current_key) + encoded_count = raw_counts.get(current_key) if isinstance(encoded_count, str) and re.fullmatch(r"0|[1-9][0-9]*", encoded_count): - counts[current_key] = int(encoded_count) - if set(counts) != {"current_agent_claimed_advancement_count", "unclaimed_advancement_count", "other_agent_claimed_advancement_count"} or any(type(count) is not int or count < 0 for count in counts.values()): + raw_counts[current_key] = int(encoded_count) + if set(raw_counts) != _FRONTIER_COUNT_KEYS or any( + type(count) is not int or count < 0 for count in raw_counts.values() + ): raise TypeError("invalid typed advancement frontier counts") - return groups, counts + return groups, {key: cast(int, value) for key, value in raw_counts.items()} def todo_advancement_frontier_items( - summary: dict[str, Any] | None, *, agent_id: str | None, -) -> dict[str, list[dict[str, Any]]]: + summary: TodoMapping | None, + *, + agent_id: str | None, +) -> dict[str, list[TodoObject]]: """Read the typed frontier, retaining the caller's original display rows.""" - if not isinstance(summary, dict): - return {"current_agent_claimed_items": [], "unclaimed_items": [], "other_agent_claimed_items": []} + if not isinstance(summary, Mapping): + return {key: [] for key in _FRONTIER_GROUP_KEYS} return _advancement_frontier_projection(summary, agent_id=agent_id)[0] def agent_scoped_selectable_advancement_todo_ids( - agent_todo_summary: dict[str, Any] | None, *, agent_id: str | None, + agent_todo_summary: TodoMapping | None, + *, + agent_id: str | None, ) -> set[str]: frontier = todo_advancement_frontier_items(agent_todo_summary, agent_id=agent_id) - return {todo_id for item in frontier["current_agent_claimed_items"] + frontier["unclaimed_items"] - if (todo_id := normalize_todo_id(item.get("todo_id")))} + return { + todo_id + for item in ( + frontier["current_agent_claimed_items"] + frontier["unclaimed_items"] + ) + if (todo_id := normalize_todo_id(item.get("todo_id"))) + } def todo_scoped_runnable_advancement_count( - summary: dict[str, Any] | None, *, agent_id: str | None, + summary: TodoMapping | None, + *, + agent_id: str | None, ) -> int | None: """Decode the typed selection count; unknown sources keep legacy fences. Commitment floors intentionally include work held by receipt-owned waits. They do not override a complete same-lane runnable-work projection. """ - counts = (summary or {}).get("work_counts") + counts = summary.get("work_counts") if isinstance(summary, Mapping) else None if ( - isinstance(counts, dict) + isinstance(counts, Mapping) and counts.get("schema_version") == "todo_work_counts_v0" and counts.get("complete") is True and counts.get("agent_id") == agent_id and type(counts.get("advancement")) is int - and counts["advancement"] >= 0 + and cast(int, counts["advancement"]) >= 0 ): - return cast(int | None, counts["advancement"]) + return cast(int, counts["advancement"]) return None def todo_advancement_frontier_counts( - summary: dict[str, Any] | None, *, agent_id: str | None, + summary: TodoMapping | None, + *, + agent_id: str | None, ) -> dict[str, int]: """Read commitment counts; diagnostic floors do not grant execution.""" - if not isinstance(summary, dict): - return {"current_agent_claimed_advancement_count": 0, - "unclaimed_advancement_count": 0, "other_agent_claimed_advancement_count": 0} + if not isinstance(summary, Mapping): + return {key: 0 for key in _FRONTIER_COUNT_KEYS} return _advancement_frontier_projection(summary, agent_id=agent_id)[1] - - -def todo_item_has_removed_continuation_policy(item: dict[str, Any]) -> bool: - return bool( - normalize_removed_todo_continuation_policy( - item.get("removed_continuation_policy") - ) - ) - - -def todo_item_excludes_agent( - item: dict[str, Any], - *, - agent_id: str | None, -) -> bool: - normalized_agent_id = normalize_todo_claimed_by(agent_id) - return bool( - normalized_agent_id - and normalized_agent_id - in normalize_todo_excluded_agents(item.get("excluded_agents")) - ) - - -def todo_summary_claim_scope_agent_id(summary: dict[str, Any] | None) -> str | None: - if not isinstance(summary, dict): - return None - claim_scope = summary.get("claim_scope") - if not isinstance(claim_scope, dict): - return None - return normalize_todo_claimed_by(claim_scope.get("agent_id")) - - -def todo_summary_monitor_writeback_contract( - summary: dict[str, Any] | None, -) -> dict[str, Any] | None: - if not isinstance(summary, dict): - return None - contract = summary.get("monitor_writeback") - if not isinstance(contract, dict): - return None - if contract.get("supported") is not False: - return None - compact: dict[str, Any] = {"supported": False} - source = str(contract.get("source") or "").strip() - if source: - compact["source"] = source - return compact - - -def todo_summary_monitor_writeback_supported(summary: dict[str, Any] | None) -> bool: - contract = todo_summary_monitor_writeback_contract(summary) - if not contract: - return True - return contract.get("supported") is not False - - -def todo_summary_monitor_items(summary: dict[str, Any] | None) -> list[dict[str, Any]]: - if not isinstance(summary, dict): - return [] - items: list[dict[str, Any]] = [] - seen: set[tuple[str, int]] = set() - for key in ( - "monitor_due_items", - "current_agent_claimed_monitor_items", - "monitor_open_items", - "claimed_monitor_open_items", - "first_open_items", - ): - values = summary.get(key) - if not isinstance(values, list): - continue - for value in values: - if not isinstance(value, dict): - continue - if not todo_item_is_actionable_open(value): - continue - if todo_item_task_class(value) != TODO_TASK_CLASS_MONITOR: - continue - identity = (normalize_todo_id(value.get("todo_id")) or "", id(value)) - if identity in seen: - continue - seen.add(identity) - items.append(value) - return items - - -def _summary_monitor_items( - summary: dict[str, Any] | None, - *, - projected_key: str, - predicate: Any, - task_text_keys: tuple[str, ...], - text_mode: str, -) -> list[dict[str, Any]]: - if not isinstance(summary, dict): - return [] - if not todo_summary_monitor_writeback_supported(summary): - return [] - projected_items = summary.get(projected_key) - if isinstance(projected_items, list): - items = [ - item - for item in projected_items - if isinstance(item, dict) - if todo_item_is_actionable_open(item) - if todo_item_task_class(item, task_text_keys=task_text_keys) - == TODO_TASK_CLASS_MONITOR - if predicate(item) - ] - else: - raw_items = summary.get("monitor_open_items") - items = [ - item - for item in (raw_items if isinstance(raw_items, list) else []) - if isinstance(item, dict) - if predicate(item) - ] - agent_id = todo_summary_claim_scope_agent_id(summary) - if agent_id: - items = [ - item - for item in items - if todo_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id) - ] - return sorted( - items, - key=lambda item: todo_projection_sort_key(item, text_mode=text_mode), - ) - - -def todo_summary_monitor_due_items( - summary: dict[str, Any] | None, - *, - task_text_keys: tuple[str, ...] = ("title", "text"), - text_mode: str = "label", -) -> list[dict[str, Any]]: - return _summary_monitor_items( - summary, - projected_key="monitor_due_items", - predicate=lambda item: todo_item_is_due_monitor( - item, - task_text_keys=task_text_keys, - ), - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - - -def todo_summary_watch_only_monitor_due_items( - summary: dict[str, Any] | None, - *, - task_text_keys: tuple[str, ...] = ("title", "text"), - text_mode: str = "label", -) -> list[dict[str, Any]]: - """Consume the typed watch-only partition; legacy summaries fall back safely.""" - - if isinstance(summary, dict) and isinstance( - summary.get("watch_only_monitor_due_items"), list - ): - return _summary_monitor_items( - summary, - projected_key="watch_only_monitor_due_items", - predicate=lambda _item: True, - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - return [ - item - for item in todo_summary_monitor_due_items( - summary, - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - if todo_item_is_watch_only_monitor(item) - ] - - -def todo_summary_non_watch_only_monitor_due_items( - summary: dict[str, Any] | None, - *, - task_text_keys: tuple[str, ...] = ("title", "text"), - text_mode: str = "label", -) -> list[dict[str, Any]]: - """Consume the typed ordinary-due partition; classify only legacy summaries.""" - - if isinstance(summary, dict) and isinstance( - summary.get("non_watch_only_monitor_due_items"), list - ): - return _summary_monitor_items( - summary, - projected_key="non_watch_only_monitor_due_items", - predicate=lambda _item: True, - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - return [ - item - for item in todo_summary_monitor_due_items( - summary, - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - if not todo_item_is_watch_only_monitor(item) - ] - - -def todo_summary_monitor_due_count( - summary: dict[str, Any] | None, - *, - due_items: list[dict[str, Any]] | None = None, - task_text_keys: tuple[str, ...] = ("title", "text"), - text_mode: str = "label", -) -> int: - if not isinstance(summary, dict): - return 0 - if not todo_summary_monitor_writeback_supported(summary): - return 0 - projected_count = summary.get("monitor_due_count") - if isinstance(projected_count, int): - return max(0, projected_count) - agent_id = todo_summary_claim_scope_agent_id(summary) - if agent_id: - raw_items = summary.get("monitor_open_items") - if isinstance(raw_items, list): - return len( - [ - item - for item in raw_items - if isinstance(item, dict) - if todo_item_is_due_monitor(item, task_text_keys=task_text_keys) - if todo_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id) - ] - ) - return len( - due_items - if due_items is not None - else todo_summary_monitor_due_items( - summary, - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - ) - return len( - due_items - if due_items is not None - else todo_summary_monitor_due_items( - summary, - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - ) - - -def todo_summary_monitor_schedule_gap_items( - summary: dict[str, Any] | None, - *, - task_text_keys: tuple[str, ...] = ("title", "text"), - text_mode: str = "label", -) -> list[dict[str, Any]]: - return _summary_monitor_items( - summary, - projected_key="monitor_schedule_gap_items", - predicate=lambda item: todo_item_missing_monitor_schedule( - item, - task_text_keys=task_text_keys, - ), - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - - -def todo_summary_monitor_schedule_gap_count( - summary: dict[str, Any] | None, - *, - gap_items: list[dict[str, Any]] | None = None, - task_text_keys: tuple[str, ...] = ("title", "text"), - text_mode: str = "label", -) -> int: - if not isinstance(summary, dict): - return 0 - if not todo_summary_monitor_writeback_supported(summary): - return 0 - agent_id = todo_summary_claim_scope_agent_id(summary) - if agent_id: - raw_items = summary.get("monitor_open_items") - if isinstance(raw_items, list): - return len( - [ - item - for item in raw_items - if isinstance(item, dict) - if todo_item_missing_monitor_schedule( - item, - task_text_keys=task_text_keys, - ) - if todo_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id) - ] - ) - return len( - gap_items - if gap_items is not None - else todo_summary_monitor_schedule_gap_items( - summary, - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - ) - projected_count = summary.get("monitor_schedule_gap_count") - if isinstance(projected_count, int): - return max(0, projected_count) - return len( - gap_items - if gap_items is not None - else todo_summary_monitor_schedule_gap_items( - summary, - task_text_keys=task_text_keys, - text_mode=text_mode, - ) - ) - - -def todo_summary_open_count(summary: dict[str, Any] | None) -> int: - if not isinstance(summary, dict): - return 0 - try: - return max(0, int(summary.get("open_count") or 0)) - except (TypeError, ValueError): - return 0 - - -def todo_summary_open_task_counts(summary: dict[str, Any] | None) -> dict[str, Any]: - """Consume pre-limit counts; old display-only summaries provide lower bounds.""" - from ..effect_runtime import effect_runtime_result - - summary = summary if isinstance(summary, dict) else {} - counts = summary.get("work_counts") - if counts is None: - rows = [] - for key in ("items", "executable_backlog_items", "first_executable_items", "first_open_items", "monitor_open_items"): - for item in summary.get(key) or []: - if not isinstance(item, dict) or item.get("done") is True: - continue - text = str(item.get("text") or "").strip() - if not text: - continue - rows.append({"identity": str(item.get("todo_id") or (str(item.get("index")) + ":" + text)), - "actionable": todo_item_is_actionable_open(item), "task_class": todo_item_task_class(item)}) - counts = effect_runtime_result("todo.work_counts.project", { - "schema_version": "todo_work_counts_request_v0", "rows": rows, - "source_open_count": summary.get("open_count"), - "agent_id": todo_summary_claim_scope_agent_id(summary), - }) - if (not isinstance(counts, dict) or counts.get("schema_version") != "todo_work_counts_v0" - or not isinstance(counts.get("complete"), bool) - or any(type(counts.get(key)) is not int or counts[key] < 0 - for key in ("open", "advancement", "monitor", "hidden")) - or counts.get("agent_id") != todo_summary_claim_scope_agent_id(summary)): - raise ValueError("invalid or differently scoped Todo work counts") - if (counts["hidden"] > counts["open"] - or counts["advancement"] + counts["monitor"] > counts["open"] - counts["hidden"] - or (counts["complete"] and counts["hidden"] != 0)): - raise ValueError("inconsistent Todo work count envelope") - return {key: counts[key] for key in ("open", "advancement", "monitor", "hidden", "complete")} | { - "monitor_due": todo_summary_monitor_due_count(summary), - "monitor_schedule_gap": todo_summary_monitor_schedule_gap_count(summary), - } - - -def todo_summary_has_only_future_scoped_monitor_work( - summary: dict[str, Any] | None, -) -> bool: - """Return true when the scoped agent has only non-due monitor work left.""" - - agent_id = todo_summary_claim_scope_agent_id(summary) - if not agent_id or not isinstance(summary, dict): - return False - if not todo_summary_monitor_items(summary): - return False - counts = todo_summary_open_task_counts(summary) - if counts["complete"] is not True or counts["advancement"] > 0: - return False - if todo_summary_monitor_due_count(summary) > 0: - return False - if todo_summary_monitor_schedule_gap_count(summary) > 0: - return False - if _positive_int(summary.get("current_agent_claimed_advancement_count")) > 0: - return False - - for key in ( - "current_agent_claimed_advancement_items", - "unclaimed_priority_open_items", - "first_executable_items", - "executable_backlog_items", - ): - values = summary.get(key) - if not isinstance(values, list): - continue - for item in values: - if not isinstance(item, dict): - continue - if not todo_item_is_actionable_open(item): - continue - if todo_item_task_class(item) != TODO_TASK_CLASS_ADVANCEMENT: - continue - if todo_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id): - return False - return True - - -def _positive_int(value: Any) -> int: - try: - parsed = int(value) - except (TypeError, ValueError): - return 0 - return max(0, parsed) - - -def todo_summary_first_executable_item( - summary: dict[str, Any] | None, -) -> dict[str, Any] | None: - if not isinstance(summary, dict): - return None - raw_items = summary.get("first_executable_items") - items = raw_items if isinstance(raw_items, list) else [] - for item in items: - if not isinstance(item, dict): - continue - if not todo_item_is_actionable_open(item): - continue - if todo_item_task_class(item) != TODO_TASK_CLASS_ADVANCEMENT: - continue - return item - return None diff --git a/loopx/control_plane/todos/todo_summary_semantics.py b/loopx/control_plane/todos/todo_summary_semantics.py new file mode 100644 index 0000000000..723e06115f --- /dev/null +++ b/loopx/control_plane/todos/todo_summary_semantics.py @@ -0,0 +1,501 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from typing import cast + +from .contract import ( + TODO_TASK_CLASS_ADVANCEMENT, + TODO_TASK_CLASS_MONITOR, + normalize_todo_claimed_by, + normalize_todo_id, +) +from .todo_item_semantics import ( + TodoMapping, + TodoObject, + positive_int, + todo_item_allows_normalized_agent, + todo_item_is_actionable_open, + todo_item_is_due_monitor, + todo_item_is_watch_only_monitor, + todo_item_missing_monitor_schedule, + todo_item_task_class, + todo_projection_sort_key, +) + +_WORK_COUNT_CORE_KEYS = ("open", "advancement", "monitor", "hidden") +_MONITOR_SUMMARY_SOURCE_KEYS = ( + "monitor_due_items", + "current_agent_claimed_monitor_items", + "monitor_open_items", + "claimed_monitor_open_items", + "first_open_items", +) +_ADVANCEMENT_CONFLICT_KEYS = ( + "current_agent_claimed_advancement_items", + "unclaimed_priority_open_items", + "first_executable_items", + "executable_backlog_items", +) + + +def todo_summary_claim_scope_agent_id(summary: TodoMapping | None) -> str | None: + if not isinstance(summary, Mapping): + return None + claim_scope = summary.get("claim_scope") + if not isinstance(claim_scope, Mapping): + return None + return normalize_todo_claimed_by(claim_scope.get("agent_id")) + + +def todo_summary_monitor_writeback_contract( + summary: TodoMapping | None, +) -> TodoObject | None: + if not isinstance(summary, Mapping): + return None + contract = summary.get("monitor_writeback") + if not isinstance(contract, Mapping): + return None + if contract.get("supported") is not False: + return None + compact: TodoObject = {"supported": False} + source = str(contract.get("source") or "").strip() + if source: + compact["source"] = source + return compact + + +def todo_summary_monitor_writeback_supported(summary: TodoMapping | None) -> bool: + contract = todo_summary_monitor_writeback_contract(summary) + if not contract: + return True + return contract.get("supported") is not False + + +def todo_summary_monitor_items(summary: TodoMapping | None) -> list[TodoObject]: + if not isinstance(summary, Mapping): + return [] + items: list[TodoObject] = [] + seen: set[tuple[str, int]] = set() + for key in _MONITOR_SUMMARY_SOURCE_KEYS: + values = summary.get(key) + if not isinstance(values, list): + continue + for value in values: + if not isinstance(value, dict): + continue + typed_value = cast(TodoObject, value) + if not todo_item_is_actionable_open(typed_value): + continue + if todo_item_task_class(typed_value) != TODO_TASK_CLASS_MONITOR: + continue + identity = ( + normalize_todo_id(typed_value.get("todo_id")) or "", + id(value), + ) + if identity in seen: + continue + seen.add(identity) + items.append(typed_value) + return items + + +def _summary_has_monitor_item(summary: TodoMapping | None) -> bool: + if not isinstance(summary, Mapping): + return False + for key in _MONITOR_SUMMARY_SOURCE_KEYS: + values = summary.get(key) + if not isinstance(values, list): + continue + for value in values: + if not isinstance(value, dict): + continue + typed_value = cast(TodoObject, value) + if ( + todo_item_is_actionable_open(typed_value) + and todo_item_task_class(typed_value) == TODO_TASK_CLASS_MONITOR + ): + return True + return False + + +def _summary_monitor_items( + summary: TodoMapping | None, + *, + projected_key: str, + predicate: Callable[[TodoObject], bool], + task_text_keys: tuple[str, ...], + text_mode: str, + sort_items: bool = True, +) -> list[TodoObject]: + if not isinstance(summary, Mapping): + return [] + if not todo_summary_monitor_writeback_supported(summary): + return [] + agent_id = todo_summary_claim_scope_agent_id(summary) + projected_items = summary.get(projected_key) + items: list[TodoObject] = [] + if isinstance(projected_items, list): + for raw in projected_items: + if not isinstance(raw, dict): + continue + item = cast(TodoObject, raw) + if agent_id and not todo_item_allows_normalized_agent( + item, normalized_agent_id=agent_id + ): + continue + if ( + todo_item_is_actionable_open(item) + and todo_item_task_class(item, task_text_keys=task_text_keys) + == TODO_TASK_CLASS_MONITOR + and predicate(item) + ): + items.append(item) + else: + raw_items = summary.get("monitor_open_items") + if isinstance(raw_items, list): + for raw in raw_items: + if not isinstance(raw, dict): + continue + item = cast(TodoObject, raw) + if agent_id and not todo_item_allows_normalized_agent( + item, normalized_agent_id=agent_id + ): + continue + if predicate(item): + items.append(item) + if not sort_items: + return items + return sorted( + items, + key=lambda item: todo_projection_sort_key(item, text_mode=text_mode), + ) + + +def todo_summary_monitor_due_items( + summary: TodoMapping | None, + *, + task_text_keys: tuple[str, ...] = ("title", "text"), + text_mode: str = "label", +) -> list[TodoObject]: + return _summary_monitor_items( + summary, + projected_key="monitor_due_items", + predicate=lambda item: todo_item_is_due_monitor( + item, + task_text_keys=task_text_keys, + ), + task_text_keys=task_text_keys, + text_mode=text_mode, + ) + + +def _summary_partitioned_due_monitor_items( + summary: TodoMapping | None, + *, + projected_key: str, + expect_watch_only: bool, + task_text_keys: tuple[str, ...], + text_mode: str, +) -> list[TodoObject]: + if isinstance(summary, Mapping) and isinstance(summary.get(projected_key), list): + return _summary_monitor_items( + summary, + projected_key=projected_key, + predicate=lambda _item: True, + task_text_keys=task_text_keys, + text_mode=text_mode, + ) + return [ + item + for item in todo_summary_monitor_due_items( + summary, + task_text_keys=task_text_keys, + text_mode=text_mode, + ) + if todo_item_is_watch_only_monitor(item) is expect_watch_only + ] + + +def todo_summary_watch_only_monitor_due_items( + summary: TodoMapping | None, + *, + task_text_keys: tuple[str, ...] = ("title", "text"), + text_mode: str = "label", +) -> list[TodoObject]: + """Consume the typed watch-only partition; legacy summaries fall back safely.""" + return _summary_partitioned_due_monitor_items( + summary, + projected_key="watch_only_monitor_due_items", + expect_watch_only=True, + task_text_keys=task_text_keys, + text_mode=text_mode, + ) + + +def todo_summary_non_watch_only_monitor_due_items( + summary: TodoMapping | None, + *, + task_text_keys: tuple[str, ...] = ("title", "text"), + text_mode: str = "label", +) -> list[TodoObject]: + """Consume the typed ordinary-due partition; classify only legacy summaries.""" + return _summary_partitioned_due_monitor_items( + summary, + projected_key="non_watch_only_monitor_due_items", + expect_watch_only=False, + task_text_keys=task_text_keys, + text_mode=text_mode, + ) + + +def _count_scoped_raw_monitor_items( + raw_items: list[object], + *, + agent_id: str, + predicate: Callable[[TodoObject], bool], +) -> int: + total = 0 + for raw in raw_items: + if not isinstance(raw, dict): + continue + item = cast(TodoObject, raw) + if predicate(item) and todo_item_allows_normalized_agent( + item, normalized_agent_id=agent_id + ): + total += 1 + return total + + +def todo_summary_monitor_due_count( + summary: TodoMapping | None, + *, + due_items: list[TodoObject] | None = None, + task_text_keys: tuple[str, ...] = ("title", "text"), + text_mode: str = "label", +) -> int: + if not isinstance(summary, Mapping): + return 0 + if not todo_summary_monitor_writeback_supported(summary): + return 0 + projected_count = summary.get("monitor_due_count") + if isinstance(projected_count, int): + return max(0, projected_count) + agent_id = todo_summary_claim_scope_agent_id(summary) + if agent_id and isinstance(raw_items := summary.get("monitor_open_items"), list): + return _count_scoped_raw_monitor_items( + raw_items, + agent_id=agent_id, + predicate=lambda item: todo_item_is_due_monitor( + item, task_text_keys=task_text_keys + ), + ) + if due_items is not None: + return len(due_items) + return len( + _summary_monitor_items( + summary, + projected_key="monitor_due_items", + predicate=lambda item: todo_item_is_due_monitor( + item, task_text_keys=task_text_keys + ), + task_text_keys=task_text_keys, + text_mode=text_mode, + sort_items=False, + ) + ) + + +def todo_summary_monitor_schedule_gap_items( + summary: TodoMapping | None, + *, + task_text_keys: tuple[str, ...] = ("title", "text"), + text_mode: str = "label", +) -> list[TodoObject]: + return _summary_monitor_items( + summary, + projected_key="monitor_schedule_gap_items", + predicate=lambda item: todo_item_missing_monitor_schedule( + item, + task_text_keys=task_text_keys, + ), + task_text_keys=task_text_keys, + text_mode=text_mode, + ) + + +def todo_summary_monitor_schedule_gap_count( + summary: TodoMapping | None, + *, + gap_items: list[TodoObject] | None = None, + task_text_keys: tuple[str, ...] = ("title", "text"), + text_mode: str = "label", +) -> int: + if not isinstance(summary, Mapping): + return 0 + if not todo_summary_monitor_writeback_supported(summary): + return 0 + agent_id = todo_summary_claim_scope_agent_id(summary) + if agent_id: + raw_items = summary.get("monitor_open_items") + if isinstance(raw_items, list): + return _count_scoped_raw_monitor_items( + raw_items, + agent_id=agent_id, + predicate=lambda item: todo_item_missing_monitor_schedule( + item, task_text_keys=task_text_keys + ), + ) + else: + projected_count = summary.get("monitor_schedule_gap_count") + if isinstance(projected_count, int): + return max(0, projected_count) + if gap_items is not None: + return len(gap_items) + return len( + _summary_monitor_items( + summary, + projected_key="monitor_schedule_gap_items", + predicate=lambda item: todo_item_missing_monitor_schedule( + item, task_text_keys=task_text_keys + ), + task_text_keys=task_text_keys, + text_mode=text_mode, + sort_items=False, + ) + ) + + +def todo_summary_open_count(summary: TodoMapping | None) -> int: + if not isinstance(summary, Mapping): + return 0 + return positive_int(summary.get("open_count") or 0) + + +def todo_summary_open_task_counts(summary: TodoMapping | None) -> dict[str, int]: + """Consume pre-limit counts; old display-only summaries provide lower bounds.""" + from ..effect_runtime import effect_runtime_result + + resolved_summary: TodoMapping = summary if isinstance(summary, Mapping) else {} + scoped_agent_id = todo_summary_claim_scope_agent_id(resolved_summary) + counts = resolved_summary.get("work_counts") + if counts is None: + rows: list[TodoObject] = [] + for key in ( + "items", + "executable_backlog_items", + "first_executable_items", + "first_open_items", + "monitor_open_items", + ): + for raw in cast(list[object], resolved_summary.get(key) or []): + if not isinstance(raw, dict) or raw.get("done") is True: + continue + item = cast(TodoObject, raw) + text = str(item.get("text") or "").strip() + if not text: + continue + rows.append( + { + "identity": str( + item.get("todo_id") or (str(item.get("index")) + ":" + text) + ), + "actionable": todo_item_is_actionable_open(item), + "task_class": todo_item_task_class(item), + } + ) + counts = effect_runtime_result( + "todo.work_counts.project", + { + "schema_version": "todo_work_counts_request_v0", + "rows": rows, + "source_open_count": resolved_summary.get("open_count"), + "agent_id": scoped_agent_id, + }, + ) + if ( + not isinstance(counts, Mapping) + or counts.get("schema_version") != "todo_work_counts_v0" + or not isinstance(counts.get("complete"), bool) + or any( + type(counts.get(key)) is not int or cast(int, counts[key]) < 0 + for key in _WORK_COUNT_CORE_KEYS + ) + or counts.get("agent_id") != scoped_agent_id + ): + raise ValueError("invalid or differently scoped Todo work counts") + open_count = cast(int, counts["open"]) + advancement_count = cast(int, counts["advancement"]) + monitor_count = cast(int, counts["monitor"]) + hidden_count = cast(int, counts["hidden"]) + complete = cast(bool, counts["complete"]) + if ( + hidden_count > open_count + or advancement_count + monitor_count > open_count - hidden_count + or (complete and hidden_count != 0) + ): + raise ValueError("inconsistent Todo work count envelope") + return { + "open": open_count, + "advancement": advancement_count, + "monitor": monitor_count, + "hidden": hidden_count, + "complete": complete, + "monitor_due": todo_summary_monitor_due_count(resolved_summary), + "monitor_schedule_gap": todo_summary_monitor_schedule_gap_count(resolved_summary), + } + + +def todo_summary_has_only_future_scoped_monitor_work( + summary: TodoMapping | None, +) -> bool: + """Return true when the scoped agent has only non-due monitor work left.""" + + agent_id = todo_summary_claim_scope_agent_id(summary) + if not agent_id or not isinstance(summary, Mapping): + return False + if not _summary_has_monitor_item(summary): + return False + counts = todo_summary_open_task_counts(summary) + if counts["complete"] is not True or counts["advancement"] > 0: + return False + if counts["monitor_due"] > 0 or counts["monitor_schedule_gap"] > 0: + return False + if positive_int(summary.get("current_agent_claimed_advancement_count")) > 0: + return False + for key in _ADVANCEMENT_CONFLICT_KEYS: + values = summary.get(key) + if not isinstance(values, list): + continue + for raw in values: + if not isinstance(raw, dict): + continue + item = cast(TodoObject, raw) + if ( + todo_item_is_actionable_open(item) + and todo_item_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT + and todo_item_allows_normalized_agent( + item, normalized_agent_id=agent_id + ) + ): + return False + return True + + +def todo_summary_first_executable_item( + summary: TodoMapping | None, +) -> TodoObject | None: + if not isinstance(summary, Mapping): + return None + raw_items = summary.get("first_executable_items") + if not isinstance(raw_items, list): + return None + for raw in raw_items: + if not isinstance(raw, dict): + continue + item = cast(TodoObject, raw) + if ( + todo_item_is_actionable_open(item) + and todo_item_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT + ): + return item + return None diff --git a/tests/control_plane/test_todo_semantics_contract.py b/tests/control_plane/test_todo_semantics_contract.py new file mode 100644 index 0000000000..5ee0ace0d0 --- /dev/null +++ b/tests/control_plane/test_todo_semantics_contract.py @@ -0,0 +1,508 @@ +from __future__ import annotations + +import ast +from pathlib import Path +import subprocess +import sys +from types import MappingProxyType +from typing import cast + +import pytest + +from loopx.control_plane.todos import todo_item_semantics, todo_semantics, todo_summary_semantics +from loopx.control_plane.todos.todo_semantics import ( + TODO_LEGACY_ITEM_SCHEMA, + TODO_MISSING_INDEX, + TODO_MISSING_PRIORITY_RANK, + TODO_NATIVE_ITEM_SCHEMA, + TODO_PRESENTATION_METADATA_SCHEMA, + TODO_STATUS_BLOCKED, + TODO_STATUS_DEFERRED, + TODO_TASK_CLASS_ADVANCEMENT, + TODO_TASK_CLASS_BLOCKER, + TODO_TASK_CLASS_MONITOR, + agent_scoped_selectable_advancement_todo_ids, + todo_advancement_frontier_counts, + todo_advancement_frontier_items, + todo_blocker_reason, + todo_index_rank, + todo_item_claimed_by_agent_or_unclaimed, + todo_item_excludes_agent, + todo_item_expires_at, + todo_item_has_removed_continuation_policy, + todo_item_is_actionable_open, + todo_item_is_deferred, + todo_item_is_due_monitor, + todo_item_is_expired_monitor, + todo_item_is_watch_only_monitor, + todo_item_missing_monitor_schedule, + todo_item_next_due_at, + todo_item_task_class, + todo_item_task_text, + todo_presentation_metadata, + todo_presentation_sort_key, + todo_priority_label, + todo_priority_parts, + todo_priority_rank, + todo_projection_sort_key, + todo_scoped_runnable_advancement_count, + todo_summary_claim_scope_agent_id, + todo_summary_first_executable_item, + todo_summary_has_only_future_scoped_monitor_work, + todo_summary_monitor_due_count, + todo_summary_monitor_due_items, + todo_summary_monitor_items, + todo_summary_monitor_schedule_gap_count, + todo_summary_monitor_schedule_gap_items, + todo_summary_monitor_writeback_contract, + todo_summary_monitor_writeback_supported, + todo_summary_non_watch_only_monitor_due_items, + todo_summary_open_count, + todo_summary_open_task_counts, + todo_summary_watch_only_monitor_due_items, +) + +REPO_ROOT = Path(__file__).resolve().parents[2] +_IGNORE_MARKER = "type" + ": ignore" +_PINNED_EXPORTS = ( + "TODO_MISSING_PRIORITY_RANK", + "TODO_MISSING_INDEX", + "TODO_PRIORITY_PREFIX_PATTERN", + "TODO_PRIORITY_LABEL_PATTERN", + "TODO_PRESENTATION_METADATA_SCHEMA", + "TODO_LEGACY_ITEM_SCHEMA", + "TODO_NATIVE_ITEM_SCHEMA", + "TODO_STATUS_BLOCKED", + "TODO_STATUS_DEFERRED", + "TODO_TASK_CLASS_ADVANCEMENT", + "TODO_TASK_CLASS_BLOCKER", + "TODO_TASK_CLASS_MONITOR", + "todo_blocker_reason", + "todo_item_is_watch_only_monitor", + "todo_priority_parts", + "todo_priority_label", + "todo_priority_rank", + "todo_index_rank", + "todo_presentation_metadata", + "todo_presentation_sort_key", + "todo_projection_sort_key", + "todo_item_task_text", + "todo_item_task_class", + "todo_item_is_actionable_open", + "todo_item_is_deferred", + "todo_item_next_due_at", + "todo_item_expires_at", + "todo_item_is_expired_monitor", + "todo_item_is_due_monitor", + "todo_item_missing_monitor_schedule", + "todo_item_claimed_by_agent_or_unclaimed", + "_advancement_frontier_projection", + "todo_advancement_frontier_items", + "agent_scoped_selectable_advancement_todo_ids", + "todo_scoped_runnable_advancement_count", + "todo_advancement_frontier_counts", + "todo_item_has_removed_continuation_policy", + "todo_item_excludes_agent", + "todo_summary_claim_scope_agent_id", + "todo_summary_monitor_writeback_contract", + "todo_summary_monitor_writeback_supported", + "todo_summary_monitor_items", + "_summary_monitor_items", + "todo_summary_monitor_due_items", + "todo_summary_watch_only_monitor_due_items", + "todo_summary_non_watch_only_monitor_due_items", + "todo_summary_monitor_due_count", + "todo_summary_monitor_schedule_gap_items", + "todo_summary_monitor_schedule_gap_count", + "todo_summary_open_count", + "todo_summary_open_task_counts", + "todo_summary_has_only_future_scoped_monitor_work", + "_positive_int", + "todo_summary_first_executable_item", +) + + +def _any_ast_refs(path: Path) -> int: + tree = ast.parse(path.read_text(encoding="utf-8")) + count = 0 + for node in ast.walk(tree): + if isinstance(node, ast.Name) and node.id == "Any": + count += 1 + elif isinstance(node, ast.Attribute) and node.attr == "Any": + count += 1 + elif isinstance(node, ast.alias) and node.name == "Any": + count += 1 + return count + + +def test_todo_semantics_split_zero_any_ceilings_and_exports() -> None: + paths = [ + REPO_ROOT / "loopx/control_plane/todos/todo_item_semantics.py", + REPO_ROOT / "loopx/control_plane/todos/todo_summary_semantics.py", + REPO_ROOT / "loopx/control_plane/todos/todo_semantics.py", + Path(__file__).resolve(), + ] + for path in paths: + text = path.read_text(encoding="utf-8") + assert _any_ast_refs(path) == 0, path + assert _IGNORE_MARKER not in text, path + assert len(text.splitlines()) < 750, path + + main_lines = (REPO_ROOT / "loopx/control_plane/todos/todo_semantics.py").read_text( + encoding="utf-8" + ).splitlines() + assert len(main_lines) <= 550 + + for symbol in _PINNED_EXPORTS: + assert hasattr(todo_semantics, symbol), symbol + + assert todo_semantics.todo_priority_label is todo_item_semantics.todo_priority_label + assert ( + todo_semantics.todo_summary_open_task_counts + is todo_summary_semantics.todo_summary_open_task_counts + ) + assert TODO_STATUS_BLOCKED == "blocked" + assert TODO_STATUS_DEFERRED == "deferred" + assert TODO_TASK_CLASS_BLOCKER == "blocker" + + +def test_priority_key_presence_blocker_reason_and_presentation_boundaries() -> None: + assert todo_priority_parts("[p1] Ship fix") == ("P1", "Ship fix") + assert todo_priority_parts("No priority") == (None, "No priority") + assert todo_priority_label({"priority": None, "text": "[P0] Urgent"}) is None + assert todo_priority_label({"text": "[P0] Urgent"}) == "P0" + assert todo_priority_label({"title": "[P2] Title fallback"}) == "P2" + assert todo_priority_rank({"priority": None, "text": "[P0] Urgent"}) == TODO_MISSING_PRIORITY_RANK + assert todo_priority_rank("p3") == 3 + assert todo_priority_rank(MappingProxyType({"priority": "P1"})) == 1 + + assert todo_index_rank({"index": "12"}) == 12 + assert todo_index_rank({"index": None}) == TODO_MISSING_INDEX + assert todo_index_rank({"index": "not-an-int"}) == TODO_MISSING_INDEX + + assert ( + todo_blocker_reason( + { + "status": "blocked", + "reason": "Blocked on local file ~/workspace/secret/run.json failure", + } + ) + is None + ) + assert ( + todo_blocker_reason( + { + "status": "blocked", + "reason": "Blocked on missing peer receipt", + } + ) + == "Blocked on missing peer receipt" + ) + assert ( + todo_blocker_reason({"status": "open", "task_class": "advancement_task", "reason": "skip"}) + is None + ) + + with pytest.raises(ValueError, match="must be an object"): + todo_presentation_metadata(cast(dict[str, object], "bad")) + with pytest.raises(ValueError, match="unsupported Todo presentation schema"): + todo_presentation_metadata({"schema_version": "unknown_v99"}) + + native = { + "schema_version": TODO_NATIVE_ITEM_SCHEMA, + "todo_id": "t_native", + "role": "user", + "index": 1, + "updated_at": "2026-01-01T00:00:00Z", + } + assert todo_presentation_metadata(native) == { + "schema_version": TODO_PRESENTATION_METADATA_SCHEMA, + "todo_id": "t_native", + "display_section": "User Todo", + "display_order": None, + "order_source": "todo_id", + } + assert todo_presentation_sort_key(native)[1:] == ( + TODO_MISSING_INDEX, + "2026-01-01T00:00:00Z", + "t_native", + ) + legacy = { + "schema_version": TODO_LEGACY_ITEM_SCHEMA, + "todo_id": "t_legacy", + "index": 4, + } + assert todo_presentation_sort_key(legacy)[1:] == (4, "", "") + assert todo_presentation_sort_key({"schema_version": "outer_envelope_v1", "index": True})[1] == TODO_MISSING_INDEX + assert todo_presentation_sort_key({"schema_version": "outer_envelope_v1", "index": 3})[1] == 3 + assert todo_projection_sort_key({"priority": "P1", "index": 5}) == (1, 5) + + +def test_item_schedule_claim_and_actionable_predicates() -> None: + due_item = { + "todo_id": "m1", + "status": "open", + "title": "Observe peer status", + "next_due_at": "2025-01-01T00:00:00Z", + "expires_at": "2099-01-01T00:00:00Z", + "watch_only": True, + } + assert todo_item_task_text({"title": "A", "text": "B"}) == "A B" + assert todo_item_task_class(due_item) == TODO_TASK_CLASS_MONITOR + assert todo_item_is_watch_only_monitor(due_item) is True + assert todo_item_is_actionable_open(due_item) is True + assert todo_item_is_actionable_open( + {**due_item, "goal_acceptance_guard": {"allowed": False}} + ) is False + assert todo_item_is_deferred({"status": "deferred"}) is True + assert todo_item_next_due_at(due_item) is not None + assert todo_item_expires_at(due_item) is not None + assert todo_item_is_expired_monitor(due_item) is False + assert todo_item_is_due_monitor(due_item) is True + assert todo_item_missing_monitor_schedule({"status": "open", "task_class": TODO_TASK_CLASS_MONITOR}) is True + assert todo_item_has_removed_continuation_policy({"removed_continuation_policy": "primary_review"}) is True + assert todo_item_has_removed_continuation_policy({"removed_continuation_policy": "retired"}) is False + assert todo_item_excludes_agent({"excluded_agents": ["agent-a"]}, agent_id="agent-a") is True + assert todo_item_claimed_by_agent_or_unclaimed( + {"removed_continuation_policy": "primary_review"}, agent_id="agent-a" + ) is False + + +def test_summary_writeback_precedence_and_work_count_validation() -> None: + due_monitor = { + "todo_id": "m_due", + "status": "open", + "task_class": TODO_TASK_CLASS_MONITOR, + "next_due_at": "2020-01-01T00:00:00Z", + } + watch_due = {**due_monitor, "todo_id": "m_watch", "watch_only": True} + gap_monitor = { + "todo_id": "m_gap", + "status": "open", + "task_class": TODO_TASK_CLASS_MONITOR, + "claimed_by": "agent-a", + } + disabled: dict[str, object] = { + "monitor_writeback": {"supported": False, "source": " legacy_ro "}, + "monitor_due_items": [due_monitor], + "monitor_open_items": [due_monitor, gap_monitor], + } + assert todo_summary_monitor_writeback_contract(disabled) == { + "supported": False, + "source": "legacy_ro", + } + assert todo_summary_monitor_writeback_supported(disabled) is False + assert todo_summary_monitor_due_items(disabled) == [] + assert todo_summary_monitor_due_count(disabled) == 0 + assert todo_summary_monitor_schedule_gap_items(disabled) == [] + assert todo_summary_monitor_schedule_gap_count(disabled) == 0 + + precedence: dict[str, object] = { + "claim_scope": {"agent_id": "agent-a"}, + "monitor_due_count": 7, + "monitor_schedule_gap_count": 9, + "monitor_open_items": [due_monitor, gap_monitor], + } + assert todo_summary_monitor_due_count(precedence) == 7 + assert todo_summary_monitor_schedule_gap_count(precedence) == 1 + assert todo_summary_watch_only_monitor_due_items( + {"monitor_open_items": [due_monitor, watch_due]} + ) == [watch_due] + assert todo_summary_non_watch_only_monitor_due_items( + {"monitor_open_items": [due_monitor, watch_due]} + ) == [due_monitor] + assert todo_summary_open_count({"open_count": "-4"}) == 0 + assert todo_summary_open_count({"open_count": "15"}) == 15 + assert todo_summary_first_executable_item( + { + "first_executable_items": [ + due_monitor, + {"todo_id": "a1", "status": "open", "task_class": TODO_TASK_CLASS_ADVANCEMENT}, + ] + } + ) == {"todo_id": "a1", "status": "open", "task_class": TODO_TASK_CLASS_ADVANCEMENT} + + assert todo_summary_claim_scope_agent_id(None) is None + assert todo_summary_claim_scope_agent_id({"claim_scope": {"agent_id": " Agent A "}}) == "agent-a" + assert todo_summary_monitor_items( + {"monitor_due_items": [due_monitor], "monitor_open_items": [due_monitor, gap_monitor]} + ) == [due_monitor, gap_monitor] + assert todo_advancement_frontier_items(None, agent_id="agent-a") == { + "current_agent_claimed_items": [], + "unclaimed_items": [], + "other_agent_claimed_items": [], + } + assert todo_advancement_frontier_counts(None, agent_id="agent-a") == { + "current_agent_claimed_advancement_count": 0, + "unclaimed_advancement_count": 0, + "other_agent_claimed_advancement_count": 0, + } + assert agent_scoped_selectable_advancement_todo_ids( + {"executable_backlog_items": [{"todo_id": "todo_sample_a1", "status": "open", "task_class": TODO_TASK_CLASS_ADVANCEMENT}]}, + agent_id="agent-a", + ) == {"todo_sample_a1"} + assert ( + todo_scoped_runnable_advancement_count( + {"work_counts": {"schema_version": "todo_work_counts_v0", "complete": True, "agent_id": "agent-a", "advancement": 3}}, + agent_id="agent-a", + ) + == 3 + ) + assert ( + todo_scoped_runnable_advancement_count( + {"work_counts": {"schema_version": "todo_work_counts_v0", "complete": True, "agent_id": "agent-a", "advancement": True}}, + agent_id="agent-a", + ) + is None + ) + + for bad_counts in ( + {"schema_version": "wrong", "complete": True, "open": 0, "advancement": 0, "monitor": 0, "hidden": 0}, + {"schema_version": "todo_work_counts_v0", "complete": True, "open": True, "advancement": 0, "monitor": 0, "hidden": 0}, + {"schema_version": "todo_work_counts_v0", "complete": True, "open": 1, "advancement": 0, "monitor": 0, "hidden": 1}, + {"schema_version": "todo_work_counts_v0", "complete": False, "open": 1, "advancement": 1, "monitor": 1, "hidden": 0}, + ): + with pytest.raises(ValueError, match="Todo work count"): + todo_summary_open_task_counts({"work_counts": bad_counts}) + + +def test_hot_path_avoids_sort_dict_allocations_and_duplicate_monitor_count_scans( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail_metadata(_item: object) -> dict[str, object]: + raise AssertionError("todo_presentation_sort_key allocated full metadata dict") + + monkeypatch.setattr(todo_item_semantics, "todo_presentation_metadata", fail_metadata) + rows: list[dict[str, object]] = [ + {"schema_version": TODO_NATIVE_ITEM_SCHEMA, "priority": "P2", "todo_id": "b", "updated_at": "2"}, + {"schema_version": TODO_LEGACY_ITEM_SCHEMA, "priority": "P2", "todo_id": "a", "index": 1}, + ] + assert [row["todo_id"] for row in sorted(rows, key=todo_presentation_sort_key)] == ["a", "b"] + + due_calls = 0 + gap_calls = 0 + orig_due = todo_summary_semantics.todo_summary_monitor_due_count + orig_gap = todo_summary_semantics.todo_summary_monitor_schedule_gap_count + + def count_due(*args: object, **kwargs: object) -> int: + nonlocal due_calls + due_calls += 1 + return orig_due(*cast(tuple[dict[str, object] | None], args)) + + def count_gap(*args: object, **kwargs: object) -> int: + nonlocal gap_calls + gap_calls += 1 + return orig_gap(*cast(tuple[dict[str, object] | None], args)) + + def fail_monitor_list(_summary: object) -> list[dict[str, object]]: + raise AssertionError("future-scoped check materialized full monitor list") + + monkeypatch.setattr(todo_summary_semantics, "todo_summary_monitor_due_count", count_due) + monkeypatch.setattr(todo_summary_semantics, "todo_summary_monitor_schedule_gap_count", count_gap) + monkeypatch.setattr(todo_summary_semantics, "todo_summary_monitor_items", fail_monitor_list) + + future_monitor = { + "todo_id": "m_future", + "status": "open", + "task_class": TODO_TASK_CLASS_MONITOR, + "claimed_by": "agent-a", + "next_due_at": "2099-01-01T00:00:00Z", + } + summary: dict[str, object] = { + "claim_scope": {"agent_id": "agent-a"}, + "monitor_open_items": [future_monitor], + "work_counts": { + "schema_version": "todo_work_counts_v0", + "agent_id": "agent-a", + "complete": True, + "open": 1, + "advancement": 0, + "monitor": 1, + "hidden": 0, + }, + } + assert todo_summary_has_only_future_scoped_monitor_work(summary) is True + assert due_calls == 1 + assert gap_calls == 1 + + +def test_paired_origin_main_behavioral_parity_across_item_frontier_and_summary( + tmp_path: Path, +) -> None: + rev = subprocess.run( + ["git", "-C", str(REPO_ROOT), "rev-parse", "--verify", "origin/main"], + text=True, + capture_output=True, + ) + if rev.returncode != 0: + pytest.skip("origin/main ref unavailable in shallow checkout") + + baseline_code = subprocess.check_output( + [ + "git", + "-C", + str(REPO_ROOT), + "show", + "origin/main:loopx/control_plane/todos/todo_semantics.py", + ], + text=True, + ) + script = """ +import sys, types +from loopx.control_plane.todos import todo_semantics as head_mod +spec_mod = types.ModuleType("baseline_todo_semantics") +spec_mod.__package__ = "loopx.control_plane.todos" +baseline_code = open(sys.argv[1], encoding="utf-8").read() +exec(compile(baseline_code, "origin_main_todo_semantics.py", "exec"), spec_mod.__dict__) + +future_m = {"todo_id": "m_future", "status": "open", "task_class": "continuous_monitor", + "claimed_by": "agent-a", "next_due_at": "2099-01-01T00:00:00Z"} +due_m = {"todo_id": "m_due", "status": "open", "task_class": "continuous_monitor", + "next_due_at": "2020-01-01T00:00:00Z", "watch_only": True} +gap_m = {"todo_id": "m_gap", "status": "open", "task_class": "continuous_monitor", "claimed_by": "agent-a"} +adv_a = {"todo_id": "a_own", "status": "open", "task_class": "advancement_task", "claimed_by": "agent-a", "priority": "P1", "index": 2} +adv_free = {"todo_id": "a_free", "status": "open", "task_class": "advancement_task", "text": "[P0] First", "index": 5} +adv_null_prio = {"todo_id": "a_null", "status": "open", "task_class": "advancement_task", "priority": None, "text": "[P0] Ignored"} + +items = [ + adv_a, adv_free, adv_null_prio, future_m, due_m, gap_m, + {"schema_version": "todo_domain_record_v0", "todo_id": "t_dom", "role": "agent", "archive_state": "archive", "index": 0, "completed_at": "2025-01-01T00:00:00Z"}, + {"schema_version": "todo_item_v0", "todo_id": "t_v0", "source_section": "User Todo", "index": 3}, + {"schema_version": "outer_custom_v1", "todo_id": "t_outer", "index": 2, "priority": "P1"}, + {"status": "blocked", "reason": "Blocked near ~/example/a/b"}, +] +summaries = [ + None, + {}, + {"claim_scope": {"agent_id": "agent-a"}, "monitor_open_items": [future_m], + "work_counts": {"schema_version": "todo_work_counts_v0", "agent_id": "agent-a", "complete": True, "open": 1, "advancement": 0, "monitor": 1, "hidden": 0}}, + {"claim_scope": {"agent_id": "agent-a"}, "monitor_due_items": [], "monitor_open_items": [due_m, gap_m], + "executable_backlog_items": [adv_a, adv_free], "current_agent_claimed_advancement_count": 9007199254740993, + "work_counts": {"schema_version": "todo_work_counts_v0", "agent_id": "agent-a", "complete": True, "open": 4, "advancement": 2, "monitor": 2, "hidden": 0}}, + {"unclaimed_priority_open_items": [adv_free], "claimed_advancement_open_items": [adv_a], "monitor_due_count": 4, "monitor_schedule_gap_count": 3}, + {"monitor_writeback": {"supported": False, "source": "ro"}, "monitor_due_items": [due_m]}, +] +for item in items: + for fn_name in ("todo_blocker_reason", "todo_item_is_watch_only_monitor", "todo_priority_label", "todo_priority_rank", "todo_index_rank", "todo_presentation_sort_key", "todo_projection_sort_key", "todo_item_task_text", "todo_item_task_class", "todo_item_is_actionable_open", "todo_item_is_deferred", "todo_item_is_expired_monitor", "todo_item_is_due_monitor", "todo_item_missing_monitor_schedule"): + assert getattr(head_mod, fn_name)(item) == getattr(spec_mod, fn_name)(item), (fn_name, item) + assert head_mod.todo_item_claimed_by_agent_or_unclaimed(item, agent_id="agent-a") == spec_mod.todo_item_claimed_by_agent_or_unclaimed(item, agent_id="agent-a") +for summary in summaries: + for fn_name in ("todo_summary_claim_scope_agent_id", "todo_summary_monitor_writeback_contract", "todo_summary_monitor_writeback_supported", "todo_summary_monitor_items", "todo_summary_monitor_due_items", "todo_summary_watch_only_monitor_due_items", "todo_summary_non_watch_only_monitor_due_items", "todo_summary_monitor_due_count", "todo_summary_monitor_schedule_gap_items", "todo_summary_monitor_schedule_gap_count", "todo_summary_open_count", "todo_summary_open_task_counts", "todo_summary_has_only_future_scoped_monitor_work", "todo_summary_first_executable_item"): + assert getattr(head_mod, fn_name)(summary) == getattr(spec_mod, fn_name)(summary), (fn_name, summary) + for agent in (None, "agent-a"): + assert head_mod.todo_advancement_frontier_items(summary, agent_id=agent) == spec_mod.todo_advancement_frontier_items(summary, agent_id=agent) + assert head_mod.todo_advancement_frontier_counts(summary, agent_id=agent) == spec_mod.todo_advancement_frontier_counts(summary, agent_id=agent) + assert head_mod.agent_scoped_selectable_advancement_todo_ids(summary, agent_id=agent) == spec_mod.agent_scoped_selectable_advancement_todo_ids(summary, agent_id=agent) + assert head_mod.todo_scoped_runnable_advancement_count(summary, agent_id=agent) == spec_mod.todo_scoped_runnable_advancement_count(summary, agent_id=agent) +print("PARITY_OK") +""" + baseline_file = tmp_path / "origin_main_todo_semantics.py" + baseline_file.write_text(baseline_code, encoding="utf-8") + proc = subprocess.run( + [sys.executable, "-c", script, str(baseline_file)], + cwd=str(REPO_ROOT), + text=True, + capture_output=True, + check=True, + ) + assert proc.stdout.strip() == "PARITY_OK"