diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json index e6a6fe67b9..0b32d9555f 100644 --- a/loopx/canary/module_metric_baseline.json +++ b/loopx/canary/module_metric_baseline.json @@ -50,7 +50,7 @@ "lines": 2058 }, "loopx/control_plane/agents/agent_scope.py": { - "any_count": 107, + "any_count": 13, "dict_any_count": 0 }, "loopx/control_plane/goals/goal_frontier/__init__.py": { diff --git a/loopx/control_plane/agents/agent_scope.py b/loopx/control_plane/agents/agent_scope.py index 0b5cc95ff9..f144b40ce9 100644 --- a/loopx/control_plane/agents/agent_scope.py +++ b/loopx/control_plane/agents/agent_scope.py @@ -1,8 +1,8 @@ from __future__ import annotations -import re +from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass -from typing import Any, TypeGuard +from typing import Any, TypedDict, TypeGuard from .agent_scope_frontier import ( AGENT_LANE_FRONTIER_HINT_SCHEMA_VERSION, @@ -11,12 +11,6 @@ agent_scope_frontier_action as _frontier_action, build_agent_scope_frontier_payload, ) - -from ..todos.decision_scope import select_scoped_gate_fallback -from ..work_items.work_lane import ( - work_lane_contract_is_due_monitor_attempt, - work_lane_contract_requires_current_agent_attempt, -) from ..todos.contract import ( TODO_TASK_CLASS_ADVANCEMENT, TODO_TASK_CLASS_MONITOR, @@ -26,8 +20,10 @@ normalize_todo_excluded_agents, normalize_todo_id, ) +from ..todos.decision_scope import select_scoped_gate_fallback from ..todos.handoff_gate import HandoffGateState from ..todos.resume_planning import project_todo_resume_planning +from ..todos.summary_item import compact_todo_summary_item, compact_todo_summary_items from ..todos.todo_semantics import ( todo_item_claimed_by_agent_or_unclaimed, todo_item_excludes_agent, @@ -37,66 +33,99 @@ todo_presentation_sort_key, todo_scoped_runnable_advancement_count, ) -from ..todos.summary_item import compact_todo_summary_item, compact_todo_summary_items from ..todos.user_gate import ( open_todo_count as _open_todo_count, open_user_gate_todo_items as _open_user_gate_todo_items, ) +from ..work_items.work_lane import ( + work_lane_contract_is_due_monitor_attempt, + work_lane_contract_requires_current_agent_attempt, +) _agent_scope_frontier_action = _frontier_action -_ACTION_SCOPE_STOPWORDS = { - "a", - "an", - "and", - "approve", - "approved", - "approval", - "before", - "blocked", - "continue", - "decide", - "decision", - "for", - "from", - "gate", - "gated", - "goal", - "harness", - "internal", - "material", - "next", - "open", - "owner", - "p0", - "p1", - "p2", - "p3", - "provide", - "read", - "registered", - "safe", - "should", - "sync", - "the", - "todo", - "until", - "user", - "whether", - "with", -} - AGENT_TASK_SCOPE = "goal_all_read_claimed_run_global_read_v0" + + +class _TodoPatch(TypedDict): + status: str + waiting_on: str + recommended_action: str + + +def _as_dict(value: object) -> dict[str, object]: + """Return ``value`` when it is a dict, otherwise an empty dict.""" + return value if isinstance(value, dict) else {} + + +def _int_value(value: object) -> int: + """Coerce numeric or string count values to int, defaulting to zero.""" + return int(value or 0) if isinstance(value, (int, float, str)) else 0 + + +def _dict_items(value: object) -> list[dict[str, object]]: + """Filter a list value down to dictionary items.""" + return [item for item in value if isinstance(item, dict)] if isinstance(value, list) else [] + + +def _first_dict(mapping: Mapping[str, object], key: str) -> dict[str, object]: + """Return the first dictionary element stored under ``key``, or an empty dict.""" + items = _dict_items(mapping.get(key)) + return items[0] if items else {} + + +def _todo_label( + item: Mapping[str, object], + *, + keys: tuple[str, ...] = ("todo_id",), + fallback: str, +) -> str: + """Return the first non-empty stripped label among ``keys``, else ``fallback``.""" + for key in keys: + label = str(item.get(key) or "").strip() + if label: + return label + return fallback + + +def _todo_identity( + item: Mapping[str, object], + *, + keys: tuple[str, ...] = ("todo_id", "index", "text"), +) -> str: + """Build a deduplication identity from the first truthy field in ``keys``.""" + for key in keys: + if value := item.get(key): + return str(value) + return "" + + +def _sorted_claimants( + items: Sequence[Mapping[str, object]], + *, + excluded_agent: str | None = None, +) -> list[str]: + """Return sorted unique claimants, optionally filtered to items excluding an agent.""" + return sorted( + { + claimed_by + for item in items + if excluded_agent is None or excluded_agent in agent_scope_item_excluded_agents(item) + if (claimed_by := agent_scope_item_claimed_by(item)) + } + ) + + def _agent_identity_has_scoped_lane( - agent_identity: dict[str, Any] | None, -) -> TypeGuard[dict[str, object]]: + agent_identity: Mapping[str, object] | None, +) -> TypeGuard[Mapping[str, object]]: return isinstance(agent_identity, dict) and bool( normalize_todo_claimed_by(agent_identity.get("agent_id")) ) + + def _attach_agent_identity_contracts( - *, - payload: dict[str, Any], - agent_identity: dict[str, Any] | None, + *, payload: dict[str, Any], agent_identity: Mapping[str, object] | None ) -> dict[str, Any]: if not agent_identity: return payload @@ -105,61 +134,48 @@ def _attach_agent_identity_contracts( return payload -def _todo_task_class(item: dict[str, Any]) -> str: +def _todo_task_class(item: Mapping[str, object]) -> str: return todo_item_task_class(item) -def _todo_projection_sort_key(item: dict[str, Any]) -> tuple[int, int, str, str]: - return todo_presentation_sort_key(item) -def _todo_item_is_actionable_open(item: dict[str, Any]) -> bool: +def _todo_item_is_actionable_open(item: dict[str, object]) -> bool: return todo_item_is_actionable_open(item) -def agent_scope_item_claimed_by(item: dict[str, Any]) -> str | None: +def agent_scope_item_claimed_by(item: Mapping[str, object]) -> str | None: return normalize_todo_claimed_by(item.get("claimed_by")) -def agent_scope_item_blocks_agent(item: dict[str, Any]) -> str | None: +def agent_scope_item_blocks_agent(item: Mapping[str, object]) -> str | None: return normalize_todo_blocks_agent(item.get("blocks_agent")) -def agent_scope_item_bound_agent(item: dict[str, Any]) -> str | None: +def agent_scope_item_bound_agent(item: Mapping[str, object]) -> str | None: return normalize_todo_bound_agent(item.get("bound_agent")) -def agent_scope_item_excluded_agents(item: dict[str, Any]) -> list[str]: +def agent_scope_item_excluded_agents(item: Mapping[str, object]) -> list[str]: return normalize_todo_excluded_agents(item.get("excluded_agents")) def agent_scope_item_claimed_by_agent_or_unclaimed( - item: dict[str, Any], - *, - agent_id: str | None, + item: dict[str, object], *, agent_id: str | None ) -> bool: return todo_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id) def agent_scope_item_matches_agent_or_unclaimed( - item: dict[str, Any], - *, - agent_id: str | None, + item: dict[str, object], *, agent_id: str | None ) -> bool: normalized_agent_id = normalize_todo_claimed_by(agent_id) if not normalized_agent_id: return True if todo_item_excludes_agent(item, agent_id=normalized_agent_id): return False - return agent_scope_item_claimed_by_agent_or_unclaimed( - item, - agent_id=normalized_agent_id, - ) + return agent_scope_item_claimed_by_agent_or_unclaimed(item, agent_id=normalized_agent_id) -def agent_scope_count_advancement_items( - items: Any, - *, - claimed_by: str | None = None, -) -> int: +def agent_scope_count_advancement_items(items: object, *, claimed_by: str | None = None) -> int: if not isinstance(items, list): return 0 normalized_claimed_by = ( @@ -171,11 +187,11 @@ def agent_scope_count_advancement_items( ) count = 0 for item in items: - if not isinstance(item, dict): - continue - if not _todo_item_is_actionable_open(item): - continue - if _todo_task_class(item) != TODO_TASK_CLASS_ADVANCEMENT: + if ( + not isinstance(item, dict) + or not _todo_item_is_actionable_open(item) + or _todo_task_class(item) != TODO_TASK_CLASS_ADVANCEMENT + ): continue item_claimed_by = agent_scope_item_claimed_by(item) if normalized_claimed_by == "__unclaimed__": @@ -187,134 +203,110 @@ def agent_scope_count_advancement_items( return count -def _protocol_action_text(value: Any, *, limit: int = 220) -> str | None: +def _protocol_action_text(value: object, *, limit: int = 220) -> str | None: if value is None: return None text = " ".join(str(value).strip().split()) if not text: return None - if len(text) <= limit: - return text - return text[: max(0, limit - 3)].rstrip() + "..." + return text if len(text) <= limit else text[: max(0, limit - 3)].rstrip() + "..." -def _action_scope_tokens_from_text(text: str) -> set[str]: - return { - token - for token in re.findall( - r"[a-z0-9]+", - text.lower().replace("_", " ").replace("-", " "), +def _gate_fallback_candidates( + agent_todo_summary: Mapping[str, object], + capability_gate: Mapping[str, object] | None, + requested_candidate: dict[str, object] | None, +) -> list[dict[str, object]]: + """Collect due monitors, runnable advancement items, and ready deferred candidates.""" + # An empty capability projection is authoritative for advancement work. + # Due monitors are projected separately and are already scoped and due here. + capability_candidates = ( + capability_gate.get("runnable_candidates") if isinstance(capability_gate, Mapping) else None + ) + if isinstance(capability_candidates, list): + advancement_candidates = _dict_items(capability_candidates) + else: + raw_backlog = agent_todo_summary.get("executable_backlog_items") + advancement_candidates = _dict_items( + raw_backlog + if isinstance(raw_backlog, list) + else agent_todo_summary.get("first_executable_items") ) - if len(token) > 1 and token not in _ACTION_SCOPE_STOPWORDS - } - - -def _todo_item_claimed_by_agent_or_unclaimed(item: dict[str, Any], *, agent_id: str) -> bool: - return agent_scope_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id) + executable_items: list[dict[str, object]] = [ + *_dict_items(agent_todo_summary.get("monitor_due_items")), + *advancement_candidates, + *_dict_items(agent_todo_summary.get("deferred_resume_candidates")), + ] + # Exact selection was qualified from the complete inventory; carry it first + # so display lanes dropping it never lose gate metadata. + return [requested_candidate, *executable_items] if requested_candidate is not None else executable_items def _scoped_user_gate_fallback( - user_todo_summary: dict[str, Any] | None, - agent_todo_summary: dict[str, Any] | None, + user_todo_summary: Mapping[str, object] | None, + agent_todo_summary: Mapping[str, object] | None, *, - capability_gate: dict[str, Any] | None = None, + capability_gate: Mapping[str, object] | None = None, allow_unrelated_gate: bool = False, monitor_debt_backoff_active: bool = False, requested_todo_id: str | None = None, - requested_candidate: dict[str, Any] | None = None, + requested_candidate: dict[str, object] | None = None, ) -> dict[str, Any] | None: - gates = _open_user_gate_todo_items(user_todo_summary) + gates = _open_user_gate_todo_items(user_todo_summary if isinstance(user_todo_summary, dict) else None) if not gates or not isinstance(agent_todo_summary, dict): return None - raw_due_monitor_candidates = agent_todo_summary.get("monitor_due_items") - due_monitor_candidates = raw_due_monitor_candidates if isinstance(raw_due_monitor_candidates, list) else [] - raw_ready_deferred_candidates = agent_todo_summary.get( - "deferred_resume_candidates" - ) - ready_deferred_candidates = raw_ready_deferred_candidates if isinstance(raw_ready_deferred_candidates, list) else [] - - # An empty capability projection is authoritative for advancement work. - # Due monitors are projected separately from advancement candidates and are - # already current-agent scoped, due, and capability-runnable here. - capability_candidates = ( - capability_gate.get("runnable_candidates") - if isinstance(capability_gate, dict) - else None - ) - if isinstance(capability_candidates, list): - executable_items = [ - *due_monitor_candidates, - *capability_candidates, - *ready_deferred_candidates, - ] - else: - raw_backlog_items = agent_todo_summary.get("executable_backlog_items") - raw_first_items = agent_todo_summary.get("first_executable_items") - advancement_items = ( - raw_backlog_items - if isinstance(raw_backlog_items, list) - else raw_first_items - if isinstance(raw_first_items, list) - else [] - ) - executable_items = [ - *due_monitor_candidates, - *advancement_items, - *ready_deferred_candidates, - ] - executable_items = [item for item in executable_items if isinstance(item, dict)] - # Exact selection was qualified from the complete inventory. Display lanes - # may omit it; transport the original row so gate metadata is not lost. - if requested_candidate is not None: - executable_items = [requested_candidate, *executable_items] - claim_scope = ( - agent_todo_summary.get("claim_scope") - if isinstance(agent_todo_summary.get("claim_scope"), dict) - else None - ) + executable_items = _gate_fallback_candidates(agent_todo_summary, capability_gate, requested_candidate) + raw_scope_agent_id = _as_dict(agent_todo_summary.get("claim_scope")).get("agent_id") selection = select_scoped_gate_fallback( - gates, executable_items, agent_id=claim_scope.get("agent_id") if claim_scope else None, - allow_unrelated_gate=allow_unrelated_gate, monitor_debt_backoff_active=monitor_debt_backoff_active, + gates, + executable_items, + agent_id=None if raw_scope_agent_id is None else str(raw_scope_agent_id), + allow_unrelated_gate=allow_unrelated_gate, + monitor_debt_backoff_active=monitor_debt_backoff_active, requested_todo_id=requested_todo_id, ) if selection is None: return None selected = executable_items[selection["selected_index"]] gate_to_surface = gates[selection["gate_index"]] - blocking_gate = selection["has_blocking_gate"] - blocked_items = [] - for blocked in selection["blocked"][:3]: - item = executable_items[blocked["candidate_index"]] - blocked_items.append({**compact_todo_summary_item(item, text=str(item.get("text") or "").strip()), - "todo_gate_relation": blocked["relation"]}) - selected_text = str(selected.get("text") or "").strip() - selected_item = compact_todo_summary_item(selected, text=selected_text) + blocked_items = [ + { + **compact_todo_summary_item(item, text=str(item.get("text") or "").strip()), + "todo_gate_relation": blocked["relation"], + } + for blocked in selection["blocked"][:3] + for item in (executable_items[blocked["candidate_index"]],) + ] + selected_item = compact_todo_summary_item(selected, text=str(selected.get("text") or "").strip()) selected_is_deferred_replan = selection["deferred_replan"] if selected_is_deferred_replan: selected_item["fallback_kind"] = "deferred_successor_replan" - selected_relation = selection["selected_relation"] - if selected_relation: - selected_item["todo_gate_relation"] = selected_relation - gate_text = str(gate_to_surface.get("text") or "").strip() - reason = ( - "an open user_gate blocks a scoped agent todo, but a non-dependent " - "executable fallback remains available" - if blocking_gate - else ( + if selection["selected_relation"]: + selected_item["todo_gate_relation"] = selection["selected_relation"] + if selection["has_blocking_gate"]: + reason = ( + "an open user_gate blocks a scoped agent todo, but a non-dependent " + "executable fallback remains available" + ) + elif selected_is_deferred_replan: + reason = ( "an open user_gate blocks a different action scope, but the ready " "deferred successor can be replanned independently" - if selected_is_deferred_replan - else "an open user_gate blocks a different action scope, but the selected " + ) + else: + reason = ( + "an open user_gate blocks a different action scope, but the selected " "executable agent todo is non-dependent and safe to advance" ) - ) return { "schema_version": "scoped_user_gate_fallback_v0", "kind": "scoped_user_gate_fallback", "notify_user": True, "requires_user_action": True, "reason": reason, - "blocked_user_gate": compact_todo_summary_item(gate_to_surface, text=gate_text), + "blocked_user_gate": compact_todo_summary_item( + gate_to_surface, text=str(gate_to_surface.get("text") or "").strip() + ), "blocked_agent_items": blocked_items[:3], "selected_executable": selected_item, "recommended_action": ( @@ -328,73 +320,54 @@ def _scoped_user_gate_fallback( } -def _first_executable_todo_text(agent_todo_summary: dict[str, Any] | None) -> str | None: - if not isinstance(agent_todo_summary, dict): - return None - raw_items = agent_todo_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_task_class(item) != TODO_TASK_CLASS_ADVANCEMENT: - continue - text = _protocol_action_text(item.get("text"), limit=320) - if text: - return text - return None - - -def _first_monitor_todo_text(agent_todo_summary: dict[str, Any] | None) -> str | None: - if not isinstance(agent_todo_summary, dict): +def _first_todo_text_for_class( + agent_todo_summary: Mapping[str, object] | None, + *, + keys: tuple[str, ...], + task_class: str, +) -> str | None: + """Return the first normalized open todo text matching ``task_class`` across ``keys``.""" + if not isinstance(agent_todo_summary, Mapping): return None - for key in ("monitor_due_items", "monitor_open_items"): - raw_items = agent_todo_summary.get(key) - 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_task_class(item) != TODO_TASK_CLASS_MONITOR: - continue - text = _protocol_action_text(item.get("text"), limit=320) - if text: - return text + for key in keys: + for item in _dict_items(agent_todo_summary.get(key)): + if _todo_item_is_actionable_open(item) and _todo_task_class(item) == task_class: + if text := _protocol_action_text(item.get("text"), limit=320): + return text return None def _agent_scoped_user_todo_override( *, state: str, - item: dict[str, Any], - user_todo_summary: dict[str, Any] | None, - agent_todo_summary: dict[str, Any] | None, - agent_identity: dict[str, Any] | None, + item: Mapping[str, object], + user_todo_summary: Mapping[str, object] | None, + agent_todo_summary: Mapping[str, object] | None, + agent_identity: Mapping[str, object] | None, ) -> dict[str, Any] | None: - if state != "operator_gate": - return None - if not isinstance(agent_identity, dict): - return None - if not isinstance(user_todo_summary, dict): + if state != "operator_gate" or not isinstance(agent_identity, dict) or not isinstance(user_todo_summary, dict): return None - # A non-blocking user_action may still need a reminder without preserving - # an operator gate inherited from a different agent's user_gate. + # Non-blocking user_action rows may remain a reminder without preserving an + # operator gate inherited from another agent's user_gate. if _open_user_gate_todo_items(user_todo_summary): return None - other_gate_count = _open_todo_count( - {"open_count": user_todo_summary.get("other_agent_scoped_open_count")} - ) if item.get("operator_question") or item.get("missing_gates"): return None - selected_action = _first_executable_todo_text(agent_todo_summary) - if not selected_action: - selected_action = _first_monitor_todo_text(agent_todo_summary) + selected_action = _first_todo_text_for_class( + agent_todo_summary, keys=("first_executable_items",), task_class=TODO_TASK_CLASS_ADVANCEMENT + ) or _first_todo_text_for_class( + agent_todo_summary, keys=("monitor_due_items", "monitor_open_items"), task_class=TODO_TASK_CLASS_MONITOR + ) agent_id = normalize_todo_claimed_by(agent_identity.get("agent_id")) + other_gate_count = _open_todo_count({"open_count": user_todo_summary.get("other_agent_scoped_open_count")}) if other_gate_count > 0: if not selected_action: return None + gate_patch: _TodoPatch = { + "status": "active_state_agent_todo", + "waiting_on": "codex", + "recommended_action": selected_action, + } return { "schema_version": "agent_scoped_user_gate_override_v0", "kind": "agent_scoped_user_gate_override", @@ -407,21 +380,18 @@ def _agent_scoped_user_todo_override( "the open user gate is scoped to another agent via blocks_agent or " "claimed_by; this agent still has an executable in-scope todo" ), - "item_patch": { - "status": "active_state_agent_todo", - "waiting_on": "codex", - "recommended_action": selected_action, - }, + "item_patch": gate_patch, } other_action_count = _open_todo_count( - { - "open_count": user_todo_summary.get( - "other_agent_bound_user_action_open_count" - ) - } + {"open_count": user_todo_summary.get("other_agent_bound_user_action_open_count")} ) if other_action_count <= 0: return None + action_patch: _TodoPatch = { + "status": "active_state_agent_todo" if selected_action else "agent_scope_wait", + "waiting_on": "codex" if selected_action else "agent_scope", + "recommended_action": selected_action or "wait for work or a user action bound to this agent", + } result: dict[str, Any] = { "schema_version": "agent_scoped_user_action_override_v0", "kind": "agent_scoped_user_action_override", @@ -433,268 +403,204 @@ def _agent_scoped_user_todo_override( "the only open user actions are bound to another agent; they remain " "diagnostic-only for this lane and cannot create an operator gate" ), - "quota_patch": { - "safe_bypass_allowed": False, - "safe_bypass_kind": None, - "blocked_action_scope": None, - }, - "item_patch": { - "status": "active_state_agent_todo" if selected_action else "agent_scope_wait", - "waiting_on": "codex" if selected_action else "agent_scope", - "recommended_action": ( - selected_action or "wait for work or a user action bound to this agent" - ), - }, + "quota_patch": {"safe_bypass_allowed": False, "safe_bypass_kind": None, "blocked_action_scope": None}, + "item_patch": action_patch, } if selected_action: result["selected_action"] = selected_action return result -def _count_advancement_items(items: Any, *, claimed_by: str | None = None) -> int: - return agent_scope_count_advancement_items(items, claimed_by=claimed_by) - - -def _selectable_unclaimed_advancement_count( - agent_todo_summary: dict[str, Any], -) -> int: +def _selectable_unclaimed_advancement_count(agent_todo_summary: Mapping[str, object]) -> int: executable_items = agent_todo_summary.get("executable_backlog_items") source_items = ( - executable_items - if isinstance(executable_items, list) - else agent_todo_summary.get("unclaimed_priority_open_items") + executable_items if isinstance(executable_items, list) else agent_todo_summary.get("unclaimed_priority_open_items") ) - return _count_advancement_items(source_items, claimed_by="__unclaimed__") + return agent_scope_count_advancement_items(source_items, claimed_by="__unclaimed__") -def _first_compact_todo_id(items: Any) -> str | None: - if not isinstance(items, list): - return None - for item in items: - if not isinstance(item, dict): - continue - todo_id = normalize_todo_id(item.get("todo_id")) - if todo_id: +def _first_compact_todo_id(items: object) -> str | None: + for item in _dict_items(items): + if todo_id := normalize_todo_id(item.get("todo_id")): return todo_id return None +def _build_frontier_hint( + agent_id: str, + decision: AgentLaneFrontierHintDecision, + *, + reason_code: str, + source: str = "agent_scope_frontier", + quiet_noop_allowed: bool = False, + target_todo_id: str | None = None, + next_cli_action: str | None = None, +) -> dict[str, object]: + """Construct the structured hint projection for a scoped agent frontier.""" + hint: dict[str, object] = { + "schema_version": AGENT_LANE_FRONTIER_HINT_SCHEMA_VERSION, + "decision": decision.value, + "agent_id": agent_id, + "agent_model": "peer_v1", + "source": source, + "reason_code": reason_code, + "quiet_noop_allowed": quiet_noop_allowed, + "uses_structured_frontier": True, + } + if target_todo_id: + hint["target_todo_id"] = target_todo_id + if next_cli_action: + hint["next_cli_action"] = next_cli_action + return hint + + +def _successor_replan_frontier_hint( + frontier: Mapping[str, object], *, goal_id: str, agent_id: str +) -> dict[str, object] | None: + """Select the highest-precedence hint when successor replan is required.""" + if cleared_todo_id := _first_compact_todo_id(frontier.get("cleared_without_successor_handoff_gates")): + return _build_frontier_hint( + agent_id, + AgentLaneFrontierHintDecision.RECORD_NO_FOLLOWUP, + reason_code="cleared_handoff_without_successor", + target_todo_id=cleared_todo_id, + next_cli_action=( + f"loopx todo complete --goal-id {goal_id} --todo-id {cleared_todo_id} " + f"--agent-id {agent_id} --no-follow-up --evidence ''" + ), + ) + if frontier.get("dependency_cycle_candidates"): + # The typed replan carries the repair; no legacy hint describes dependency repair safely. + return None + if monitor_candidate := _first_dict(frontier, "monitor_blocked_resume_candidates"): + monitor_blocker_id = normalize_todo_id(monitor_candidate.get("blocking_monitor_todo_id")) + target_todo_id = normalize_todo_id(monitor_candidate.get("todo_id")) + return _build_frontier_hint( + agent_id, + AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, + reason_code="resume_blocked_by_open_monitor", + target_todo_id=target_todo_id or monitor_blocker_id, + next_cli_action=( + f"loopx todo complete --goal-id {goal_id} --todo-id {monitor_blocker_id} " + f"--agent-id {agent_id} --evidence ''" + if monitor_blocker_id + else None + ), + ) + if route_candidate := _first_dict(frontier, "route_continuation_replan_candidates"): + route_target = ( + normalize_todo_id(route_candidate.get("todo_id")) + or normalize_todo_id(route_candidate.get("route_id")) + or normalize_todo_id(route_candidate.get("route_key")) + ) + return _build_frontier_hint( + agent_id, + AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, + reason_code="route_continuation_replan_required", + target_todo_id=route_target, + next_cli_action=( + f"loopx todo add --goal-id {goal_id} --role agent " + "--text ''" + ), + ) + return _build_frontier_hint( + agent_id, + AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, + reason_code="successor_replan_required", + target_todo_id=_first_compact_todo_id(frontier.get("deferred_resume_candidates")), + ) + + +_WAIT_HINT_CANDIDATE_KEYS: tuple[tuple[str, str], ...] = ( + ("blocked_todo_wait_candidates", "current_agent_blocker"), + ("blocked_successor_wait_candidates", "blocked_successor_resume_pending"), + ("blocking_handoff_gates", "blocked_by_other_agent_frontier"), + ("other_agent_claimed_items", "blocked_by_other_agent_frontier"), +) + + +def _wait_frontier_hint(frontier: Mapping[str, object], *, agent_id: str) -> dict[str, object]: + """Select the wait-blocker hint in precedence order.""" + for key, reason_code in _WAIT_HINT_CANDIDATE_KEYS: + if target_todo_id := _first_compact_todo_id(frontier.get(key)): + return _build_frontier_hint( + agent_id, + AgentLaneFrontierHintDecision.QUIET_NOOP_BLOCKER, + reason_code=reason_code, + target_todo_id=target_todo_id, + quiet_noop_allowed=True, + ) + return _build_frontier_hint( + agent_id, + AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, + reason_code="no_current_agent_advancement_todo", + quiet_noop_allowed=True, + ) + + def _agent_lane_frontier_hint( *, goal_id: str, - agent_identity: dict[str, Any] | None, - agent_todo_summary: dict[str, Any] | None, - agent_lane_next_action: dict[str, Any] | None, - agent_scope_frontier: dict[str, Any] | None, - work_lane_contract: dict[str, Any] | None, -) -> dict[str, Any] | None: + agent_identity: Mapping[str, object] | None, + agent_todo_summary: Mapping[str, object] | None, + agent_lane_next_action: Mapping[str, object] | None, + agent_scope_frontier: Mapping[str, object] | None, + work_lane_contract: dict[str, object] | None, +) -> dict[str, object] | None: if not _agent_identity_has_scoped_lane(agent_identity): return None agent_id = normalize_todo_claimed_by(agent_identity.get("agent_id")) if not agent_id: return None - def build_hint( - decision: AgentLaneFrontierHintDecision, - *, - source: str, - reason_code: str, - target_todo_id: str | None = None, - quiet_noop_allowed: bool, - next_cli_action: str | None = None, - ) -> dict[str, Any]: - hint: dict[str, Any] = { - "schema_version": AGENT_LANE_FRONTIER_HINT_SCHEMA_VERSION, - "decision": decision.value, - "agent_id": agent_id, - "agent_model": "peer_v1", - "source": source, - "reason_code": reason_code, - "quiet_noop_allowed": quiet_noop_allowed, - "uses_structured_frontier": True, - } - if target_todo_id: - hint["target_todo_id"] = target_todo_id - if next_cli_action: - hint["next_cli_action"] = next_cli_action - return hint - if isinstance(agent_lane_next_action, dict): selected_by = str(agent_lane_next_action.get("selected_by") or "") claim_required = agent_lane_next_action.get("claim_required_before_work") is True target_todo_id = normalize_todo_id(agent_lane_next_action.get("todo_id")) if selected_by == "unclaimed_todo" or claim_required: - action = None - if target_todo_id: - action = ( - f"loopx todo claim --goal-id {goal_id} --todo-id {target_todo_id} " - f"--claimed-by {agent_id} --agent-id {agent_id}" - ) - return build_hint( + return _build_frontier_hint( + agent_id, AgentLaneFrontierHintDecision.CLAIM_UNOWNED_IN_SCOPE, source="agent_lane_next_action", reason_code="unclaimed_advancement_selected", target_todo_id=target_todo_id, - quiet_noop_allowed=False, - next_cli_action=action, - ) - - if work_lane_contract_is_due_monitor_attempt(work_lane_contract): - return None - if work_lane_contract_requires_current_agent_attempt(work_lane_contract): - return None - - frontier = agent_scope_frontier if isinstance(agent_scope_frontier, dict) else {} - frontier_action = _agent_scope_frontier_action(frontier.get("action")) - if frontier_action == AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED: - cleared_todo_id = _first_compact_todo_id( - frontier.get("cleared_without_successor_handoff_gates") - ) - if cleared_todo_id: - return build_hint( - AgentLaneFrontierHintDecision.RECORD_NO_FOLLOWUP, - source="agent_scope_frontier", - reason_code="cleared_handoff_without_successor", - target_todo_id=cleared_todo_id, - quiet_noop_allowed=False, next_cli_action=( - f"loopx todo complete --goal-id {goal_id} --todo-id {cleared_todo_id} " - f"--agent-id {agent_id} --no-follow-up " - "--evidence ''" - ), - ) - if frontier.get("dependency_cycle_candidates"): - # The typed replan and its CLI contract carry the repair. None of - # the legacy hints describes dependency repair without suggesting - # unrelated work, so do not manufacture an add-next hint. - return None - monitor_candidates = ( - frontier.get("monitor_blocked_resume_candidates") - if isinstance(frontier.get("monitor_blocked_resume_candidates"), list) - else [] - ) - monitor_candidate = ( - monitor_candidates[0] - if monitor_candidates and isinstance(monitor_candidates[0], dict) - else {} - ) - monitor_blocker_id = normalize_todo_id( - monitor_candidate.get("blocking_monitor_todo_id") - ) - if monitor_candidate: - target_todo_id = normalize_todo_id(monitor_candidate.get("todo_id")) - return build_hint( - AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, - source="agent_scope_frontier", - reason_code="resume_blocked_by_open_monitor", - target_todo_id=target_todo_id or monitor_blocker_id, - quiet_noop_allowed=False, - next_cli_action=( - f"loopx todo complete --goal-id {goal_id} --todo-id {monitor_blocker_id} " - f"--agent-id {agent_id} --evidence ''" - if monitor_blocker_id + f"loopx todo claim --goal-id {goal_id} --todo-id {target_todo_id} " + f"--claimed-by {agent_id} --agent-id {agent_id}" + if target_todo_id else None ), ) - deferred_todo_id = _first_compact_todo_id(frontier.get("deferred_resume_candidates")) - route_todo_id = _first_compact_todo_id( - frontier.get("route_continuation_replan_candidates") - ) - route_candidates = ( - frontier.get("route_continuation_replan_candidates") - if isinstance(frontier.get("route_continuation_replan_candidates"), list) - else [] - ) - route_candidate = ( - route_candidates[0] - if route_candidates and isinstance(route_candidates[0], dict) - else {} - ) - route_target = ( - route_todo_id - or normalize_todo_id(route_candidate.get("route_id")) - or normalize_todo_id(route_candidate.get("route_key")) - ) - if route_candidate: - return build_hint( - AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, - source="agent_scope_frontier", - reason_code="route_continuation_replan_required", - target_todo_id=route_target, - quiet_noop_allowed=False, - next_cli_action=( - f"loopx todo add --goal-id {goal_id} --role agent " - "--text ''" - ), - ) - return build_hint( - AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, - source="agent_scope_frontier", - reason_code="successor_replan_required", - target_todo_id=deferred_todo_id, - quiet_noop_allowed=False, - ) - if frontier_action in { - AgentScopeFrontierAction.AGENT_SCOPE_WAIT, - AgentScopeFrontierAction.REASSIGNMENT_REQUIRED, - }: - blocked_todo_id = _first_compact_todo_id(frontier.get("blocked_todo_wait_candidates")) - if blocked_todo_id: - return build_hint( - AgentLaneFrontierHintDecision.QUIET_NOOP_BLOCKER, - source="agent_scope_frontier", - reason_code="current_agent_blocker", - target_todo_id=blocked_todo_id, - quiet_noop_allowed=True, - ) - blocked_successor_todo_id = _first_compact_todo_id( - frontier.get("blocked_successor_wait_candidates") - ) - if blocked_successor_todo_id: - return build_hint( - AgentLaneFrontierHintDecision.QUIET_NOOP_BLOCKER, - source="agent_scope_frontier", - reason_code="blocked_successor_resume_pending", - target_todo_id=blocked_successor_todo_id, - quiet_noop_allowed=True, - ) - blocker_todo_id = _first_compact_todo_id(frontier.get("blocking_handoff_gates")) - if not blocker_todo_id: - blocker_todo_id = _first_compact_todo_id(frontier.get("other_agent_claimed_items")) - if blocker_todo_id: - return build_hint( - AgentLaneFrontierHintDecision.QUIET_NOOP_BLOCKER, - source="agent_scope_frontier", - reason_code="blocked_by_other_agent_frontier", - target_todo_id=blocker_todo_id, - quiet_noop_allowed=True, - ) - return build_hint( - AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, - source="agent_scope_frontier", - reason_code="no_current_agent_advancement_todo", - quiet_noop_allowed=True, - ) + if ( + work_lane_contract_is_due_monitor_attempt(work_lane_contract) + or work_lane_contract_requires_current_agent_attempt(work_lane_contract) + ): + return None + frontier = _as_dict(agent_scope_frontier) + frontier_action = _agent_scope_frontier_action(frontier.get("action")) + if frontier_action == AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED: + return _successor_replan_frontier_hint(frontier, goal_id=goal_id, agent_id=agent_id) + if frontier_action in {AgentScopeFrontierAction.AGENT_SCOPE_WAIT, AgentScopeFrontierAction.REASSIGNMENT_REQUIRED}: + return _wait_frontier_hint(frontier, agent_id=agent_id) if frontier_action == AgentScopeFrontierAction.AGENT_SCOPE_EXHAUSTED: - return build_hint( + return _build_frontier_hint( + agent_id, AgentLaneFrontierHintDecision.ADD_NEXT_ADVANCEMENT, - source="agent_scope_frontier", reason_code="agent_scope_exhausted", quiet_noop_allowed=True, ) - if not isinstance(agent_todo_summary, dict): + if not isinstance(agent_todo_summary, Mapping): return None - current_advancement_count = int( - agent_todo_summary.get("current_agent_claimed_advancement_count") or 0 - ) - current_monitor_count = int(agent_todo_summary.get("current_agent_claimed_monitor_count") or 0) + current_advancement_count = _int_value(agent_todo_summary.get("current_agent_claimed_advancement_count")) + current_monitor_count = _int_value(agent_todo_summary.get("current_agent_claimed_monitor_count")) unclaimed_count = _selectable_unclaimed_advancement_count(agent_todo_summary) lane = str(work_lane_contract.get("lane") or "") if isinstance(work_lane_contract, dict) else "" if current_advancement_count == 0 and unclaimed_count == 0 and current_monitor_count > 0: - return build_hint( + return _build_frontier_hint( + agent_id, AgentLaneFrontierHintDecision.QUIET_NOOP_BLOCKER, source="agent_todo_summary", reason_code="only_current_agent_monitor_work_remains", @@ -703,116 +609,97 @@ def build_hint( return None -def _agent_scope_deferred_resume_candidates( - agent_todo_summary: dict[str, Any], - *, - agent_id: str | None, -) -> list[dict[str, Any]]: - candidates: list[dict[str, Any]] = [] - for key in ( - "current_agent_deferred_resume_candidates", - "unclaimed_deferred_resume_candidates", - ): - value = agent_todo_summary.get(key) - if isinstance(value, list): - candidates.extend(item for item in value if isinstance(item, dict)) - if not candidates: - value = agent_todo_summary.get("deferred_resume_candidates") - if isinstance(value, list): - for item in value: - if not isinstance(item, dict): - continue - if not agent_scope_item_claimed_by_agent_or_unclaimed( - item, - agent_id=agent_id, - ): - continue - candidates.append(item) - - unique: list[dict[str, Any]] = [] - seen: set[str] = set() - for item in candidates: - if todo_item_excludes_agent(item, agent_id=agent_id): - continue - if item.get("resume_ready") is not True: - continue - if not todo_item_is_deferred(item): - continue - identity = str(item.get("todo_id") or item.get("index") or item.get("text") or "") - if identity in seen: - continue - seen.add(identity) - unique.append(item) - return sorted(compact_todo_summary_items(unique, strip_text=True), key=_todo_projection_sort_key) - - -def _agent_scope_monitor_blocked_resume_candidates( - agent_todo_summary: dict[str, Any] | None, +def _select_and_compact_candidates( + items: Sequence[dict[str, object]], *, - agent_id: str | None, + predicate: Callable[[dict[str, object]], bool], + identity_keys: tuple[str, ...] = ("todo_id", "index", "text"), + require_identity: bool = False, + copy_fields: tuple[str, ...] = (), + copy_truthy_only: bool = False, + defaults: Mapping[str, object] | None = None, ) -> list[dict[str, Any]]: - if not isinstance(agent_todo_summary, dict): - return [] - candidates: list[dict[str, Any]] = [] - if agent_id: - for key in ( - "current_agent_monitor_blocked_resume_candidates", - "unclaimed_monitor_blocked_resume_candidates", - ): - value = agent_todo_summary.get(key) - if isinstance(value, list): - candidates.extend(item for item in value if isinstance(item, dict)) - else: - value = agent_todo_summary.get("monitor_blocked_resume_candidates") - if isinstance(value, list): - candidates.extend(item for item in value if isinstance(item, dict)) - - unique: list[dict[str, Any]] = [] + """Filter, deduplicate, compact, and sort todo candidate records.""" + unique: list[dict[str, object]] = [] seen: set[str] = set() - for item in candidates: - if todo_item_excludes_agent(item, agent_id=agent_id): - continue - if _todo_task_class(item) != TODO_TASK_CLASS_ADVANCEMENT: - continue - if item.get("resume_ready") is not False: + for item in items: + if not predicate(item): continue - # The typed resume-planning owner has already diagnosed and selected - # this repair lane. This consumer keeps executor scope and presentation, - # not a second interpretation of condition target/class/status. - identity = str(item.get("todo_id") or item.get("index") or item.get("text") or "") - if identity in seen: + identity = _todo_identity(item, keys=identity_keys) + if (require_identity and not identity) or identity in seen: continue seen.add(identity) unique.append(item) compacts = compact_todo_summary_items(unique, strip_text=True) for item, compact in zip(unique, compacts, strict=True): - if item.get("blocking_monitor_todo_id"): - compact["blocking_monitor_todo_id"] = item["blocking_monitor_todo_id"] - return sorted(compacts, key=_todo_projection_sort_key) + if defaults: + compact.update(defaults) + for field in copy_fields: + value = item.get(field) + if value if copy_truthy_only else value is not None: + compact[field] = value + return sorted(compacts, key=todo_presentation_sort_key) -def _agent_scope_cleared_without_successor_handoff_gates( - agent_todo_summary: dict[str, Any], +def _collect_lane_or_fallback( + summary: Mapping[str, object], *, - agent_id: str, + lane_keys: tuple[str, ...], + fallback_key: str, + fallback_predicate: Callable[[dict[str, object]], bool], +) -> list[dict[str, object]]: + """Collect candidate rows from lane keys, falling back when all lane lists are empty.""" + candidates = [item for key in lane_keys for item in _dict_items(summary.get(key))] + if candidates: + return candidates + return [item for item in _dict_items(summary.get(fallback_key)) if fallback_predicate(item)] + + +def _agent_scope_deferred_resume_candidates( + agent_todo_summary: Mapping[str, object], *, agent_id: str | None ) -> list[dict[str, Any]]: - unique = _agent_scope_handoff_gates_by_state( + candidates = _collect_lane_or_fallback( agent_todo_summary, - agent_id=agent_id, - gate_state=HandoffGateState.CLEARED_WITHOUT_SUCCESSOR.value, - preferred_key="current_agent_cleared_without_successor_handoff_gates", + lane_keys=("current_agent_deferred_resume_candidates", "unclaimed_deferred_resume_candidates"), + fallback_key="deferred_resume_candidates", + fallback_predicate=lambda item: agent_scope_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id), ) - return sorted( - unique, - key=lambda item: ( - -int(item.get("index") or 0), - str(item.get("todo_id") or ""), + return _select_and_compact_candidates( + candidates, + predicate=lambda item: ( + not todo_item_excludes_agent(item, agent_id=agent_id) + and item.get("resume_ready") is True + and todo_item_is_deferred(item) + ), + ) + + +def _agent_scope_monitor_blocked_resume_candidates( + agent_todo_summary: Mapping[str, object] | None, *, agent_id: str | None +) -> list[dict[str, Any]]: + if not isinstance(agent_todo_summary, Mapping): + return [] + keys = ( + ("current_agent_monitor_blocked_resume_candidates", "unclaimed_monitor_blocked_resume_candidates") + if agent_id + else ("monitor_blocked_resume_candidates",) + ) + candidates = [item for key in keys for item in _dict_items(agent_todo_summary.get(key))] + # The typed resume-planning owner already selected this repair lane; preserve executor scope only. + return _select_and_compact_candidates( + candidates, + predicate=lambda item: ( + not todo_item_excludes_agent(item, agent_id=agent_id) + and _todo_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT + and item.get("resume_ready") is False ), + copy_fields=("blocking_monitor_todo_id",), + copy_truthy_only=True, ) def _agent_scope_handoff_gates_by_state( - agent_todo_summary: dict[str, Any], + agent_todo_summary: Mapping[str, object], *, agent_id: str | None, gate_state: str, @@ -820,34 +707,24 @@ def _agent_scope_handoff_gates_by_state( ) -> list[dict[str, Any]]: if not agent_id: return [] - gates = agent_todo_summary.get(preferred_key) - if not isinstance(gates, list): - gates = agent_todo_summary.get("handoff_gates") - if not isinstance(gates, list): - return [] + raw_gates = agent_todo_summary.get(preferred_key) + if not isinstance(raw_gates, list): + raw_gates = agent_todo_summary.get("handoff_gates") selected: list[dict[str, Any]] = [] seen: set[str] = set() - for item in gates: - if not isinstance(item, dict): + for item in _dict_items(raw_gates): + if agent_id not in agent_scope_item_excluded_agents(item) or item.get("gate_state") != gate_state: continue - if agent_id not in agent_scope_item_excluded_agents(item): - continue - if item.get("gate_state") != gate_state: - continue - identity = str(item.get("todo_id") or item.get("index") or item.get("text") or "") + identity = _todo_identity(item) if identity in seen: continue seen.add(identity) - compact = dict(item) - compact["text"] = str(item.get("text") or "").strip() - selected.append(compact) + selected.append({**item, "text": str(item.get("text") or "").strip()}) return selected def agent_scope_blocking_handoff_gates( - agent_todo_summary: dict[str, Any], - *, - agent_id: str | None, + agent_todo_summary: Mapping[str, object], *, agent_id: str | None ) -> list[dict[str, Any]]: selected = _agent_scope_handoff_gates_by_state( agent_todo_summary, @@ -855,112 +732,72 @@ def agent_scope_blocking_handoff_gates( gate_state=HandoffGateState.BLOCKING.value, preferred_key="current_agent_handoff_gates", ) - return sorted(selected, key=_todo_projection_sort_key) - - -def _agent_scope_blocking_handoff_gates( - agent_todo_summary: dict[str, Any], - *, - agent_id: str, -) -> list[dict[str, Any]]: - return agent_scope_blocking_handoff_gates(agent_todo_summary, agent_id=agent_id) - - -def _route_continuation_candidate_matches_agent( - item: dict[str, Any], - *, - agent_id: str, -) -> bool: - return agent_scope_item_matches_agent_or_unclaimed(item, agent_id=agent_id) + return sorted(selected, key=todo_presentation_sort_key) def _agent_scope_route_continuation_replan_candidates( - agent_todo_summary: dict[str, Any], - *, - agent_id: str, + agent_todo_summary: Mapping[str, object], *, agent_id: str ) -> list[dict[str, Any]]: - candidates: list[dict[str, Any]] = [] - for key in ( - "current_agent_route_continuation_replan_candidates", - "unclaimed_route_continuation_replan_candidates", - ): - value = agent_todo_summary.get(key) - if isinstance(value, list): - candidates.extend(item for item in value if isinstance(item, dict)) - if not candidates: - value = agent_todo_summary.get("route_continuation_replan_candidates") - if isinstance(value, list): - for item in value: - if not isinstance(item, dict): - continue - if not _route_continuation_candidate_matches_agent(item, agent_id=agent_id): - continue - candidates.append(item) - - unique: list[dict[str, Any]] = [] - seen: set[str] = set() - for item in candidates: - if not _route_continuation_candidate_matches_agent( - item, - agent_id=agent_id, - ): - continue - if item.get("route_continuation_replan_required") is False: - continue - identity = str( - item.get("todo_id") - or item.get("route_id") - or item.get("route_key") - or item.get("index") - or item.get("text") - or "" - ) - if not identity or identity in seen: - continue - seen.add(identity) - unique.append(item) - compacts = compact_todo_summary_items(unique, strip_text=True) - for item, compact in zip(unique, compacts, strict=True): - compact["route_continuation_replan_required"] = True - if item.get("route_continuation_reason") is not None: - compact["route_continuation_reason"] = item.get("route_continuation_reason") - if item.get("route_id") is not None: - compact["route_id"] = item.get("route_id") - if item.get("route_key") is not None: - compact["route_key"] = item.get("route_key") - return sorted(compacts, key=_todo_projection_sort_key) + candidates = _collect_lane_or_fallback( + agent_todo_summary, + lane_keys=( + "current_agent_route_continuation_replan_candidates", + "unclaimed_route_continuation_replan_candidates", + ), + fallback_key="route_continuation_replan_candidates", + fallback_predicate=lambda item: agent_scope_item_matches_agent_or_unclaimed(item, agent_id=agent_id), + ) + return _select_and_compact_candidates( + candidates, + predicate=lambda item: ( + agent_scope_item_matches_agent_or_unclaimed(item, agent_id=agent_id) + and item.get("route_continuation_replan_required") is not False + ), + identity_keys=("todo_id", "route_id", "route_key", "index", "text"), + require_identity=True, + copy_fields=("route_continuation_reason", "route_id", "route_key"), + defaults={"route_continuation_replan_required": True}, + ) @dataclass(frozen=True) class _AgentScopeNoCandidateContext: agent_id: str - summary: dict[str, Any] + summary: Mapping[str, object] current_agent_count: int unclaimed_count: int has_advancement_contract: bool - @property - def candidate_counts(self) -> dict[str, int]: + def counts(self, **extra: int) -> dict[str, int]: return { "current_agent_claimed_advancement_count": self.current_agent_count, "unclaimed_advancement_count": self.unclaimed_count, + **extra, } +def _blocking_handoff_copy(agent_id: str, owner: str) -> tuple[str, str]: + """Return shared ``reason`` and ``recommended_action`` prose for blocking handoffs.""" + reason = ( + f"current agent {agent_id} has no current/unclaimed advancement " + f"candidate; blocking handoff work is claimed by {owner}" + ) + recommended_action = ( + f"Keep {agent_id} active but quiet: wait for {owner} to finish the " + "blocking handoff, reassign it, or create a concrete current-agent/" + "unclaimed advancement todo before delivery." + ) + return reason, recommended_action + + def _selected_candidate_priority_frontier( - *, - agent_id: str, - summary: dict[str, Any], - selected: dict[str, Any], -) -> dict[str, Any] | None: + *, agent_id: str, summary: Mapping[str, object], selected: dict[str, object] +) -> dict[str, object] | None: candidates = _agent_scope_deferred_resume_candidates(summary, agent_id=agent_id) - if not candidates: - return None - first = candidates[0] - if _todo_projection_sort_key(first)[0] >= _todo_projection_sort_key(selected)[0]: + if not candidates or todo_presentation_sort_key(candidates[0])[0] >= todo_presentation_sort_key(selected)[0]: return None - candidate_todo_id = str(first.get("todo_id") or "").strip() or "" - selected_todo_id = str(selected.get("todo_id") or "").strip() or "" + candidate_todo_id = _todo_label(candidates[0], fallback="") + selected_todo_id = _todo_label(selected, fallback="") return build_agent_scope_frontier_payload( agent_id=agent_id, action=AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED, @@ -976,81 +813,51 @@ def _selected_candidate_priority_frontier( f"supersede, or record a no-follow-up rationale for {candidate_todo_id}." ), requires_replan=True, - candidate_counts={ - "deferred_resume_candidate_count": len(candidates), - "preempted_open_candidate_count": 1, - }, + candidate_counts={"deferred_resume_candidate_count": len(candidates), "preempted_open_candidate_count": 1}, extra_fields={ "deferred_resume_candidates": candidates[:3], - "preempted_open_candidate": compact_todo_summary_item( - selected, - text=str(selected.get("text") or "").strip(), - ), + "preempted_open_candidate": compact_todo_summary_item(selected, text=str(selected.get("text") or "").strip()), "priority_preemption": True, }, ) -def _agent_scope_advancement_counts( - summary: dict[str, Any], - *, - agent_id: str, -) -> tuple[int, int]: +def _agent_scope_advancement_counts(summary: Mapping[str, object], *, agent_id: str) -> tuple[int, int]: current = max( - int(summary.get("current_agent_claimed_advancement_count") or 0), - _count_advancement_items( - summary.get("current_agent_claimed_advancement_items"), - claimed_by=agent_id, - ), + _int_value(summary.get("current_agent_claimed_advancement_count")), + agent_scope_count_advancement_items(summary.get("current_agent_claimed_advancement_items"), claimed_by=agent_id), ) unclaimed = _selectable_unclaimed_advancement_count(summary) executable_items = summary.get("executable_backlog_items") if isinstance(executable_items, list): - current = max( - current, - _count_advancement_items(executable_items, claimed_by=agent_id), - ) - unclaimed = _count_advancement_items( - executable_items, - claimed_by="__unclaimed__", - ) + current = max(current, agent_scope_count_advancement_items(executable_items, claimed_by=agent_id)) + unclaimed = agent_scope_count_advancement_items(executable_items, claimed_by="__unclaimed__") return current, unclaimed -def _dependency_cycle_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: - repair = project_todo_resume_planning( - context.summary, agent_id=context.agent_id, - ).get("dependency_cycle_replan") +def _dependency_cycle_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: + repair = project_todo_resume_planning(context.summary, agent_id=context.agent_id).get("dependency_cycle_replan") if not repair: return None return build_agent_scope_frontier_payload( agent_id=context.agent_id, action=AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED, - quiet_noop_allowed=False, requires_replan=True, - spend_policy=repair["spend_policy"], reason=repair["reason"], + quiet_noop_allowed=False, + requires_replan=True, + spend_policy=repair["spend_policy"], + reason=repair["reason"], recommended_action=repair["recommended_action"], - candidate_counts={**context.candidate_counts, "dependency_cycle_count": repair["count"]}, + candidate_counts=context.counts(dependency_cycle_count=repair["count"]), extra_fields={"dependency_cycle_candidates": repair["candidates"]}, ) -def _monitor_blocked_resume_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: - candidates = _agent_scope_monitor_blocked_resume_candidates( - context.summary, - agent_id=context.agent_id, - ) +def _monitor_blocked_resume_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: + candidates = _agent_scope_monitor_blocked_resume_candidates(context.summary, agent_id=context.agent_id) if not candidates: return None - first = candidates[0] - candidate_id = str(first.get("todo_id") or "").strip() or "" - monitor_id = ( - str(first.get("blocking_monitor_todo_id") or "").strip() - or "" - ) + candidate_id = _todo_label(candidates[0], fallback="") + monitor_id = _todo_label(candidates[0], keys=("blocking_monitor_todo_id",), fallback="") return build_agent_scope_frontier_payload( agent_id=context.agent_id, action=AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED, @@ -1067,24 +874,16 @@ def _monitor_blocked_resume_frontier( "a non-blocking monitor contract before delivery." ), requires_replan=True, - candidate_counts={ - **context.candidate_counts, - "monitor_blocked_resume_candidate_count": len(candidates), - }, + candidate_counts=context.counts(monitor_blocked_resume_candidate_count=len(candidates)), extra_fields={"monitor_blocked_resume_candidates": candidates[:3]}, ) -def _deferred_resume_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: - candidates = _agent_scope_deferred_resume_candidates( - context.summary, - agent_id=context.agent_id, - ) +def _deferred_resume_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: + candidates = _agent_scope_deferred_resume_candidates(context.summary, agent_id=context.agent_id) if not candidates: return None - candidate_id = str(candidates[0].get("todo_id") or "").strip() or "" + candidate_id = _todo_label(candidates[0], fallback="") return build_agent_scope_frontier_payload( agent_id=context.agent_id, action=AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED, @@ -1099,46 +898,40 @@ def _deferred_resume_frontier( f"record a no-follow-up rationale for {candidate_id}." ), requires_replan=True, - candidate_counts={ - **context.candidate_counts, - "deferred_resume_candidate_count": len(candidates), - }, + candidate_counts=context.counts(deferred_resume_candidate_count=len(candidates)), extra_fields={"deferred_resume_candidates": candidates[:3]}, ) -def _blocked_todo_wait_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: - planning = project_todo_resume_planning(context.summary, agent_id=context.agent_id) - blocked_items = planning.get("blocked_wait_items") - if blocked_items: - return build_agent_scope_frontier_payload( - agent_id=context.agent_id, - action=AgentScopeFrontierAction.AGENT_SCOPE_WAIT, - quiet_noop_allowed=True, - spend_policy="no quota spend while scoped work is blocked", - reason=f"current agent {context.agent_id} has blocked work and no runnable candidate", - recommended_action=( - "Wait for the blocker to be resolved or its resume condition to become ready; " - "recheck when the Todo state or available work changes." - ), - candidate_counts={**context.candidate_counts, "blocked_todo_wait_count": len(blocked_items)}, - extra_fields={"blocked_todo_wait_candidates": blocked_items[:3]}, - ) - return None +def _blocked_todo_wait_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: + blocked_items = project_todo_resume_planning(context.summary, agent_id=context.agent_id).get("blocked_wait_items") + if not blocked_items: + return None + return build_agent_scope_frontier_payload( + agent_id=context.agent_id, + action=AgentScopeFrontierAction.AGENT_SCOPE_WAIT, + quiet_noop_allowed=True, + spend_policy="no quota spend while scoped work is blocked", + reason=f"current agent {context.agent_id} has blocked work and no runnable candidate", + recommended_action=( + "Wait for the blocker to be resolved or its resume condition to become ready; " + "recheck when the Todo state or available work changes." + ), + candidate_counts=context.counts(blocked_todo_wait_count=len(blocked_items)), + extra_fields={"blocked_todo_wait_candidates": blocked_items[:3]}, + ) -def _blocked_successor_wait_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: +def _blocked_successor_wait_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: planning = project_todo_resume_planning(context.summary, agent_id=context.agent_id) candidates = planning["blocked_successor_items"] if not candidates: return None - first = candidates[0] - candidate_id = str(first.get("todo_id") or "").strip() or "" - resume_when = str(first.get("resume_when") or "").strip() + candidate_id = _todo_label(candidates[0], fallback="") + resume_when = str(candidates[0].get("resume_when") or "").strip() + extra_fields: dict[str, object] = {"blocked_successor_wait_candidates": candidates[:3]} + if "automatic_resume_todo" in planning: + extra_fields["automatic_resume_todo"] = planning["automatic_resume_todo"] return build_agent_scope_frontier_payload( agent_id=context.agent_id, action=AgentScopeFrontierAction.AGENT_SCOPE_WAIT, @@ -1146,45 +939,23 @@ def _blocked_successor_wait_frontier( spend_policy="no quota spend while an exact successor resume condition is pending", reason=( f"current agent {context.agent_id} has exact blocked successor {candidate_id} " - f"waiting on {resume_when}; another successor replan would duplicate the " - "existing route" + f"waiting on {resume_when}; another successor replan would duplicate the existing route" ), recommended_action=( f"Keep {context.agent_id} active but quiet until {resume_when} becomes ready; " "then resume ordinary todo/deferred-successor routing automatically." ), requires_replan=False, - candidate_counts={ - **context.candidate_counts, - "blocked_successor_wait_count": len(candidates), - }, - extra_fields={ - "blocked_successor_wait_candidates": candidates[:3], - **({"automatic_resume_todo": planning["automatic_resume_todo"]} - if "automatic_resume_todo" in planning else {}), - }, + candidate_counts=context.counts(blocked_successor_wait_count=len(candidates)), + extra_fields=extra_fields, ) -def _route_continuation_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: - candidates = _agent_scope_route_continuation_replan_candidates( - context.summary, - agent_id=context.agent_id, - ) +def _route_continuation_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: + candidates = _agent_scope_route_continuation_replan_candidates(context.summary, agent_id=context.agent_id) if not candidates: return None - first = candidates[0] - route_label = ( - str( - first.get("route_id") - or first.get("route_key") - or first.get("todo_id") - or "" - ).strip() - or "" - ) + route_label = _todo_label(candidates[0], keys=("route_id", "route_key", "todo_id"), fallback="") return build_agent_scope_frontier_payload( agent_id=context.agent_id, action=AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED, @@ -1192,8 +963,7 @@ def _route_continuation_frontier( spend_policy="spend once after validated route continuation replan/todo writeback", reason=( f"current agent {context.agent_id} has no open current/unclaimed advancement " - "candidate, but the route continuation projection requires a successor " - f"replan for {route_label}" + f"candidate, but the route continuation projection requires a successor replan for {route_label}" ), recommended_action=( "Run a bounded route continuation replan before quiet wait: create or claim " @@ -1201,50 +971,27 @@ def _route_continuation_frontier( f"{route_label}, or record an explicit no-follow-up rationale." ), requires_replan=True, - candidate_counts={ - **context.candidate_counts, - "route_continuation_replan_candidate_count": len(candidates), - }, + candidate_counts=context.counts(route_continuation_replan_candidate_count=len(candidates)), extra_fields={"route_continuation_replan_candidates": candidates[:3]}, ) -def _blocking_handoff_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: - gates = _agent_scope_blocking_handoff_gates( - context.summary, - agent_id=context.agent_id, - ) +def _blocking_handoff_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: + gates = agent_scope_blocking_handoff_gates(context.summary, agent_id=context.agent_id) if not gates: return None - claimants = sorted( - { - claimed_by - for item in gates - for claimed_by in [agent_scope_item_claimed_by(item)] - if claimed_by - } + claimants = _sorted_claimants(gates) + reason, recommended_action = _blocking_handoff_copy( + context.agent_id, ", ".join(claimants) or "the owning agent" ) - owner = ", ".join(claimants) or "the owning agent" return build_agent_scope_frontier_payload( agent_id=context.agent_id, action=AgentScopeFrontierAction.AGENT_SCOPE_WAIT, quiet_noop_allowed=True, spend_policy="no quota spend while the current agent has no in-scope runnable candidate", - reason=( - f"current agent {context.agent_id} has no current/unclaimed advancement " - f"candidate; blocking handoff work is claimed by {owner}" - ), - recommended_action=( - f"Keep {context.agent_id} active but quiet: wait for {owner} to finish the " - "blocking handoff, reassign it, or create a concrete current-agent/" - "unclaimed advancement todo before delivery." - ), - candidate_counts={ - **context.candidate_counts, - "blocking_handoff_gate_count": len(gates), - }, + reason=reason, + recommended_action=recommended_action, + candidate_counts=context.counts(blocking_handoff_gate_count=len(gates)), extra_fields={ "other_claimants": claimants, "blocking_handoff_claimants": claimants, @@ -1253,18 +1000,20 @@ def _blocking_handoff_frontier( ) -def _cleared_handoff_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: - gates = _agent_scope_cleared_without_successor_handoff_gates( - context.summary, - agent_id=context.agent_id, +def _cleared_handoff_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: + gates = sorted( + _agent_scope_handoff_gates_by_state( + context.summary, + agent_id=context.agent_id, + gate_state=HandoffGateState.CLEARED_WITHOUT_SUCCESSOR.value, + preferred_key="current_agent_cleared_without_successor_handoff_gates", + ), + key=lambda item: (-int(item.get("index") or 0), str(item.get("todo_id") or "")), ) if not gates: return None - first = gates[0] - blocker_id = str(first.get("todo_id") or "").strip() or "" - unblocks_id = normalize_todo_id(first.get("unblocks_todo_id")) + blocker_id = _todo_label(gates[0], fallback="") + unblocks_id = normalize_todo_id(gates[0].get("unblocks_todo_id")) target_text = f" for unblocked todo {unblocks_id}" if unblocks_id else "" return build_agent_scope_frontier_payload( agent_id=context.agent_id, @@ -1282,58 +1031,26 @@ def _cleared_handoff_frontier( "todo, or record an explicit no-follow-up rationale." ), requires_replan=True, - candidate_counts={ - **context.candidate_counts, - "cleared_without_successor_handoff_count": len(gates), - }, + candidate_counts=context.counts(cleared_without_successor_handoff_count=len(gates)), extra_fields={"cleared_without_successor_handoff_gates": gates[:3]}, ) -def _other_agent_or_exhausted_frontier( - context: _AgentScopeNoCandidateContext, -) -> dict[str, Any] | None: - claimed_items = context.summary.get("claimed_advancement_open_items") - claimed_items = claimed_items if isinstance(claimed_items, list) else [] +def _other_agent_or_exhausted_frontier(context: _AgentScopeNoCandidateContext) -> dict[str, object] | None: other_items = [ item - for item in claimed_items - if isinstance(item, dict) - and _todo_item_is_actionable_open(item) + for item in _dict_items(context.summary.get("claimed_advancement_open_items")) + if _todo_item_is_actionable_open(item) and _todo_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT and agent_scope_item_claimed_by(item) not in {None, "", context.agent_id} ] if not context.has_advancement_contract and not other_items: return None - other_claimants = sorted( - { - claimed_by - for item in other_items - for claimed_by in [agent_scope_item_claimed_by(item)] - if claimed_by - } - ) - blocking_claimants = sorted( - { - claimed_by - for item in other_items - if context.agent_id in agent_scope_item_excluded_agents(item) - for claimed_by in [agent_scope_item_claimed_by(item)] - if claimed_by - } - ) + other_claimants = _sorted_claimants(other_items) + blocking_claimants = _sorted_claimants(other_items, excluded_agent=context.agent_id) if blocking_claimants: action = AgentScopeFrontierAction.AGENT_SCOPE_WAIT - owner = ", ".join(blocking_claimants) - reason = ( - f"current agent {context.agent_id} has no current/unclaimed advancement " - f"candidate; blocking handoff work is claimed by {owner}" - ) - recommended_action = ( - f"Keep {context.agent_id} active but quiet: wait for {owner} to finish the " - "blocking handoff, reassign it, or create a concrete current-agent/" - "unclaimed advancement todo before delivery." - ) + reason, recommended_action = _blocking_handoff_copy(context.agent_id, ", ".join(blocking_claimants)) elif other_items: action = AgentScopeFrontierAction.REASSIGNMENT_REQUIRED owner = ", ".join(other_claimants) or "the owning agent" @@ -1343,8 +1060,7 @@ def _other_agent_or_exhausted_frontier( ) recommended_action = ( f"Keep {context.agent_id} active but quiet: wait for {owner} to finish, " - "reassign, or create a concrete current-agent/unclaimed advancement todo " - "before delivery." + "reassign, or create a concrete current-agent/unclaimed advancement todo before delivery." ) else: action = AgentScopeFrontierAction.AGENT_SCOPE_EXHAUSTED @@ -1356,8 +1072,7 @@ def _other_agent_or_exhausted_frontier( f"Keep {context.agent_id} active but quiet until LoopX projects a concrete " "current-agent or unclaimed advancement todo, or another peer transfers work." ) - claim_scope = context.summary.get("claim_scope") - claim_scope = claim_scope if isinstance(claim_scope, dict) else {} + claim_scope = _as_dict(context.summary.get("claim_scope")) return build_agent_scope_frontier_payload( agent_id=context.agent_id, action=action, @@ -1365,13 +1080,10 @@ def _other_agent_or_exhausted_frontier( spend_policy="no quota spend while the current agent has no in-scope runnable candidate", reason=reason, recommended_action=recommended_action, - candidate_counts={ - **context.candidate_counts, - "other_agent_claimed_advancement_count": len(other_items), - "other_agent_claimed_open_count": int( - claim_scope.get("other_agent_claimed_open_count") or 0 - ), - }, + candidate_counts=context.counts( + other_agent_claimed_advancement_count=len(other_items), + other_agent_claimed_open_count=_int_value(claim_scope.get("other_agent_claimed_open_count")), + ), extra_fields={ "other_claimants": other_claimants, "blocking_handoff_claimants": blocking_claimants, @@ -1395,12 +1107,12 @@ def _other_agent_or_exhausted_frontier( def _agent_scope_no_candidate_frontier( *, - agent_identity: dict[str, Any] | None, - agent_todo_summary: dict[str, Any] | None, - agent_lane_next_action: dict[str, Any] | None, - work_lane_contract: dict[str, Any] | None, + agent_identity: Mapping[str, object] | None, + agent_todo_summary: dict[str, object] | None, + agent_lane_next_action: dict[str, object] | None, + work_lane_contract: dict[str, object] | None, candidate_should_run: bool, - vision_wait_state: dict[str, Any] | None = None, + vision_wait_state: Mapping[str, object] | None = None, ) -> dict[str, Any] | None: if not candidate_should_run or not _agent_identity_has_scoped_lane(agent_identity): return None @@ -1410,28 +1122,19 @@ def _agent_scope_no_candidate_frontier( if work_lane_contract_is_due_monitor_attempt(work_lane_contract): return None if isinstance(agent_lane_next_action, dict): - # Eligibility and real delivery gates have already been qualified by - # the typed action-selection owner. Priority ranks the default route; - # it must not replace an explicitly selected eligible Todo. + # Eligibility and real delivery gates are already qualified by the typed + # action-selection owner; priority must not replace an explicit selection. if agent_lane_next_action.get("selected_by") == "agent_action_selection": return None return _selected_candidate_priority_frontier( - agent_id=agent_id, - summary=agent_todo_summary, - selected=agent_lane_next_action, + agent_id=agent_id, summary=agent_todo_summary, selected=agent_lane_next_action ) if work_lane_contract_requires_current_agent_attempt(work_lane_contract): return None - current_count, unclaimed_count = _agent_scope_advancement_counts( - agent_todo_summary, - agent_id=agent_id, - ) - if vision_wait_state and todo_scoped_runnable_advancement_count( - agent_todo_summary, agent_id=agent_id, - ) == 0: - # A committed retry keeps its unfinished commitment while selection - # proves there is no runnable work. Preserve the exact wait route. + current_count, unclaimed_count = _agent_scope_advancement_counts(agent_todo_summary, agent_id=agent_id) + if vision_wait_state and todo_scoped_runnable_advancement_count(agent_todo_summary, agent_id=agent_id) == 0: + # A committed retry preserves its unfinished wait route when selection proves no runnable work. current_count = unclaimed_count = 0 if current_count > 0 or unclaimed_count > 0: return None @@ -1447,7 +1150,6 @@ def _agent_scope_no_candidate_frontier( ), ) for rule in _AGENT_SCOPE_NO_CANDIDATE_RULES: - frontier = rule(context) - if frontier is not None: + if (frontier := rule(context)) is not None: return frontier return None diff --git a/loopx/control_plane/quota/_supporting_projections.py b/loopx/control_plane/quota/_supporting_projections.py index 847cab99c3..8ea500e1d6 100644 --- a/loopx/control_plane/quota/_supporting_projections.py +++ b/loopx/control_plane/quota/_supporting_projections.py @@ -1,71 +1,388 @@ """Supporting diagnostics shared by active and settled quota packets.""" from __future__ import annotations +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +import re from typing import Any, cast - -from ..agents.agent_scope import _action_scope_tokens_from_text from ..runtime.decision_freshness import decision_freshness_warning as _decision_freshness_warning from ..runtime.promotion_readiness import promotion_readiness_warning as _promotion_readiness_warning +from ..todos.contract import ( + normalize_explicit_todo_task_class, + normalize_required_capabilities, + normalize_required_write_scopes, + normalize_target_capabilities, + normalize_todo_action_kind, + normalize_todo_claimed_by, + normalize_todo_decision_scope, + normalize_todo_id, + normalize_todo_id_list, + normalize_todo_required_decision_scopes, +) from ..todos.user_gate import build_gate_prompt as _build_gate_prompt from .recent_runs import goal_latest_runs as _goal_latest_runs +_LEADING_ACTION_PREFIX_RE = re.compile( + r"^(?:\[[^\]]+\]\s*|todo_[a-z0-9_-]+:\s*|p[0-4]:\s*|(?:agent|user|owner|codex)\s*:\s*)+", + re.IGNORECASE, +) +_BARE_PRIORITY_RE = re.compile(r"^\[?p[0-4]\]?$", re.IGNORECASE) +_LESSON_STRUCTURED_KEYS = ( + "todo_id", + "todo_ids", + "claimed_by", + "agent_id", + "task_class", + "capability_id", + "capability_ids", + "required_capabilities", + "work_lane", + "action_kind", + "target_key", + "scope_key", + "scope_keys", + "target_scopes", + "decision_scope", + "target", + "scope", +) -def _recent_reward_lessons(status_payload: dict[str, Any], *, goal_id: str) -> list[dict[str, Any]]: - lessons: list[dict[str, Any]] = [] - for run in _goal_latest_runs(status_payload, goal_id=goal_id): - reward = cast(dict[str, Any], run.get("human_reward")) if isinstance(run.get("human_reward"), dict) else {} - lesson = cast(dict[str, Any], reward.get("lesson")) if isinstance(reward.get("lesson"), dict) else {} - if not lesson: + +def _normalized_phrase(value: object) -> str: + return " ".join(str(value or "").strip().split()).casefold() + + +def _normalized_action_body(value: object) -> str: + collapsed = " ".join(str(value or "").strip().split()) + stripped = _LEADING_ACTION_PREFIX_RE.sub("", collapsed).strip() + return (stripped or collapsed).casefold() + + +def _string_tokens(value: object) -> set[str]: + items: Iterable[object] = value if isinstance(value, (list, tuple, set)) else (value,) + return {text for item in items if (text := str(item or "").strip().lower())} + + +def _decision_scope_tokens(value: object) -> set[str]: + tokens: set[str] = set() + if normalized := normalize_todo_decision_scope(value): + tokens.add(f"{normalized['kind']}:{normalized['granularity']}:{normalized['scope_key']}") + tokens.add(normalized["scope_key"]) + for entry in normalize_todo_required_decision_scopes(value): + tokens.add(f"{entry['kind']}:{entry['granularity']}:{entry['scope_key']}") + tokens.add(entry["scope_key"]) + return tokens + + +@dataclass(frozen=True, slots=True) +class _SelectionScopeContext: + todo_ids: frozenset[str] + agent_ids: frozenset[str] + task_classes: frozenset[str] + capability_ids: frozenset[str] + work_lane_fields: dict[str, str] + action_kinds: frozenset[str] + target_keys: frozenset[str] + scope_keys: frozenset[str] + + @property + def has_structured_targets(self) -> bool: + return bool( + self.todo_ids + or self.task_classes + or self.capability_ids + or self.work_lane_fields + or self.action_kinds + or self.target_keys + or self.scope_keys + ) + + +def _extract_selection_scope_context( + sources: Sequence[Mapping[str, object] | None], + *, + work_lane: Mapping[str, object] | None, +) -> _SelectionScopeContext: + todo_ids: set[str] = set() + agent_ids: set[str] = set() + task_classes: set[str] = set() + capability_ids: set[str] = set() + action_kinds: set[str] = set() + target_keys: set[str] = set() + scope_keys: set[str] = set() + + def collect_row(row: Mapping[str, object]) -> None: + for key in ("todo_id", "selected_todo_id"): + if todo_id := normalize_todo_id(row.get(key)): + todo_ids.add(todo_id) + for key in ("claimed_by", "agent_id"): + if agent_id := normalize_todo_claimed_by(row.get(key)): + agent_ids.add(agent_id) + for key in ("task_class", "lane"): + if task_class := normalize_explicit_todo_task_class(row.get(key)): + task_classes.add(task_class) + for key in ("capability_id", "capability_ids"): + capability_ids.update(_string_tokens(row.get(key))) + capability_ids.update(normalize_required_capabilities(row.get("required_capabilities"))) + capability_ids.update(normalize_target_capabilities(row.get("target_capabilities"))) + if action_kind := normalize_todo_action_kind(row.get("action_kind")): + action_kinds.add(action_kind) + for key in ("target_key", "route_id", "route_key"): + target_keys.update(_string_tokens(row.get(key))) + scope_keys.update(normalize_required_write_scopes(row.get("required_write_scopes"))) + scope_keys.update(_decision_scope_tokens(row.get("decision_scope"))) + scope_keys.update(_decision_scope_tokens(row.get("required_decision_scopes"))) + for key in ("scope_key", "scope_keys", "target_scopes"): + scope_keys.update(_string_tokens(row.get(key))) + + for source in sources: + if not isinstance(source, Mapping): continue - lessons.append( - { - "generated_at": run.get("generated_at"), - "decision": reward.get("decision"), - "reward": reward.get("reward"), - "kind": lesson.get("kind"), - "summary": lesson.get("summary"), - "avoid": cast(list[Any], lesson.get("avoid")) if isinstance(lesson.get("avoid"), list) else [], - "prefer": cast(list[Any], lesson.get("prefer")) if isinstance(lesson.get("prefer"), list) else [], + collect_row(source) + monitor_due_items = source.get("monitor_due_items") + if isinstance(monitor_due_items, list): + for due_item in monitor_due_items: + if isinstance(due_item, Mapping): + collect_row(due_item) + + work_lane_fields: dict[str, str] = {} + if isinstance(work_lane, Mapping): + collect_row(work_lane) + for key in ("lane", "next_lane", "obligation", "monitor_kind", "selected_todo_id"): + value = str(work_lane.get(key) or "").strip().lower() + if value: + work_lane_fields[key] = value + + return _SelectionScopeContext( + todo_ids=frozenset(todo_ids), + agent_ids=frozenset(agent_ids), + task_classes=frozenset(task_classes), + capability_ids=frozenset(capability_ids), + work_lane_fields=work_lane_fields, + action_kinds=frozenset(action_kinds), + target_keys=frozenset(target_keys), + scope_keys=frozenset(scope_keys), + ) + + +def _merged_lesson_scope(lesson: Mapping[str, object]) -> dict[str, object]: + merged: dict[str, object] = dict(lesson) + for nested_key in ("target", "scope"): + nested = lesson.get(nested_key) + if isinstance(nested, Mapping): + for key, value in nested.items(): + if key not in merged and value is not None: + merged[key] = value + return merged + + +def _match_lesson_structured_scope( + lesson: Mapping[str, object], + context: _SelectionScopeContext, +) -> tuple[bool, dict[str, object]]: + """Evaluate structured scope fields on a lesson against the active selection.""" + fields = _merged_lesson_scope(lesson) + lesson_agents = { + agent + for key in ("claimed_by", "agent_id") + if (agent := normalize_todo_claimed_by(fields.get(key))) + } + if lesson_agents and not (lesson_agents & context.agent_ids): + return True, {} + + lesson_todo_ids = set(normalize_todo_id_list(fields.get("todo_id"))) | set( + normalize_todo_id_list(fields.get("todo_ids")) + ) + lesson_task_class = normalize_explicit_todo_task_class(fields.get("task_class")) + lesson_capabilities = ( + _string_tokens(fields.get("capability_id")) + | _string_tokens(fields.get("capability_ids")) + | set(normalize_required_capabilities(fields.get("required_capabilities"))) + ) + lesson_work_lane = fields.get("work_lane") + lesson_action_kind = normalize_todo_action_kind(fields.get("action_kind")) + lesson_target_keys = _string_tokens(fields.get("target_key")) + lesson_scope_keys = ( + _string_tokens(fields.get("scope_key")) + | _string_tokens(fields.get("scope_keys")) + | _string_tokens(fields.get("target_scopes")) + | _decision_scope_tokens(fields.get("decision_scope")) + ) + + if not ( + lesson_todo_ids + or lesson_task_class + or lesson_capabilities + or lesson_work_lane is not None + or lesson_action_kind + or lesson_target_keys + or lesson_scope_keys + ): + return False, {} + + matched: dict[str, object] = {} + if lesson_agents: + matched["claimed_by"] = sorted(lesson_agents & context.agent_ids)[0] + set_checks: tuple[tuple[str, set[str], frozenset[str]], ...] = ( + ("todo_id", lesson_todo_ids, context.todo_ids), + ("capability_id", lesson_capabilities, context.capability_ids), + ("target_key", lesson_target_keys, context.target_keys), + ("scope_key", lesson_scope_keys, context.scope_keys), + ) + for field_name, required_set, available_set in set_checks: + if required_set: + overlap = sorted(required_set & available_set) + if not overlap: + return True, {} + matched[field_name] = overlap[0] + for field_name, required_value, available_set in ( + ("task_class", lesson_task_class, context.task_classes), + ("action_kind", lesson_action_kind, context.action_kinds), + ): + if required_value: + if required_value not in available_set: + return True, {} + matched[field_name] = required_value + if lesson_work_lane is not None: + if isinstance(lesson_work_lane, Mapping): + expected_pairs = { + str(key): str(val).strip().lower() + for key, val in lesson_work_lane.items() + if val is not None and str(val).strip() } - ) + if not expected_pairs or any( + context.work_lane_fields.get(key) != val + for key, val in expected_pairs.items() + ): + return True, {} + matched["work_lane"] = expected_pairs + else: + lane_value = str(lesson_work_lane or "").strip().lower() + if not lane_value or lane_value not in { + context.work_lane_fields.get("lane"), + context.work_lane_fields.get("obligation"), + }: + return True, {} + matched["work_lane"] = lane_value + + return True, matched + + +def _recent_reward_lessons(status_payload: Mapping[str, object], *, goal_id: str) -> list[dict[str, object]]: + lessons: list[dict[str, object]] = [] + for run in _goal_latest_runs(cast(dict[str, Any], status_payload), goal_id=goal_id): + raw_reward = run.get("human_reward") + reward = raw_reward if isinstance(raw_reward, Mapping) else {} + raw_lesson = reward.get("lesson") + lesson = raw_lesson if isinstance(raw_lesson, Mapping) else {} + if not lesson: + continue + raw_avoid = lesson.get("avoid") + raw_prefer = lesson.get("prefer") + entry: dict[str, object] = { + "generated_at": run.get("generated_at"), + "decision": reward.get("decision"), + "reward": reward.get("reward"), + "kind": lesson.get("kind"), + "summary": lesson.get("summary"), + "avoid": raw_avoid if isinstance(raw_avoid, list) else [], + "prefer": raw_prefer if isinstance(raw_prefer, list) else [], + } + for key in _LESSON_STRUCTURED_KEYS: + if key in lesson and lesson[key] is not None: + entry[key] = lesson[key] + lessons.append(entry) return lessons +def _match_unstructured_avoid( + lesson: Mapping[str, object], + avoid_text: str, + *, + context: _SelectionScopeContext, + structured_keys: frozenset[str], + action_body: str, +) -> dict[str, object] | None: + base: dict[str, object] = { + "generated_at": lesson.get("generated_at"), + "decision": lesson.get("decision"), + "kind": lesson.get("kind"), + "summary": lesson.get("summary"), + "avoid": avoid_text, + } + if (avoid_todo_id := normalize_todo_id(avoid_text)) and avoid_todo_id in context.todo_ids: + return {**base, "match_kind": "structured_todo_id", "matched_scope": {"todo_id": avoid_todo_id}} + if avoid_text.lower() in structured_keys: + return {**base, "match_kind": "structured_scope"} + avoid_norm = _normalized_phrase(avoid_text) + if ( + action_body + and len(avoid_norm) >= 2 + and not _BARE_PRIORITY_RE.fullmatch(avoid_norm) + and avoid_norm in action_body + ): + return {**base, "match_kind": "exact_phrase"} + return None + + def _reward_lesson_projection_warning( - status_payload: dict[str, Any], + status_payload: Mapping[str, object], *, goal_id: str, recommended_action: str | None, -) -> dict[str, Any] | None: + selected_todo: Mapping[str, object] | None = None, + work_lane: Mapping[str, object] | None = None, + agent_identity: Mapping[str, object] | None = None, + agent_lane_next_action: Mapping[str, object] | None = None, + item: Mapping[str, object] | None = None, + project_asset: Mapping[str, object] | None = None, +) -> dict[str, object] | None: action = str(recommended_action or "").strip() - if not action: + context = _extract_selection_scope_context( + (selected_todo, agent_lane_next_action, agent_identity, item, project_asset), + work_lane=work_lane, + ) + if not action and not context.has_structured_targets: return None - action_lower = action.lower() - action_tokens = _action_scope_tokens_from_text(action) - matches: list[dict[str, Any]] = [] + action_body = _normalized_action_body(action) + structured_keys = context.action_kinds | context.capability_ids | context.target_keys | context.scope_keys + matches: list[dict[str, object]] = [] for lesson in _recent_reward_lessons(status_payload, goal_id=goal_id): - for avoid in lesson.get("avoid") or []: + has_structured, matched_scope = _match_lesson_structured_scope(lesson, context) + if has_structured: + if matched_scope: + raw_avoid = lesson.get("avoid") + avoid_values = [ + str(v).strip() + for v in (raw_avoid if isinstance(raw_avoid, list) else ()) + if str(v or "").strip() + ] + matches.append( + { + "generated_at": lesson.get("generated_at"), + "decision": lesson.get("decision"), + "kind": lesson.get("kind"), + "summary": lesson.get("summary"), + "avoid": avoid_values[0] if avoid_values else str(lesson.get("summary") or ""), + "match_kind": "structured_scope", + "matched_scope": matched_scope, + } + ) + continue + raw_avoid = lesson.get("avoid") + for avoid in raw_avoid if isinstance(raw_avoid, list) else (): avoid_text = str(avoid or "").strip() if not avoid_text: continue - avoid_tokens = _action_scope_tokens_from_text(avoid_text) - exact_match = avoid_text.lower() in action_lower - if not exact_match and not avoid_tokens: - continue - token_overlap = sorted(action_tokens & avoid_tokens) - if not exact_match and len(token_overlap) < min(2, len(avoid_tokens)): - continue - matches.append( - { - "generated_at": lesson.get("generated_at"), - "decision": lesson.get("decision"), - "kind": lesson.get("kind"), - "summary": lesson.get("summary"), - "avoid": avoid_text, - "token_overlap": token_overlap[:5], - } - ) + if match := _match_unstructured_avoid( + lesson, + avoid_text, + context=context, + structured_keys=structured_keys, + action_body=action_body, + ): + matches.append(match) if not matches: return None return { @@ -86,8 +403,9 @@ def _attach_truthy_fields(payload: dict[str, Any], **fields: Any) -> None: payload.update({key: value for key, value in fields.items() if value}) -def _dict_field(payload: dict[str, Any], key: str) -> dict[str, Any] | None: - return cast(dict[str, Any], payload.get(key)) if isinstance(payload.get(key), dict) else None +def _dict_field(payload: Mapping[str, object], key: str) -> dict[str, Any] | None: + value = payload.get(key) + return cast(dict[str, Any], value) if isinstance(value, dict) else None def _attach_quota_supporting_projections( @@ -104,6 +422,7 @@ def _attach_quota_supporting_projections( state_action_projection_warning: dict[str, Any] | None, next_action_warning: dict[str, Any] | None, replan_obligation: dict[str, Any] | None, + work_lane: Mapping[str, object] | None = None, notify_gate: bool = True, ) -> None: _attach_truthy_fields( @@ -123,6 +442,12 @@ def _attach_quota_supporting_projections( status_payload, goal_id=goal_id, recommended_action=selected_recommended_action, + selected_todo=_dict_field(payload, "selected_todo"), + work_lane=work_lane if work_lane is not None else _dict_field(payload, "work_lane"), + agent_identity=_dict_field(payload, "agent_identity"), + agent_lane_next_action=_dict_field(payload, "agent_lane_next_action"), + item=item, + project_asset=project_asset, ), ) if state == "operator_gate" and ( diff --git a/loopx/control_plane/quota/should_run_packet.py b/loopx/control_plane/quota/should_run_packet.py index 294d2fc2a4..5437da9654 100644 --- a/loopx/control_plane/quota/should_run_packet.py +++ b/loopx/control_plane/quota/should_run_packet.py @@ -1650,6 +1650,7 @@ def _build_active_quota_payload( state_action_projection_warning=route.state_action_projection_warning, next_action_warning=route.next_action_warning, replan_obligation=prepared.replan_obligation, + work_lane=_dict_field(payload, "work_lane_contract"), ) frontier = _dict_field(prepared.status_payload, "bounded_research_frontier") bounded_research_frontier = _dict_field(frontier or {}, "public_projection") or frontier @@ -1980,7 +1981,8 @@ def _build_settled_quota_payload( selected_recommended_action=route.selected_recommended_action, state=route.state, user_todo_summary=prepared.user_todo_summary, should_run=False, state_action_projection_warning=None, next_action_warning=None, - replan_obligation=None, notify_gate=False, + replan_obligation=None, work_lane=_dict_field(payload, "work_lane_contract"), + notify_gate=False, ) # Work-mode diagnostics survive settlement, while execution authority comes # only from the settled result, never a fallback readback or the monitor diff --git a/loopx/control_plane/runtime/run_compaction.py b/loopx/control_plane/runtime/run_compaction.py index 52df8b7ba1..fa9547a8ca 100644 --- a/loopx/control_plane/runtime/run_compaction.py +++ b/loopx/control_plane/runtime/run_compaction.py @@ -121,6 +121,32 @@ SubagentRunCompactor = Callable[..., Optional[dict[str, Any]]] +_HUMAN_REWARD_LESSON_FIELDS = ( + "schema_version", + "kind", + "summary", + "avoid", + "prefer", + "todo_id", + "todo_ids", + "claimed_by", + "agent_id", + "task_class", + "capability_id", + "capability_ids", + "required_capabilities", + "work_lane", + "action_kind", + "target_key", + "scope_key", + "scope_keys", + "target_scopes", + "decision_scope", + "target", + "scope", +) + + def compact_human_reward(reward: Any) -> dict[str, Any] | None: if not isinstance(reward, dict): return None @@ -129,7 +155,7 @@ def compact_human_reward(reward: Any) -> dict[str, Any] | None: if isinstance(lesson, dict): compact["lesson"] = { field: lesson[field] - for field in ("schema_version", "kind", "summary", "avoid", "prefer") + for field in _HUMAN_REWARD_LESSON_FIELDS if field in lesson } return compact or None diff --git a/loopx/feedback.py b/loopx/feedback.py index 1b44e1339b..efdac88808 100644 --- a/loopx/feedback.py +++ b/loopx/feedback.py @@ -202,6 +202,56 @@ def compact_reward( return payload +HUMAN_REWARD_LESSON_STRUCTURED_SCOPE_FIELDS = ( + "todo_id", + "todo_ids", + "claimed_by", + "agent_id", + "task_class", + "capability_id", + "capability_ids", + "required_capabilities", + "work_lane", + "action_kind", + "target_key", + "scope_key", + "scope_keys", + "target_scopes", + "decision_scope", +) + + +def _compact_reward_lesson_scope_value(field: str, value: Any) -> Any: + if value is None or value == "" or value == []: + return None + if isinstance(value, str): + cleaned = value.strip() + if not cleaned: + return None + validate_public_safe_text(f"lesson {field}", cleaned) + return cleaned + if isinstance(value, list): + items: list[str] = [] + for entry in value: + cleaned = str(entry or "").strip() + if not cleaned: + continue + validate_public_safe_text(f"lesson {field}", cleaned) + if cleaned not in items: + items.append(cleaned) + return items[:10] if items else None + if isinstance(value, dict): + nested: dict[str, Any] = {} + for key, entry in value.items(): + if not isinstance(key, str) or entry is None or entry == "": + continue + cleaned_entry = _compact_reward_lesson_scope_value(f"{field}.{key}", entry) + if cleaned_entry is not None: + nested[key] = cleaned_entry + return nested or None + return None + + def compact_reward_lesson(lesson: dict[str, Any]) -> dict[str, Any]: kind = str(lesson.get("kind") or "").strip() summary = str(lesson.get("summary") or "").strip() @@ -229,6 +279,11 @@ def compact_reward_lesson(lesson: dict[str, Any]) -> dict[str, Any]: items.append(item) if items: payload[field] = items[:5] + for field in HUMAN_REWARD_LESSON_STRUCTURED_SCOPE_FIELDS: + if field in lesson: + compacted = _compact_reward_lesson_scope_value(field, lesson[field]) + if compacted is not None: + payload[field] = compacted return payload diff --git a/tests/control_plane/test_quota_supporting_projections.py b/tests/control_plane/test_quota_supporting_projections.py index 15a0d44305..6793a5b7a0 100644 --- a/tests/control_plane/test_quota_supporting_projections.py +++ b/tests/control_plane/test_quota_supporting_projections.py @@ -69,3 +69,223 @@ def test_reward_warning_is_scoped_to_selected_action_and_goal( assert warning["matches"][0]["avoid"] == "obsolete endpoint" assert "agent_command" not in payload assert "notify_user_on_gate" not in payload + + +def test_reward_warning_rejects_english_stopword_bag_overlap_and_matches_cjk_phrase() -> None: + status = { + "run_history": { + "goals": [ + { + "id": "projection-fixture", + "latest_runs": [ + { + "human_reward": { + "lesson": { + "summary": "Avoid premature benchmark expansion", + "avoid": ["deploy release pipeline", "跳过回归验证"], + } + } + } + ], + } + ] + } + } + + # Loose bag-of-words overlap ("deploy", "release") must NOT trigger a warning. + english_non_match = {} + _attach_quota_supporting_projections( + english_non_match, + status_payload=status, + item={}, + project_asset={}, + goal_id="projection-fixture", + selected_recommended_action="Check release notes and deploy docs", + state="eligible", + user_todo_summary=None, + should_run=False, + state_action_projection_warning=None, + next_action_warning=None, + replan_obligation=None, + ) + assert "reward_lesson_projection_warning" not in english_non_match + + # Exact CJK phrase works natively even with a leading priority prefix. + cjk_match = {} + _attach_quota_supporting_projections( + cjk_match, + status_payload=status, + item={}, + project_asset={}, + goal_id="projection-fixture", + selected_recommended_action="[P0] 禁止跳过回归验证后再合并", + state="eligible", + user_todo_summary=None, + should_run=False, + state_action_projection_warning=None, + next_action_warning=None, + replan_obligation=None, + ) + assert cjk_match["reward_lesson_projection_warning"]["match_count"] == 1 + assert cjk_match["reward_lesson_projection_warning"]["matches"][0]["avoid"] == "跳过回归验证" + assert cjk_match["reward_lesson_projection_warning"]["matches"][0]["match_kind"] == "exact_phrase" + + +def test_reward_warning_matches_typed_structured_scope_for_cjk_todos() -> None: + status = { + "run_history": { + "goals": [ + { + "id": "projection-fixture", + "latest_runs": [ + { + "human_reward": { + "lesson": { + "summary": "Re-verify capability route before CJK delivery", + "avoid": ["不经核验直接推进中文待办"], + "todo_id": "todo_cn_route", + "claimed_by": "agent-a", + "task_class": "advancement_task", + "capability_id": "reward_memory", + "work_lane": {"lane": "advancement_task", "obligation": "attempt_advancement"}, + } + } + } + ], + } + ] + } + } + + # Matching structured scope fires even when recommended_action is CJK and omits the avoid phrase. + matched_payload = { + "agent_identity": {"agent_id": "agent-a"}, + "selected_todo": { + "todo_id": "todo_cn_route", + "claimed_by": "agent-a", + "task_class": "advancement_task", + "required_capabilities": ["reward_memory"], + "text": "修复中文任务路由并补充测试", + }, + "work_lane": { + "lane": "advancement_task", + "obligation": "attempt_advancement", + "selected_todo_id": "todo_cn_route", + }, + } + _attach_quota_supporting_projections( + matched_payload, + status_payload=status, + item={}, + project_asset={}, + goal_id="projection-fixture", + selected_recommended_action="[P0] 修复中文任务路由并补充测试", + state="eligible", + user_todo_summary=None, + should_run=True, + state_action_projection_warning=None, + next_action_warning=None, + replan_obligation=None, + ) + warning = matched_payload["reward_lesson_projection_warning"] + assert warning["match_count"] == 1 + assert warning["matches"][0]["match_kind"] == "structured_scope" + assert warning["matches"][0]["matched_scope"]["todo_id"] == "todo_cn_route" + assert warning["matches"][0]["matched_scope"]["claimed_by"] == "agent-a" + assert warning["matches"][0]["matched_scope"]["capability_id"] == "reward_memory" + + # Different claimed_by or todo_id must NOT false-trigger even if prose matches verbatim. + for overrides in ( + {"agent_identity": {"agent_id": "agent-b"}, "selected_todo": {"todo_id": "todo_cn_route", "claimed_by": "agent-b", "task_class": "advancement_task", "required_capabilities": ["reward_memory"]}}, + {"agent_identity": {"agent_id": "agent-a"}, "selected_todo": {"todo_id": "todo_other", "claimed_by": "agent-a", "task_class": "advancement_task", "required_capabilities": ["reward_memory"]}, "work_lane": {"lane": "advancement_task", "obligation": "attempt_advancement", "selected_todo_id": "todo_other"}}, + {"agent_identity": {"agent_id": "agent-a"}, "selected_todo": {"todo_id": "todo_cn_route", "claimed_by": "agent-a", "task_class": "continuous_monitor", "required_capabilities": ["reward_memory"]}, "work_lane": {"lane": "continuous_monitor", "obligation": "attempt_due_monitor", "selected_todo_id": "todo_cn_route"}}, + ): + non_matching_payload = dict(overrides) + _attach_quota_supporting_projections( + non_matching_payload, + status_payload=status, + item={}, + project_asset={}, + goal_id="projection-fixture", + selected_recommended_action="不经核验直接推进中文待办", + state="eligible", + user_todo_summary=None, + should_run=True, + state_action_projection_warning=None, + next_action_warning=None, + replan_obligation=None, + ) + assert "reward_lesson_projection_warning" not in non_matching_payload + + +def test_build_quota_should_run_projects_structured_cjk_reward_lesson_end_to_end() -> None: + from loopx.control_plane.testing.quota_fixtures import ( + quota_status_payload, + quota_todo_item, + ) + from loopx.feedback import compact_reward + from loopx.quota import build_quota_should_run + from loopx.status import compact_human_reward + + reward = compact_human_reward( + compact_reward( + recorded_at="2026-11-18T00:00:00+00:00", + decision="route_correction", + reward="mixed", + reason_summary="需要先验证中文待办路由后再推进。", + follow_up=None, + lesson={ + "kind": "route", + "summary": "中文待办必须绑定能力并先跑核验", + "avoid": ["P0", "直接跳过中文核验"], + "todo_id": "todo_cn_route", + "claimed_by": "agent-a", + "task_class": "advancement_task", + "capability_id": "shell", + "work_lane": {"lane": "advancement_task"}, + }, + ) + ) + assert reward is not None + assert reward["lesson"]["todo_id"] == "todo_cn_route" + assert reward["lesson"]["claimed_by"] == "agent-a" + + status_a = quota_status_payload( + goal_id="projection-fixture", + status="active", + recommended_action="[P0] 修复中文路由并执行单元测试", + coordination={"agent_model": "peer_v1", "registered_agents": ["agent-a", "agent-b"]}, + agent_todo_items=[ + quota_todo_item( + todo_id="todo_cn_route", + title="修复中文路由并执行单元测试", + claimed_by="agent-a", + required_capabilities=["shell"], + ), + quota_todo_item( + todo_id="todo_cn_other", + index=2, + title="清理其他中文模块", + claimed_by="agent-b", + required_capabilities=["shell"], + ), + ], + latest_runs=[{"generated_at": "2026-11-18T00:00:00+00:00", "human_reward": reward}], + ) + guard_a = build_quota_should_run( + status_a, + goal_id="projection-fixture", + agent_id="agent-a", + available_capabilities=["shell"], + ) + assert guard_a["reward_lesson_projection_warning"]["match_count"] == 1 + assert guard_a["reward_lesson_projection_warning"]["matches"][0]["match_kind"] == "structured_scope" + assert guard_a["reward_lesson_projection_warning"]["matches"][0]["matched_scope"]["todo_id"] == "todo_cn_route" + + guard_b = build_quota_should_run( + status_a, + goal_id="projection-fixture", + agent_id="agent-b", + available_capabilities=["shell"], + ) + assert "reward_lesson_projection_warning" not in guard_b diff --git a/tests/control_plane/test_scoped_gate_fallback_selection.py b/tests/control_plane/test_scoped_gate_fallback_selection.py index ea88ae822f..0bcf2d8059 100644 --- a/tests/control_plane/test_scoped_gate_fallback_selection.py +++ b/tests/control_plane/test_scoped_gate_fallback_selection.py @@ -49,3 +49,69 @@ def test_empty_capability_result_does_not_revive_backlog(): def test_finished_rows_in_stale_candidate_lanes_are_not_executable(): for state in ({"status": "done"}, {"archive_state": "archive"}, {"status": "blocked"}): assert select(items=[{"todo_id": "todo_work", "action_kind": "compile_library", **state}]) is None + + +def test_cjk_todo_descriptions_use_typed_scope_without_stopwords(): + # Identical CJK prose on gate and fallback still admits when typed dependency scope is disjoint. + independent = select( + { + "text": "审批发布生产配置", + "action_kind": "release_publish", + "unblocks_todo_id": "todo_other", + }, + items=[ + { + "todo_id": "todo_cn_work", + "task_class": "advancement_task", + "status": "open", + "claimed_by": "agent-a", + "action_kind": "release_publish", + "text": "审批发布生产配置(先跑本地单元测试)", + "index": 1, + } + ], + ) + assert independent is not None + assert independent["selected_executable"]["todo_id"] == "todo_cn_work" + + # Distinct CJK prose without structural scope fails closed. + assert ( + select( + { + "text": "等待审批生产权限", + "action_kind": None, + "unblocks_todo_id": None, + }, + items=[ + { + "todo_id": "todo_cn_work", + "task_class": "advancement_task", + "status": "open", + "claimed_by": "agent-a", + "action_kind": "run_local_tests", + "text": "修复中文任务调度", + "index": 1, + } + ], + ) + is None + ) + + # CJK task claimed by another agent is never selected. + assert ( + select( + {"text": "审批发布生产配置", "unblocks_todo_id": "todo_other"}, + items=[ + { + "todo_id": "todo_cn_other", + "task_class": "advancement_task", + "status": "open", + "claimed_by": "agent-b", + "action_kind": "run_local_tests", + "text": "修复中文任务调度", + "index": 1, + } + ], + ) + is None + )