From 532a729582f8ce664f0f78805d7837530c157fa4 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:08:49 +0800 Subject: [PATCH] refactor(goal-frontier): slim __init__.py below 1,000 lines and consolidate rule/projection owners Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/canary/module_metric_baseline.json | 25 +- .../goals/goal_frontier/__init__.py | 1985 ++++------------- .../goals/goal_frontier/acceptance.py | 105 +- .../goals/goal_frontier/ack_policy.py | 199 +- .../goals/goal_frontier/projection.py | 305 +++ .../goals/goal_frontier/replan_rules.py | 309 ++- 6 files changed, 1365 insertions(+), 1563 deletions(-) create mode 100644 loopx/control_plane/goals/goal_frontier/projection.py diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json index 24e8292c00..aae9707bcf 100644 --- a/loopx/canary/module_metric_baseline.json +++ b/loopx/canary/module_metric_baseline.json @@ -94,8 +94,29 @@ "lines": 826 }, "loopx/control_plane/goals/goal_frontier/__init__.py": { - "any_count": 115, - "dict_any_count": 0 + "any_count": 0, + "dict_any_count": 0, + "lines": 968 + }, + "loopx/control_plane/goals/goal_frontier/acceptance.py": { + "any_count": 0, + "dict_any_count": 0, + "lines": 221 + }, + "loopx/control_plane/goals/goal_frontier/ack_policy.py": { + "any_count": 0, + "dict_any_count": 0, + "lines": 333 + }, + "loopx/control_plane/goals/goal_frontier/projection.py": { + "any_count": 0, + "dict_any_count": 0, + "lines": 305 + }, + "loopx/control_plane/goals/goal_frontier/replan_rules.py": { + "any_count": 0, + "dict_any_count": 0, + "lines": 525 }, "loopx/control_plane/goals/goal_frontier/terminal.py": { "any_count": 15, diff --git a/loopx/control_plane/goals/goal_frontier/__init__.py b/loopx/control_plane/goals/goal_frontier/__init__.py index a399b8d130..349c78872a 100644 --- a/loopx/control_plane/goals/goal_frontier/__init__.py +++ b/loopx/control_plane/goals/goal_frontier/__init__.py @@ -1,8 +1,7 @@ from __future__ import annotations -from typing import Any, cast - -from collections.abc import Callable, Mapping +from collections.abc import Callable, Mapping, Sequence +from typing import cast from ...agents.agent_scope import ( agent_scope_blocking_handoff_gates, @@ -10,175 +9,171 @@ agent_scope_item_claimed_by, agent_scope_item_claimed_by_agent_or_unclaimed, ) -from ...agents.profile import agent_profile_requires_vision from ...agents.runtime_model import peer_work_key, select_peer_for_work from ...runtime.time import parse_timestamp # Refs #4447: the todo contract owns this vocabulary; import it instead of # restating the literal in every module that classifies a Todo. -from ...todos.contract import ( - TODO_TASK_CLASS_ADVANCEMENT, - TODO_TASK_CLASS_MONITOR, - normalize_todo_replan_obligation_id, -) +from ...todos.contract import TODO_TASK_CLASS_ADVANCEMENT, TODO_TASK_CLASS_MONITOR +from ...todos.resume_planning import read_todo_deferred_work_counts +from ...todos.succession_warning import todo_succession_gap_items from ...todos.todo_semantics import ( todo_advancement_frontier_counts, todo_item_is_watch_only_monitor, todo_scoped_runnable_advancement_count, todo_summary_open_task_counts, ) -from ...todos.succession_warning import ( - TODO_SUCCESSION_WARNING_REASON_CODE, - todo_succession_gap_items, -) from ...todos.user_gate import open_todo_count as _open_todo_count -from ...todos.resume_planning import read_todo_deferred_work_counts -from ...work_items.autonomous_replan_ack import ( - autonomous_replan_ack_matches_agent, - autonomous_replan_ack_matches_frontier, - normalize_projected_autonomous_replan_ack, -) +from ...work_items.autonomous_replan_ack import autonomous_replan_ack_matches_frontier from ...work_items.autonomous_replan_obligation import ( MONITOR_NO_CHANGE_STREAK_THRESHOLD, - TODO_LIFECYCLE_SETTLEMENT_RESOLUTION_MODE, - build_autonomous_replan_obligation_payload, ensure_replan_novelty_policy, with_replan_novelty_guidance, ) from ...work_items.lifecycle_recovery import attach_receipt_replan_context +from ...work_items.replan_history_codec import project_replan_history from ..goal_vision_policy import ( completed_todo_replan_threshold, goal_vision_repeats_advancement_until_closed, ) -from ..goal_vision_state import goal_vision_state_is_closed from ..goal_vision_read_model import ( VISION_ACCEPTANCE_GAP_TRIGGER as VISION_ACCEPTANCE_GAP_TRIGGER, VISION_SUCCESSOR_GAP_TRIGGER as VISION_SUCCESSOR_GAP_TRIGGER, - _compact_projection_text, acceptance_gaps_from_agent_vision as acceptance_gaps_from_agent_vision, parse_vision_todo_delta_entries as parse_vision_todo_delta_entries, ) +from ..goal_vision_state import goal_vision_state_is_closed from ..goal_vision_wait import build_goal_vision_wait_state -from . import outcome_continuity +from . import outcome_continuity as outcome_continuity from .acceptance import ( - GOAL_ACCEPTANCE_HOLD_TRIGGERS, - acceptance_gaps_from_held_goal_binding, - acceptance_gaps_from_outcomes, - project_legacy_acceptance_hold_ack, + GOAL_ACCEPTANCE_HOLD_TRIGGERS as GOAL_ACCEPTANCE_HOLD_TRIGGERS, + VISION_PROFILE_MISSING_TRIGGER as VISION_PROFILE_MISSING_TRIGGER, + acceptance_gaps_from_agent_profile_requirement as acceptance_gaps_from_agent_profile_requirement, + acceptance_gaps_from_held_goal_binding as acceptance_gaps_from_held_goal_binding, + acceptance_gaps_from_outcomes as acceptance_gaps_from_outcomes, + project_legacy_acceptance_hold_ack as project_legacy_acceptance_hold_ack, ) -from ...work_items.replan_semantics_codec import project_replan_semantics -from ...work_items.replan_history_codec import project_replan_history from .ack_policy import ( - attach_rejected_replan_feedback, - autonomous_replan_ack_satisfies_obligation, - replan_successor_transition_ack, + _acknowledged_replan_obligation_id as _acknowledged_replan_obligation_id, + _replan_evidence_acknowledged as _replan_evidence_acknowledged, + _succession_gap_acknowledged as _succession_gap_acknowledged, + _vision_gap_acknowledged as _vision_gap_acknowledged, + attach_rejected_replan_feedback as attach_rejected_replan_feedback, + autonomous_replan_ack_satisfies_obligation as autonomous_replan_ack_satisfies_obligation, + projected_autonomous_replan_ack_for_agent as projected_autonomous_replan_ack_for_agent, + replan_successor_transition_ack as replan_successor_transition_ack, ) from .fallback_source import ( - VISION_FRONTIER_TODO_DELTA_ACTIONS, # noqa: F401 - FallbackDeclaration, # noqa: F401 - FallbackTodoSource, - agent_scoped_selectable_advancement_todo_ids, # noqa: F401 - declared_fallback_gap_from_agent_vision, - parse_fallback_declarations, # noqa: F401 + VISION_FRONTIER_TODO_DELTA_ACTIONS as VISION_FRONTIER_TODO_DELTA_ACTIONS, + FallbackDeclaration as FallbackDeclaration, + FallbackTodoSource as FallbackTodoSource, + agent_scoped_selectable_advancement_todo_ids as agent_scoped_selectable_advancement_todo_ids, + declared_fallback_gap_from_agent_vision as declared_fallback_gap_from_agent_vision, + parse_fallback_declarations as parse_fallback_declarations, +) +from .long_todo_chain import ( + LONG_TODO_CHAIN_TRIGGER as LONG_TODO_CHAIN_TRIGGER, + evaluate_long_todo_chain as evaluate_long_todo_chain, +) +from .projection import ( + AUTONOMOUS_REPLAN_DECISION_SCHEMA_VERSION as AUTONOMOUS_REPLAN_DECISION_SCHEMA_VERSION, + AUTONOMOUS_REPLAN_REQUIRED_MODE as AUTONOMOUS_REPLAN_REQUIRED_MODE, + GOAL_FRONTIER_PROJECTION_SCHEMA_VERSION as GOAL_FRONTIER_PROJECTION_SCHEMA_VERSION, + VISION_CONTINUATION_AUDIT_SCHEMA_VERSION as VISION_CONTINUATION_AUDIT_SCHEMA_VERSION, + VISION_GAP_JUDGE_SCHEMA_VERSION as VISION_GAP_JUDGE_SCHEMA_VERSION, + autonomous_replan_is_required as autonomous_replan_is_required, + build_autonomous_replan_decision as build_autonomous_replan_decision, + build_autonomous_replan_recommendation as build_autonomous_replan_recommendation, + build_goal_frontier_projection as build_goal_frontier_projection, + build_vision_continuation_audit as build_vision_continuation_audit, + build_vision_gap_judge as build_vision_gap_judge, + compact_replan_obligation as compact_replan_obligation, + safe_non_negative_int as safe_non_negative_int, ) -from .long_todo_chain import LONG_TODO_CHAIN_TRIGGER, evaluate_long_todo_chain from .replan_rules import ( - GoalFrontierReplanFacts, - GoalFrontierReplanRule, - select_goal_frontier_replan_rule, + AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION as AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION, + FRONTIER_EXHAUSTED_MONITOR_TRIGGER as FRONTIER_EXHAUSTED_MONITOR_TRIGGER, + TODO_SUCCESSION_GAP_TRIGGER as TODO_SUCCESSION_GAP_TRIGGER, + GoalFrontierReplanFacts as GoalFrontierReplanFacts, + GoalFrontierReplanRule as GoalFrontierReplanRule, + build_rule_replan_obligation, + select_goal_frontier_replan_rule as select_goal_frontier_replan_rule, ) from .semantic_history import ( - _latest_runs_for_goal, + _latest_runs_for_goal as _latest_runs_for_goal, latest_agent_vision_from_runs as latest_agent_vision_from_runs, - latest_agent_vision_from_status_payload, - receipt_bound_replan_ack_history, - latest_missing_vision_checkpoint_from_status_payload, - latest_replan_ack_feedback_from_status_payload, + latest_agent_vision_from_status_payload as latest_agent_vision_from_status_payload, + latest_autonomous_replan_ack_from_status_payload as latest_autonomous_replan_ack_from_status_payload, + latest_missing_vision_checkpoint_from_status_payload as latest_missing_vision_checkpoint_from_status_payload, + latest_replan_ack_feedback_from_status_payload as latest_replan_ack_feedback_from_status_payload, + receipt_bound_replan_ack_history as receipt_bound_replan_ack_history, ) from .terminal import ( - GOAL_TERMINAL_SOURCE_COMPLETENESS_SCHEMA_VERSION, # noqa: F401 - GOAL_TERMINAL_STATE_SCHEMA_VERSION, # noqa: F401 - VISION_CHECKPOINT_NO_FOLLOWUP_RESOLUTION, # noqa: F401 + GOAL_TERMINAL_SOURCE_COMPLETENESS_SCHEMA_VERSION as GOAL_TERMINAL_SOURCE_COMPLETENESS_SCHEMA_VERSION, + GOAL_TERMINAL_STATE_SCHEMA_VERSION as GOAL_TERMINAL_STATE_SCHEMA_VERSION, + VISION_CHECKPOINT_NO_FOLLOWUP_RESOLUTION as VISION_CHECKPOINT_NO_FOLLOWUP_RESOLUTION, _terminal_no_followup_resolves_vision_checkpoint, - derive_goal_terminal_state, - goal_frontier_is_terminal_no_followup as goal_frontier_is_terminal_no_followup, # noqa: F401 + derive_goal_terminal_state as derive_goal_terminal_state, + goal_frontier_is_terminal_no_followup as goal_frontier_is_terminal_no_followup, ) -GOAL_FRONTIER_PROJECTION_SCHEMA_VERSION = "goal_frontier_projection_v0" -VISION_CONTINUATION_AUDIT_SCHEMA_VERSION = "vision_continuation_audit_v0" -VISION_GAP_JUDGE_SCHEMA_VERSION = "vision_gap_judge_v0" -AUTONOMOUS_REPLAN_DECISION_SCHEMA_VERSION = "autonomous_replan_decision_v0" +Payload = dict[str, object] +PayloadView = Mapping[str, object] + AUTONOMOUS_REPLAN_SCOPE_SCHEMA_VERSION = "autonomous_replan_scope_v0" -AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION = "autonomous_replan_obligation_v0" -AUTONOMOUS_REPLAN_REQUIRED_MODE = "autonomous_replan_required" -FRONTIER_EXHAUSTED_MONITOR_TRIGGER = "frontier_exhausted_monitor_lane" MONITOR_NO_CHANGE_STREAK_TRIGGER = "monitor_no_change_streak" -VISION_PROFILE_MISSING_TRIGGER = "required_agent_vision_missing" -TODO_SUCCESSION_GAP_TRIGGER = TODO_SUCCESSION_WARNING_REASON_CODE - - -def safe_non_negative_int(value: Any) -> int: - try: - return max(0, int(value or 0)) - except (TypeError, ValueError): - return 0 +_REPLAN_OWNER_KEYS = ( + "agent_id", "claimed_by", "bound_agent", "owner_agent", "target_agent", "blocks_agent", +) def select_autonomous_replan_obligation( - item: dict[str, Any], - project_asset: dict[str, Any] | None = None, + item: PayloadView, + project_asset: PayloadView | None = None, *, agent_id: str | None = None, -) -> dict[str, Any] | None: - project_asset = project_asset if isinstance(project_asset, dict) else {} +) -> Payload | None: + sources = (item, project_asset) if isinstance(project_asset, dict) else (item,) safe_agent_id = str(agent_id or "").strip() if safe_agent_id: - for source in (item, project_asset): + for source in sources: obligations = source.get("autonomous_replan_obligations_by_agent") - if not isinstance(obligations, dict): - continue - value = obligations.get(safe_agent_id) - if isinstance(value, dict): - return value - value = item.get("autonomous_replan_obligation") - if isinstance(value, dict): - return value - value = project_asset.get("autonomous_replan_obligation") - if isinstance(value, dict): - return value + if isinstance(obligations, dict) and isinstance( + value := obligations.get(safe_agent_id), dict + ): + return cast(Payload, value) + for source in sources: + if isinstance(value := source.get("autonomous_replan_obligation"), dict): + return cast(Payload, value) return None -def autonomous_replan_is_required(replan_obligation: dict[str, Any] | None) -> bool: - return bool(replan_obligation and replan_obligation.get("required")) - - def align_autonomous_replan_guidance_with_acceptance_policy( - replan_obligation: dict[str, Any] | None, + replan_obligation: Payload | None, *, - acceptance_gaps: list[dict[str, Any]] | None, -) -> dict[str, Any] | None: + acceptance_gaps: Sequence[PayloadView] | None, +) -> Payload | None: """Remove wait-only guidance when the active vision requires advancement.""" if not isinstance(replan_obligation, dict): return replan_obligation + raw_triggers = replan_obligation.get("triggers") trigger_kinds = { str(trigger.get("kind") or "").strip() - for trigger in (replan_obligation.get("triggers") or []) + for trigger in (raw_triggers if isinstance(raw_triggers, list) else ()) if isinstance(trigger, dict) } if "blocked_successor_no_progress_repeat" not in trigger_kinds or not any( goal_vision_repeats_advancement_until_closed(gap.get("advancement_policy")) - for gap in (acceptance_gaps or []) + for gap in (acceptance_gaps or ()) if isinstance(gap, dict) ): return replan_obligation aligned = dict(replan_obligation) aligned["guidance_actions"] = [ - "discover_safe_successor", - "create_runnable_todo", - "successor_or_supersede", + "discover_safe_successor", "create_runnable_todo", "successor_or_supersede", ] + raw_todo_actions = replan_obligation.get("todo_actions") aligned["todo_actions"] = [ { **action, @@ -188,11 +183,9 @@ def align_autonomous_replan_guidance_with_acceptance_policy( "successor/supersede transition" ), } - if isinstance(action, dict) - and action.get("action") == "add" - and action.get("role") == "agent" + if isinstance(action, dict) and action.get("action") == "add" and action.get("role") == "agent" else action - for action in (replan_obligation.get("todo_actions") or []) + for action in (raw_todo_actions if isinstance(raw_todo_actions, list) else ()) ] aligned["recommended_action"] = with_replan_novelty_guidance( "run a bounded autonomous replan for the exact blocked successor: " @@ -201,61 +194,40 @@ def align_autonomous_replan_guidance_with_acceptance_policy( "continuation does not satisfy a repeat-until-closed vision" ) aligned["satisfying_semantic_outcomes"] = [ - "fresh_vision_path_outcome", - "new_runnable_successor", - "new_concrete_blocker", - "coverage_backed_exploration_exhausted", - "coverage_backed_no_followup", + "fresh_vision_path_outcome", "new_runnable_successor", "new_concrete_blocker", + "coverage_backed_exploration_exhausted", "coverage_backed_no_followup", ] return aligned -def _normalize_replan_agent_id(value: Any) -> str | None: - text = str(value or "").strip() - return text or None +def _normalize_replan_agent_id(value: object) -> str | None: + return str(value or "").strip() or None -def _autonomous_replan_owner_agent_ids( - replan_obligation: dict[str, Any] | None, -) -> list[str]: +def _autonomous_replan_owner_agent_ids(replan_obligation: PayloadView | None) -> list[str]: if not isinstance(replan_obligation, dict): return [] - owner_keys = ( - "agent_id", - "claimed_by", - "bound_agent", - "owner_agent", - "target_agent", - "blocks_agent", - ) - owners: list[str] = [] - - def append_owner(value: Any) -> None: - owner = _normalize_replan_agent_id(value) - if owner and owner not in owners: - owners.append(owner) - - for key in owner_keys: - append_owner(replan_obligation.get(key)) - triggers = ( - cast(list[Any], replan_obligation.get("triggers")) - if isinstance(replan_obligation.get("triggers"), list) - else [] + triggers = replan_obligation.get("triggers") + sources = [ + replan_obligation, + *(t for t in (triggers if isinstance(triggers, list) else ()) if isinstance(t, dict)), + ] + return list( + dict.fromkeys( + owner + for src in sources + for key in _REPLAN_OWNER_KEYS + if (owner := _normalize_replan_agent_id(src.get(key))) + ) ) - for trigger in triggers: - if not isinstance(trigger, dict): - continue - for key in owner_keys: - append_owner(trigger.get(key)) - return owners def autonomous_replan_scope_decision( - replan_obligation: dict[str, Any] | None, + replan_obligation: PayloadView | None, *, agent_id: str | None, registered_agent_ids: list[str] | None = None, -) -> dict[str, Any]: +) -> Payload: """Return whether a replan obligation belongs to this agent lane. Explicit agent-owned replans are consumed only by that agent. Unscoped @@ -267,28 +239,28 @@ def autonomous_replan_scope_decision( required = autonomous_replan_is_required(replan_obligation) selected_peer_agent = None if not required: - applies = False - scope = "not_required" + applies, scope = False, "not_required" elif not normalized_agent_id: - applies = True - scope = "unscoped_quota_call" + applies, scope = True, "unscoped_quota_call" elif owners: - applies = normalized_agent_id in owners - scope = "explicit_agent_owner" + applies, scope = normalized_agent_id in owners, "explicit_agent_owner" else: + obligation_obj = cast(Payload, replan_obligation) selected_peer_agent = select_peer_for_work( registered_agent_ids or [], # Display evidence and prose are mutable projections, not work # identity. Normalize before both selection and permission checks. work_key=peer_work_key( - {"obligation_id": cast(dict[str, Any], replan_obligation).get("obligation_id") - or ensure_replan_novelty_policy(cast(dict[str, Any], replan_obligation))["obligation_id"]}, + { + "obligation_id": obligation_obj.get("obligation_id") + or ensure_replan_novelty_policy(obligation_obj)["obligation_id"] + }, fallback="autonomous_replan", ), ) applies = bool(selected_peer_agent and normalized_agent_id == selected_peer_agent) scope = "deterministic_peer_assignment" - payload = { + return { "schema_version": AUTONOMOUS_REPLAN_SCOPE_SCHEMA_VERSION, "required": required, "applies": applies, @@ -298,425 +270,133 @@ def autonomous_replan_scope_decision( "owner_agent_ids": owners, "selected_peer_agent": selected_peer_agent, } - return payload - - -def projected_autonomous_replan_ack_for_agent( - item: dict[str, Any], - project_asset: dict[str, Any] | None, - *, - agent_id: str | None, -) -> dict[str, Any] | None: - """Return the current projected replan ACK when it belongs to this agent.""" - - project_asset = project_asset if isinstance(project_asset, dict) else {} - for candidate in ( - item.get("autonomous_replan_ack"), - project_asset.get("autonomous_replan_ack"), - ): - normalized = normalize_projected_autonomous_replan_ack(candidate) - if autonomous_replan_ack_matches_agent(normalized, agent_id=agent_id): - return normalized - return None -def acceptance_gaps_from_agent_profile_requirement( - agent_profile: dict[str, Any] | None, - *, - agent_id: str | None, - agent_vision: dict[str, Any] | None, - missing_checkpoint: dict[str, Any] | None, -) -> list[dict[str, Any]]: - """Require a vision baseline for registered long-lived peer lanes.""" - - if ( - not agent_id - or not agent_profile_requires_vision(agent_profile) - or isinstance(agent_vision, dict) - or isinstance(missing_checkpoint, dict) - ): - return [] - return [ - { - "kind": VISION_PROFILE_MISSING_TRIGGER, - "source": "agent_profile", - "agent_id": agent_id, - "replan_trigger_summary": ( - "the registered long-lived agent lane requires a persisted vision " - "baseline before ordinary delivery or monitor-only quiet wait" - ), - "acceptance_summary": ( - "Write a bounded agent vision with objective, acceptance evidence, " - "advancement policy, and replan trigger; or explicitly mark the " - "profile vision requirement optional." - ), - "advancement_policy": "repeat_until_closed", - } - ] - - - -def build_vision_continuation_audit( - *, - goal_id: str | None = None, - agent_id: str | None, - acceptance_gaps: list[dict[str, Any]] | None, -) -> dict[str, Any] | None: - """Return the closeout audit contract for an open per-agent vision gap. - - This is a read-path contract: quota/status can tell an agent that the - selected todo is only a step toward the active vision. Writeback still goes - through normal todo, evidence, and refresh-state commands. - """ - - compact_acceptance_gaps = [ - gap for gap in (acceptance_gaps or []) if isinstance(gap, dict) - ] - if not compact_acceptance_gaps: - return None - vision_gap_judge = build_vision_gap_judge( - goal_id=goal_id, - agent_id=agent_id, - acceptance_gaps=compact_acceptance_gaps, - ) - acceptance_requirements = [ - text - for text in ( - _compact_projection_text(gap.get("acceptance_summary"), limit=180) - for gap in compact_acceptance_gaps - ) - if text - ] - trigger_kinds = [ - kind - for kind in ( - _compact_projection_text(gap.get("kind"), limit=80) - for gap in compact_acceptance_gaps - ) - if kind - ] - audit: dict[str, Any] = { - "schema_version": VISION_CONTINUATION_AUDIT_SCHEMA_VERSION, - "required": True, - "agent_id": agent_id, - "decision": "acceptance_gap_open", - "selected_todo_is_goal_completion": False, - "closeout_allowed_without_evidence": False, - "trigger_count": len(compact_acceptance_gaps), - "trigger_kinds": list(dict.fromkeys(trigger_kinds))[:5], - "acceptance_gaps": compact_acceptance_gaps[:5], - "vision_gap_judge": vision_gap_judge, - "authoritative_evidence_kinds": [ - "changed_files", - "public_safe_evidence_records", - "public_web_research_findings", - "evaluation_outputs", - "successor_state", - "blocker_state", - "superseding_agent_vision", - ], - "not_satisfied_by": [ - "todo_completion_alone", - "autonomous_replan_ack_alone", - "vision_checkpoint_alone", - "registry_registration_alone", - "no_followup_without_acceptance_evidence", - ], - "required_before_closeout": [ - "derive_requirements_from_active_vision_and_current_todo", - "name_authoritative_evidence_for_each_requirement", - "inspect_registry_declared_materials_before_external_research", - "run_bounded_public_research_when_local_evidence_is_missing", - "create_successor_or_write_vision_replan_trigger_when_unproven", - ], - "recommended_action": ( - "audit active per-agent vision acceptance before todo closeout; " - "if evidence is weak or missing, inspect registry-declared material " - "references before bounded public research, then keep the vision " - "active with a successor todo or --vision-replan-trigger" - ), +def _todo_item_is_actionable_open(item: PayloadView) -> bool: + return item.get("done") is not True and str(item.get("status") or "open").strip().lower() in { + "", "open", "todo", "active", "pending", } - if acceptance_requirements: - audit["acceptance_requirements"] = acceptance_requirements[:5] - diagnostics = [ - {key: gap[key] for key in ("reason_code", "component_checks", "resolution_hint")} - for gap in compact_acceptance_gaps - if gap.get("reason_code") and gap.get("component_checks") and gap.get("resolution_hint") - ] - if diagnostics: - audit["outcome_checkpoint_diagnostics"] = diagnostics[:5] - return audit -def build_vision_gap_judge( - *, - goal_id: str | None = None, - agent_id: str | None, - acceptance_gaps: list[dict[str, Any]] | None, -) -> dict[str, Any]: - """Return the strict done/continue judge for active per-agent vision gaps. +def _todo_task_class(item: PayloadView) -> str: + return str(item.get("task_class") or "").strip() - The read model keeps the prompt essence compact: unless current evidence - satisfies, blocks, or supersedes the active vision, the agent should judge - the vision as still CONTINUE. - """ - compact_acceptance_gaps = [ - gap for gap in (acceptance_gaps or []) if isinstance(gap, dict) - ] - first_gap = compact_acceptance_gaps[0] if compact_acceptance_gaps else {} - reason = _compact_projection_text( - first_gap.get("replan_trigger_summary") - or "active per-agent vision still has an open acceptance gap", - limit=220, - ) - evidence_read_instruction = ( - "Use the host-projected compact coverage ledger and uncovered frontier. " - "The agent-scoped evidence log remains the durable source and an optional " - "diagnostic readback, not a model-executed closure gate." - ) - registry_read_instruction = ( - "Before external research, inspect the selected goal's registry-declared " - "topic_authority and project_materials metadata, preferring any projected " - "replan_context or agent_material_frontier. Use role, freshness, revision, " - "boundary, gate_status, and conflict_rule to choose permitted references. " - "Registration guides discovery; it neither grants access nor proves acceptance." - ) - public_research_instruction = ( - "If projected evidence, the evidence log, and permitted registry-declared " - "references remain missing, stale, or too weak and the acceptance question " - "depends on public facts, run bounded public web research using primary or " - "authoritative sources; record confirmed/refuted findings as public-safe " - "evidence or a compact vision replan trigger before judging." +def _is_actionable_monitor_item(item: object, *, watch_only: bool) -> bool: + if not isinstance(item, dict) or not _todo_item_is_actionable_open(item): + return False + is_watch_only = todo_item_is_watch_only_monitor(item) + return is_watch_only if watch_only else ( + _todo_task_class(item) == TODO_TASK_CLASS_MONITOR and not is_watch_only ) - return { - "schema_version": VISION_GAP_JUDGE_SCHEMA_VERSION, - "goal_id": goal_id, - "agent_id": agent_id, - "done": False, - "decision": "continue", - "reason": ( - reason - or "active per-agent vision still has an open acceptance gap" - ), - "agent_judge_instruction": ( - "Judge vision closure: compare active vision acceptance_summary " - "with the host-projected agent-scoped coverage ledger. " - "Inspect permitted registry-declared material references before bounded " - "public web research. " - "Mark done only when evidence proves completion, a blocker/user " - "gate, or superseding/no-follow-up closure; otherwise continue." - ), - "evidence_read_instruction": evidence_read_instruction, - "registry_read_instruction": registry_read_instruction, - "external_research_instruction": public_research_instruction, - "research_writeback_required_when_used": [ - "source_url_or_public_reference", - "confirmed_or_refuted_finding", - "supports_or_refutes_acceptance_gap", - "successor_todo_or_vision_replan_trigger", - ], - "done_only_when": [ - "authoritative_evidence_satisfies_acceptance", - "final_deliverable_or_eval_output_satisfies_acceptance", - "blocker_or_user_gate_is_projected", - "superseding_vision_or_no_followup_closes_the_frontier", - ], - "continue_when": [ - "evidence_is_missing_weak_or_stale", - "todo_lifecycle_or_protocol_status_is_the_only_proof", - "acceptance_gap_is_still_projected", - ], - "otherwise": "continue", - } -def _blocking_user_open_count(summary: dict[str, Any] | None) -> int: +def _blocking_user_open_count(summary: Payload | None) -> int: if not isinstance(summary, dict): return 0 gate_items = summary.get("gate_open_items") if isinstance(gate_items, list): - return sum( - 1 - for item in gate_items - if isinstance(item, dict) and _todo_item_is_actionable_open(item) - ) + return sum(1 for item in gate_items if isinstance(item, dict) and _todo_item_is_actionable_open(item)) # Legacy or partial summaries without typed gate projection fail closed. return _open_todo_count(summary) -def _todo_item_is_actionable_open(item: dict[str, Any]) -> bool: - if item.get("done") is True: - return False - status = str(item.get("status") or "open").strip().lower() - return status in {"", "open", "todo", "active", "pending"} - - -def _todo_task_class(item: dict[str, Any]) -> str: - return str(item.get("task_class") or "").strip() - - -def _summary_task_counts(summary: dict[str, Any] | None) -> dict[str, int]: +def _summary_task_counts(summary: Payload | None) -> dict[str, int]: open_count = _open_todo_count(summary) if not isinstance(summary, dict): - return { - "open": open_count, - "advancement": 0, - "monitor": 0, - "monitor_due": 0, - "watch_only_monitor_due": 0, - } + return {"open": open_count, "advancement": 0, "monitor": 0, "monitor_due": 0, "watch_only_monitor_due": 0} executable = summary.get("executable_backlog_items") monitor_open = summary.get("monitor_open_items") - if isinstance(summary.get("watch_only_monitor_count"), int): - watch_only_count = safe_non_negative_int( - summary.get("watch_only_monitor_count") - ) - elif isinstance(monitor_open, list): - watch_only_count = len( - [ - item - for item in monitor_open - if isinstance(item, dict) - and _todo_item_is_actionable_open(item) - and todo_item_is_watch_only_monitor(item) - ] - ) - else: - watch_only_count = 0 - if isinstance(summary.get("convergence_open_count"), int): - open_count = safe_non_negative_int(summary.get("convergence_open_count")) - else: + watch_only_count = ( + safe_non_negative_int(summary.get("watch_only_monitor_count")) + if isinstance(summary.get("watch_only_monitor_count"), int) + else sum(1 for item in monitor_open if _is_actionable_monitor_item(item, watch_only=True)) + if isinstance(monitor_open, list) + else 0 + ) + open_count = ( + safe_non_negative_int(summary.get("convergence_open_count")) + if isinstance(summary.get("convergence_open_count"), int) # Compatibility-only fallback for summaries produced before the typed # TypeScript lane owner exposed convergence_open_count. - open_count = max(0, open_count - watch_only_count) - work_counts = ( - todo_summary_open_task_counts(summary) - if summary.get("work_counts") is not None else None - ) - advancement_count = ( - safe_non_negative_int(work_counts.get("advancement")) - if isinstance(work_counts, dict) - else - _count_advancement_items(executable) - if isinstance(executable, list) - else safe_non_negative_int(summary.get("claimed_advancement_open_count")) - + len( - [ - item - for item in (summary.get("unclaimed_priority_open_items") or []) - if isinstance(item, dict) - and _todo_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT - ] - ) + else max(0, open_count - watch_only_count) ) + work_counts = todo_summary_open_task_counts(summary) if summary.get("work_counts") is not None else None if isinstance(work_counts, dict): - monitor_count = max( - 0, - safe_non_negative_int(work_counts.get("monitor")) - - watch_only_count, - ) - elif isinstance(monitor_open, list): - monitor_count = len( - [ - item - for item in monitor_open - if isinstance(item, dict) - and _todo_item_is_actionable_open(item) - and _todo_task_class(item) == TODO_TASK_CLASS_MONITOR - and not todo_item_is_watch_only_monitor(item) - ] - ) + advancement_count = safe_non_negative_int(work_counts.get("advancement")) + monitor_count = max(0, safe_non_negative_int(work_counts.get("monitor")) - watch_only_count) else: - monitor_count = safe_non_negative_int( - summary.get("claimed_monitor_open_count") + unclaimed_items = summary.get("unclaimed_priority_open_items") + advancement_count = ( + _count_advancement_items(executable) + if isinstance(executable, list) + else safe_non_negative_int(summary.get("claimed_advancement_open_count")) + + sum( + 1 for item in (unclaimed_items if isinstance(unclaimed_items, list) else ()) + if isinstance(item, dict) and _todo_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT + ) ) + monitor_count = ( + sum(1 for item in monitor_open if _is_actionable_monitor_item(item, watch_only=False)) + if isinstance(monitor_open, list) + else safe_non_negative_int(summary.get("claimed_monitor_open_count")) + ) + watch_only_due = safe_non_negative_int(summary.get("watch_only_monitor_due_count")) return { "open": open_count, "advancement": advancement_count, "monitor": monitor_count, - "monitor_due": max( - 0, - safe_non_negative_int(summary.get("monitor_due_count")) - - safe_non_negative_int(summary.get("watch_only_monitor_due_count")), - ), - "watch_only_monitor_due": safe_non_negative_int( - summary.get("watch_only_monitor_due_count") - ), + "monitor_due": max(0, safe_non_negative_int(summary.get("monitor_due_count")) - watch_only_due), + "watch_only_monitor_due": watch_only_due, } def _monitor_no_change_streak_trigger( - agent_todo_summary: dict[str, Any] | None, - *, - agent_id: str | None, -) -> dict[str, Any] | None: + agent_todo_summary: PayloadView | None, *, agent_id: str | None, +) -> Payload | None: if not isinstance(agent_todo_summary, dict): return None monitor_items = agent_todo_summary.get("monitor_open_items") if not isinstance(monitor_items, list): return None - - eligible = [] - for item in monitor_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 - if todo_item_is_watch_only_monitor(item): - continue - claimed_by = agent_scope_item_claimed_by(item) - if agent_id and claimed_by != agent_id: - continue - eligible.append(item) + eligible = [ + item for item in monitor_items + if _is_actionable_monitor_item(item, watch_only=False) + and (not agent_id or agent_scope_item_claimed_by(item) == agent_id) + ] if not eligible: return None # The enclosing frontier already established that no advancement is # selectable. Keep its eligibility facts, but share count/expiry/winner # selection and the existing public trigger with the typed replan owner. - return project_replan_history( - operation="frontier_monitor_streak", agent_id=agent_id, - agent_todos={"monitor_open_items": eligible}, - streak_threshold=MONITOR_NO_CHANGE_STREAK_THRESHOLD, + return cast( + Payload | None, + project_replan_history( + operation="frontier_monitor_streak", + agent_id=agent_id, + agent_todos={"monitor_open_items": eligible}, + streak_threshold=MONITOR_NO_CHANGE_STREAK_THRESHOLD, + ), ) def _frontier_advancement_counts( - *, - agent_todo_summary: dict[str, Any] | None, - agent_id: str | None, + *, agent_todo_summary: Payload | None, agent_id: str | None, ) -> dict[str, int]: - return todo_advancement_frontier_counts( - agent_todo_summary, - agent_id=agent_id, - ) + return todo_advancement_frontier_counts(agent_todo_summary, agent_id=agent_id) -def _compact_todo_id(item: Any) -> str | None: - if not isinstance(item, dict): - return None - todo_id = str(item.get("todo_id") or "").strip() - return todo_id or None +def _compact_todo_id(item: object) -> str | None: + return str(item.get("todo_id") or "").strip() or None if isinstance(item, dict) else None -def _deferred_successors( - summary: dict[str, Any] | None, - *, - agent_id: str | None, -) -> dict[str, Any]: - summary = summary if isinstance(summary, dict) else {} - counts = read_todo_deferred_work_counts(summary) - ready_items = [ - item - for item in (summary.get("deferred_resume_candidates") or []) - if isinstance(item, dict) - ] - ready_todo_ids = [ - todo_id for todo_id in (_compact_todo_id(item) for item in ready_items[:5]) if todo_id - ] - projection = { +def _deferred_successors(summary: Payload | None, *, agent_id: str | None) -> Payload: + summary_obj = summary if isinstance(summary, dict) else {} + counts = read_todo_deferred_work_counts(summary_obj) + raw_ready = summary_obj.get("deferred_resume_candidates") + ready_items = [i for i in (raw_ready if isinstance(raw_ready, list) else ()) if isinstance(i, dict)] + ready_todo_ids = [tid for i in ready_items[:5] if (tid := _compact_todo_id(i))] + projection: Payload = { "ready_count": counts["ready"], "blocked_count": counts["blocked"], "unknown_count": counts["unknown"], @@ -729,48 +409,37 @@ def _deferred_successors( return projection -def _is_monitor_only_lane( - work_lane_contract: dict[str, Any] | None, -) -> bool: +def _is_continuous_monitor_lane(work_lane_contract: PayloadView | None) -> bool: + return bool(work_lane_contract and work_lane_contract.get("lane") == TODO_TASK_CLASS_MONITOR) + + +def _is_monitor_only_lane(work_lane_contract: PayloadView | None) -> bool: return bool( _is_continuous_monitor_lane(work_lane_contract) + and work_lane_contract is not None and ( - cast(dict[str, Any], work_lane_contract).get("must_attempt_work") is False - or cast(dict[str, Any], work_lane_contract).get("monitor_kind") == "todo_monitor_due" + work_lane_contract.get("must_attempt_work") is False + or work_lane_contract.get("monitor_kind") == "todo_monitor_due" ) ) -def _is_continuous_monitor_lane( - work_lane_contract: dict[str, Any] | None, -) -> bool: - return bool( - work_lane_contract - and work_lane_contract.get("lane") == TODO_TASK_CLASS_MONITOR - ) - - -def _monitor_only_lane_has_future_schedule( - agent_todo_summary: dict[str, Any] | None, -) -> bool: +def _monitor_only_lane_has_future_schedule(agent_todo_summary: PayloadView | None) -> bool: if not isinstance(agent_todo_summary, dict): return False - if "monitor_due_count" not in agent_todo_summary: - return False - if "monitor_schedule_gap_count" not in agent_todo_summary: - return False - if safe_non_negative_int(agent_todo_summary.get("monitor_due_count")) > 0: + if "monitor_due_count" not in agent_todo_summary or "monitor_schedule_gap_count" not in agent_todo_summary: return False - if safe_non_negative_int(agent_todo_summary.get("monitor_schedule_gap_count")) > 0: + if ( + safe_non_negative_int(agent_todo_summary.get("monitor_due_count")) > 0 + or safe_non_negative_int(agent_todo_summary.get("monitor_schedule_gap_count")) > 0 + ): return False monitor_items = agent_todo_summary.get("monitor_open_items") return isinstance(monitor_items, list) and len(monitor_items) > 0 def _blocking_handoff_gate_count( - agent_todo_summary: dict[str, Any] | None, - *, - agent_id: str | None, + agent_todo_summary: Payload | None, *, agent_id: str | None, ) -> int: if not agent_id or not isinstance(agent_todo_summary, dict): return 0 @@ -778,150 +447,47 @@ def _blocking_handoff_gate_count( def _ready_deferred_successor_count( - agent_todo_summary: dict[str, Any] | None, - *, - agent_id: str | None, + agent_todo_summary: PayloadView | None, *, agent_id: str | None, ) -> int: if not isinstance(agent_todo_summary, dict): return 0 - current_count = safe_non_negative_int( - agent_todo_summary.get("current_agent_deferred_resume_count") - ) - unclaimed_count = safe_non_negative_int( - agent_todo_summary.get("unclaimed_deferred_resume_count") - ) + current_count = safe_non_negative_int(agent_todo_summary.get("current_agent_deferred_resume_count")) + unclaimed_count = safe_non_negative_int(agent_todo_summary.get("unclaimed_deferred_resume_count")) if current_count or unclaimed_count: return current_count + unclaimed_count - candidates = ( - cast(list[Any], agent_todo_summary.get("deferred_resume_candidates")) - if isinstance(agent_todo_summary.get("deferred_resume_candidates"), list) - else [] - ) - return len( - [ - item - for item in candidates - if isinstance(item, dict) - and agent_scope_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id) - ] - ) - - -def _replan_evidence_acknowledged( - items: list[dict[str, Any]], - latest_replan_ack: dict[str, Any] | None, - *, - time_key: str, -) -> bool: - """Return true when a valid replan ack postdates the newest evidence item. - - A gap that the agent already acknowledged with a repair delta must not - re-derive an endless replan obligation: without this, any stale gap turns - quota into a permanent run-now loop that no acknowledgement can settle. - """ - - if not items or not isinstance(latest_replan_ack, dict): - return False - ack_time = parse_timestamp(latest_replan_ack.get("generated_at")) - if ack_time is None: - return False - newest = max( - ( - timestamp - for item in items - if isinstance(item, dict) - if (timestamp := parse_timestamp(item.get(time_key))) is not None - ), - default=None, - ) - if newest is None: - return False - return ack_time >= newest - - -def _succession_gap_acknowledged( - gap_items: list[dict[str, Any]], - latest_replan_ack: dict[str, Any] | None, -) -> bool: - """Return true when a valid replan ack postdates the newest succession gap.""" - - semantic_delta = ( - cast(dict[str, Any], latest_replan_ack.get("semantic_delta")) - if isinstance(latest_replan_ack, dict) - and isinstance(latest_replan_ack.get("semantic_delta"), dict) - else {} - ) - if "new_runnable_successor" not in set(semantic_delta.get("outcomes") or []): - return False - return _replan_evidence_acknowledged( - gap_items, - latest_replan_ack, - time_key="completed_at", - ) - - -def _vision_gap_acknowledged( - acceptance_gaps: list[dict[str, Any]], - latest_replan_ack: dict[str, Any] | None, -) -> bool: - """Delegate exact acceptance holds and ordinary evidence freshness to TS.""" - - if not acceptance_gaps or not isinstance(latest_replan_ack, dict): - return False - return project_replan_semantics({ - "operation": "vision_ack", - "acceptance_gaps": acceptance_gaps, - "ack": latest_replan_ack, - })["acknowledged"] is True - - -def _acknowledged_replan_obligation_id( - latest_replan_ack: dict[str, Any] | None, -) -> str | None: - """Return the exact obligation generation closed by the latest ACK.""" - - semantic_delta = ( - cast(dict[str, Any], latest_replan_ack.get("semantic_delta")) - if isinstance(latest_replan_ack, dict) - and isinstance(latest_replan_ack.get("semantic_delta"), dict) - else {} - ) - return normalize_todo_replan_obligation_id( - semantic_delta.get("obligation_id") + candidates = agent_todo_summary.get("deferred_resume_candidates") + if not isinstance(candidates, list): + return 0 + return sum( + 1 for item in candidates + if isinstance(item, dict) and agent_scope_item_claimed_by_agent_or_unclaimed(item, agent_id=agent_id) ) def derive_goal_frontier_replan_obligation_from_summaries( *, - user_todo_summary: dict[str, Any] | None, - agent_todo_summary: dict[str, Any] | None, - work_lane_contract: dict[str, Any] | None, + user_todo_summary: Payload | None, + agent_todo_summary: Payload | None, + work_lane_contract: Payload | None, agent_id: str | None, - existing_replan_obligation: dict[str, Any] | None, - agent_todo_source_items: list[dict[str, Any]] | None = None, - latest_replan_ack: dict[str, Any] | None = None, - current_transition_replan_ack: dict[str, Any] | None = None, - acceptance_gaps: list[dict[str, Any]] | None = None, + existing_replan_obligation: Payload | None, + agent_todo_source_items: list[Payload] | None = None, + latest_replan_ack: Payload | None = None, + current_transition_replan_ack: Payload | None = None, + acceptance_gaps: list[Payload] | None = None, monitor_lane_semantically_valid: bool = True, - capability_obligation: dict[str, Any] | None = None, + capability_obligation: Payload | None = None, vision_settlement_query: bool = False, _frontier_counts: dict[str, int] | None = None, -) -> dict[str, Any] | None: - """Return a compact replan obligation when the goal frontier has no advancement. - - This keeps the per-goal completion/replan rule in the goal-frontier policy - seam. Quota should consume the resulting obligation instead of embedding - monitor/vision semantics in its scheduler path. - """ +) -> Payload | None: + """Return a compact replan obligation when the goal frontier has no advancement.""" agent_counts = _summary_task_counts(agent_todo_summary) # Only the enclosing context reduction supplies this fresh, same-agent # snapshot. Standalone callers still classify their current source. frontier_counts = ( _frontier_counts if _frontier_counts is not None - else _frontier_advancement_counts( - agent_todo_summary=agent_todo_summary, agent_id=agent_id, - ) + else _frontier_advancement_counts(agent_todo_summary=agent_todo_summary, agent_id=agent_id) ) total_frontier_advancement = sum(frontier_counts.values()) selectable_frontier_advancement = ( @@ -929,15 +495,12 @@ def derive_goal_frontier_replan_obligation_from_summaries( + frontier_counts["unclaimed_advancement_count"] ) monitor_no_change_trigger = ( - _monitor_no_change_streak_trigger( - agent_todo_summary, - agent_id=agent_id, - ) + _monitor_no_change_streak_trigger(agent_todo_summary, agent_id=agent_id) if selectable_frontier_advancement == 0 else None ) compact_acceptance_gaps = sorted( - (item for item in (acceptance_gaps or []) if isinstance(item, dict)), + (item for item in (acceptance_gaps or ()) if isinstance(item, dict)), # An enforced hold must survive the bounded trigger projection. Its # exact checkpoint is required to settle; generic vision gaps follow. key=lambda gap: gap.get("kind") not in GOAL_ACCEPTANCE_HOLD_TRIGGERS, @@ -946,24 +509,17 @@ def derive_goal_frontier_replan_obligation_from_summaries( # Diagnostic claim counts retain executor-excluded work. A causal # acceptance obligation needs an actually selectable Todo identity. selectable_frontier_advancement = len( - agent_scoped_selectable_advancement_todo_ids( - agent_todo_summary, agent_id=agent_id, - ) + agent_scoped_selectable_advancement_todo_ids(agent_todo_summary, agent_id=agent_id) ) successor_vision_required = any( - item.get("kind") - in {VISION_SUCCESSOR_GAP_TRIGGER, VISION_PROFILE_MISSING_TRIGGER} + item.get("kind") in {VISION_SUCCESSOR_GAP_TRIGGER, VISION_PROFILE_MISSING_TRIGGER} for item in compact_acceptance_gaps ) outcome_checkpoint_replan_required = any( - item.get("kind") - == outcome_continuity.VISION_OUTCOME_CHECKPOINT_REQUIRED_TRIGGER + item.get("kind") == outcome_continuity.VISION_OUTCOME_CHECKPOINT_REQUIRED_TRIGGER for item in compact_acceptance_gaps ) - succession_gap_items = todo_succession_gap_items( - agent_todo_summary, - agent_id=agent_id, - ) + succession_gap_items = todo_succession_gap_items(agent_todo_summary, agent_id=agent_id) long_chain_observation, long_chain_ack_decision = evaluate_long_todo_chain( agent_todo_summary=agent_todo_summary, agent_counts=agent_counts, @@ -972,364 +528,57 @@ def derive_goal_frontier_replan_obligation_from_summaries( agent_todo_source_items=agent_todo_source_items, latest_replan_ack=current_transition_replan_ack or latest_replan_ack, ) + future_schedule_present = _monitor_only_lane_has_future_schedule(agent_todo_summary) + summary_obj = agent_todo_summary or {} replan_rule = select_goal_frontier_replan_rule( GoalFrontierReplanFacts( - existing_replan_required=autonomous_replan_is_required( - existing_replan_obligation - ), - blocking_handoff_gate_count=_blocking_handoff_gate_count( - agent_todo_summary, - agent_id=agent_id, - ), - ready_deferred_successor_count=_ready_deferred_successor_count( - agent_todo_summary, - agent_id=agent_id, - ), + existing_replan_required=autonomous_replan_is_required(existing_replan_obligation), + blocking_handoff_gate_count=_blocking_handoff_gate_count(agent_todo_summary, agent_id=agent_id), + ready_deferred_successor_count=_ready_deferred_successor_count(agent_todo_summary, agent_id=agent_id), successor_vision_required=successor_vision_required, blocking_user_open_count=_blocking_user_open_count(user_todo_summary), user_open_count=_open_todo_count(user_todo_summary), succession_gap_count=len(succession_gap_items), - succession_gap_acknowledged=_succession_gap_acknowledged( - succession_gap_items, - latest_replan_ack, - ), - vision_gap_acknowledged=_vision_gap_acknowledged( - compact_acceptance_gaps, - latest_replan_ack, - ), + succession_gap_acknowledged=_succession_gap_acknowledged(succession_gap_items, latest_replan_ack), + vision_gap_acknowledged=_vision_gap_acknowledged(compact_acceptance_gaps, latest_replan_ack), agent_advancement_count=agent_counts.get("advancement", 0), total_frontier_advancement=total_frontier_advancement, acceptance_gap_count=len(compact_acceptance_gaps), # An already-admitted vision review may create its successor before # writeback. Reconstruct its source only for exact receipt validation; # this query never replaces the ordinary frontier decision. - selectable_frontier_advancement=( - 0 if vision_settlement_query else selectable_frontier_advancement - ), - outcome_checkpoint_replan_required=( - outcome_checkpoint_replan_required - ), + selectable_frontier_advancement=(0 if vision_settlement_query else selectable_frontier_advancement), + outcome_checkpoint_replan_required=outcome_checkpoint_replan_required, long_todo_chain_triggered=( long_chain_observation is not None and long_chain_ack_decision is not None and not long_chain_ack_decision.acknowledged ), - current_agent_blocker_count=safe_non_negative_int( - (agent_todo_summary or {}).get("current_agent_blocker_count") - ), + current_agent_blocker_count=safe_non_negative_int(summary_obj.get("current_agent_blocker_count")), capability_gap_pending=bool(capability_obligation and capability_obligation.get("required") is True), - monitor_no_change_streak_triggered=( - monitor_no_change_trigger is not None - ), + monitor_no_change_streak_triggered=monitor_no_change_trigger is not None, monitor_only_lane=_is_monitor_only_lane(work_lane_contract), monitor_count=agent_counts.get("monitor", 0), - monitor_due_count=safe_non_negative_int( - (agent_todo_summary or {}).get("monitor_due_count") - ), - monitor_schedule_gap_count=safe_non_negative_int( - (agent_todo_summary or {}).get("monitor_schedule_gap_count") - ), - future_monitor_schedule_present=( - _monitor_only_lane_has_future_schedule(agent_todo_summary) - ), + monitor_due_count=safe_non_negative_int(summary_obj.get("monitor_due_count")), + monitor_schedule_gap_count=safe_non_negative_int(summary_obj.get("monitor_schedule_gap_count")), + future_monitor_schedule_present=future_schedule_present, monitor_lane_semantically_valid=monitor_lane_semantically_valid, ) ) if not replan_rule.derives_obligation: return None - if replan_rule.rule is GoalFrontierReplanRule.CAPABILITY_EVIDENCE_GAP: - return capability_obligation - if replan_rule.rule is GoalFrontierReplanRule.TODO_SUCCESSION_GAP: - settlement_items = succession_gap_items[:3] - settlement_todo_ids = [ - str(item.get("todo_id") or "").strip() - for item in settlement_items - if str(item.get("todo_id") or "").strip() - ] - settlement_summary = ", ".join(settlement_todo_ids) - triggers = [ - { - "kind": TODO_SUCCESSION_GAP_TRIGGER, - "section": "agent_todo_summary.todo_succession_warning", - "todo_id": item.get("todo_id"), - "text": item.get("text") - or item.get("title") - or "completed advancement needs a successor or no-followup rationale", - "agent_id": agent_id, - "claimed_by": item.get("claimed_by"), - "completion_turn_key": item.get("completion_turn_key"), - } - for item in settlement_items - ] - return build_autonomous_replan_obligation_payload( - schema_version=AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION, - agent_id=agent_id, - include_agent_id=True, - stall_threshold=1, - trigger_count=len(succession_gap_items), - triggers=triggers, - guidance_actions=[ - "record_no_followup", - "link_successor", - "create_successor", - ], - todo_actions=[ - { - "action": "settle", - "role": "agent", - "priority": "P0", - "todo_ids": settlement_todo_ids, - "text": ( - "settle the completed scope using its original completion identity, or " - "record a genuine dependency on the mutable successor; do not update terminal links" - ), - }, - { - "action": "add", - "role": "agent", - "priority": "P0", - "text": ( - "create a typed runnable successor only when concrete " - "technical or validation work remains" - ), - }, - ], - stop_condition=( - "stop if the successor decision requires private material, " - "credentials, destructive git, production actions, or owner-only decisions" - ), - recommended_action=( - "settle the exact completed Todo(s) " - f"{settlement_summary} through loopx todo complete --no-follow-up " - "with the original completion identity when no follow-up remains in that scope. " - "Independent open/deferred work remains active. For genuine dependent work, " - "record its real readiness dependency on the mutable successor, preserving gates; " - "never add links to a terminal Todo; do not invent a user gate or lifecycle-only filler Todo" - ), - extra_fields={ - "resolution_mode": TODO_LIFECYCLE_SETTLEMENT_RESOLUTION_MODE, - "satisfying_semantic_outcomes": ["new_runnable_successor"], - }, - ) - if replan_rule.rule is GoalFrontierReplanRule.VISION_ACCEPTANCE_GAP: - acceptance_held = any( - gap.get("kind") in GOAL_ACCEPTANCE_HOLD_TRIGGERS for gap in compact_acceptance_gaps - ) - trigger_gaps = compact_acceptance_gaps[:3] - # Three independent holds may fill the detail slots. Preserve the - # canonical outcome owner's complete agent-set checkpoint as one more - # bounded trigger, so the same ACK can cover both sources without - # dropping a held Todo or acknowledging an unseen outcome revision. - outcome_gap = next((gap for gap in compact_acceptance_gaps - if gap.get("kind") == "goal_outcome_uncovered" - and gap.get("agent_id") == agent_id), None) - if outcome_gap is not None and outcome_gap not in trigger_gaps: - trigger_gaps.append(outcome_gap) - rearmed_after_obligation_id = _acknowledged_replan_obligation_id( - latest_replan_ack - ) - return build_autonomous_replan_obligation_payload( - schema_version=AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION, - agent_id=agent_id, - include_agent_id=True, - stall_threshold=1, - trigger_count=len(compact_acceptance_gaps), - triggers=[ - { - "kind": gap.get("kind") or VISION_ACCEPTANCE_GAP_TRIGGER, - "section": "goal_frontier_projection.acceptance_gaps", - "text": gap.get("replan_trigger_summary") - or "bounded agent vision reports an open acceptance gap", - "agent_id": agent_id, - "acceptance_summary": gap.get("acceptance_summary"), - "advancement_policy": gap.get("advancement_policy"), - **{ - key: gap.get(key) - for key in ( - "generated_at", - "completed_todo_id", - "completed_todo_count", - "completed_todo_threshold", - "completed_todo_ids", - "vision_todo_ids", - "frontier_revision", - "outcome_id", - "requirement_ids", - "legacy_frontier_revision", - "reason_code", - "component_checks", - "resolution_hint", - ) - if gap.get(key) is not None - }, - } - for gap in trigger_gaps - ], - guidance_actions=( - ["inspect_acceptance_binding", "select_eligible_successor", "record_evidence_gap"] - if acceptance_held else - ["create_successor", "update_agent_vision", "record_evidence_gap", "record_no_followup"] - ), - # Another unbound advancement Todo cannot repair this admission - # hold. Keep authoring suggestions aligned with the typed exits. - todo_actions=[] if acceptance_held else [ - { - "action": "add", - "role": "agent", - "priority": "P0", - "text": ( - "run a bounded vision-gap replan: create the next runnable " - "advancement todo or record an explicit no-follow-up rationale" - ), - } - ], - stop_condition=( - "stop if the gap requires private material, credentials, destructive git, " - "production actions, or owner-only decisions" - ), - recommended_action=( - " ".join( - str(gap["resolution_hint"]) - for gap in compact_acceptance_gaps - if gap.get("resolution_hint") - ) - if all(gap.get("resolution_hint") for gap in compact_acceptance_gaps) - else - "run a bounded vision-gap replan before another quiet poll: create " - "successor work, update the agent vision, record evidence gap, or " - "record no-follow-up" - ), - rearmed_after_obligation_id=rearmed_after_obligation_id, - ) - if replan_rule.rule is GoalFrontierReplanRule.LONG_TODO_CHAIN: - assert long_chain_observation is not None - assert long_chain_ack_decision is not None - long_chain_trigger = long_chain_observation.trigger - return build_autonomous_replan_obligation_payload( - schema_version=AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION, - agent_id=agent_id, - include_agent_id=True, - stall_threshold=cast(int, long_chain_trigger.get("threshold")), - trigger_count=cast(int, long_chain_trigger.get("trigger_count")), - triggers=[ - { - "kind": LONG_TODO_CHAIN_TRIGGER, - "section": "agent_todo_summary", - "text": ( - "current agent lane has a long claimed todo chain; " - "run a vision checkpoint/replan before continuing linearly" - ), - **long_chain_trigger, - } - ], - guidance_actions=[ - "use_replan_context", - "run_bounded_public_research_if_local_evidence_is_missing", - "group_or_prune_todo_chain", - "update_agent_vision", - "create_successor", - ], - todo_actions=[], - stop_condition=( - "stop if pruning or external research requires private material, " - "credentials, destructive git, production actions, or owner-only decisions" - ), - recommended_action=( - "run a bounded long-chain vision replan before continuing a 15+ " - "todo lane: read evidence, use public research if local evidence " - "is weak, group/prune work, and record an evidence-linked vision " - "path through replan_action_packet.writeback_contract using the " - "current Turn settlement binding; retain existing runnable work " - "when appropriate instead of adding a Todo whose only action is replan" - ), - rearmed_after_obligation_id=( - long_chain_ack_decision.rearmed_after_obligation_id - ), - ) - if replan_rule.rule is GoalFrontierReplanRule.MONITOR_NO_CHANGE_STREAK: - assert monitor_no_change_trigger is not None - return build_autonomous_replan_obligation_payload( - schema_version=AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION, - agent_id=agent_id, - include_agent_id=True, - stall_threshold=MONITOR_NO_CHANGE_STREAK_THRESHOLD, - trigger_count=1, - triggers=[monitor_no_change_trigger], - guidance_actions=[ - "set_watch_expiry", - "write_blocker", - "supersede_monitor", - "create_successor", - ], - todo_actions=[ - { - "action": "add", - "role": "agent", - "priority": "P1", - "text": ( - "resolve the stalled monitor lane with an expiry, blocker, " - "supersede transition, or runnable successor" - ), - } - ], - stop_condition=( - "stop if the replan requires private material, credentials, " - "destructive git, production actions, or owner-only decisions" - ), - recommended_action=( - "resolve the current agent's stalled monitor lane before another " - "quiet poll: set an expiry, write a blocker, supersede the monitor, " - "or create runnable successor work" - ), - ) - assert replan_rule.rule is GoalFrontierReplanRule.MONITOR_FRONTIER_EXHAUSTED - future_schedule_present = _monitor_only_lane_has_future_schedule(agent_todo_summary) - - return build_autonomous_replan_obligation_payload( - schema_version=AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION, - stall_threshold=1, - trigger_count=1, - triggers=[ - { - "kind": FRONTIER_EXHAUSTED_MONITOR_TRIGGER, - "section": "goal_frontier_projection", - "text": ( - "current goal frontier has no current, unclaimed, or other-agent " - "advancement todo while only monitor work remains" - ), - "agent_id": agent_id, - "agent_open_count": agent_counts.get("open", 0), - "agent_monitor_open_count": agent_counts.get("monitor", 0), - "future_monitor_schedule_present": future_schedule_present, - } - ], - guidance_actions=[ - "create_successor", - "supersede_monitor", - "set_watch_expiry", - "record_no_followup", - ], - todo_actions=[ - { - "action": "add", - "role": "agent", - "priority": "P1", - "text": ( - "run a compact goal-frontier replan: create a successor runnable " - "todo, supersede stale monitor work, set watch-lane expiry, or " - "record an explicit no-follow-up rationale" - ), - } - ], - stop_condition=( - "stop if the replan requires private material, credentials, destructive git, " - "production actions, or owner-only decisions" - ), - recommended_action=( - "run a bounded goal-frontier replan before another monitor-only quiet " - "poll: create successor work, supersede the monitor lane, set an expiry, " - "or record an evidence-backed no-follow-up outcome" - ), + return build_rule_replan_obligation( + replan_rule.rule, + agent_id=agent_id, + agent_counts=agent_counts, + future_schedule_present=future_schedule_present, + latest_replan_ack=latest_replan_ack, + compact_acceptance_gaps=compact_acceptance_gaps, + succession_gap_items=succession_gap_items, + capability_obligation=capability_obligation, + long_chain_observation=long_chain_observation, + long_chain_ack_decision=long_chain_ack_decision, + monitor_no_change_trigger=monitor_no_change_trigger, ) @@ -1337,24 +586,22 @@ def build_goal_frontier_projection_from_summaries( *, goal_id: str, agent_id: str | None, - user_todo_summary: dict[str, Any] | None, - agent_todo_summary: dict[str, Any] | None, - work_lane_contract: dict[str, Any] | None, - replan_obligation: dict[str, Any] | None, - acceptance_gaps: list[dict[str, Any]] | None = None, - vision_wait_state: dict[str, Any] | None = None, - fallback_gaps: list[dict[str, Any]] | None = None, + user_todo_summary: Payload | None, + agent_todo_summary: Payload | None, + work_lane_contract: Payload | None, + replan_obligation: Payload | None, + acceptance_gaps: list[Payload] | None = None, + vision_wait_state: Payload | None = None, + fallback_gaps: list[Payload] | None = None, _frontier_counts: dict[str, int] | None = None, -) -> dict[str, Any]: +) -> Payload: user_counts = _summary_task_counts(user_todo_summary) agent_counts = _summary_task_counts(agent_todo_summary) # Only the enclosing context reduction supplies this fresh, same-agent # snapshot. Standalone callers still classify their current source. frontier_counts = ( _frontier_counts if _frontier_counts is not None - else _frontier_advancement_counts( - agent_todo_summary=agent_todo_summary, agent_id=agent_id, - ) + else _frontier_advancement_counts(agent_todo_summary=agent_todo_summary, agent_id=agent_id) ) selectable_frontier_advancement = ( frontier_counts["current_agent_claimed_advancement_count"] @@ -1364,414 +611,341 @@ def build_goal_frontier_projection_from_summaries( _is_monitor_only_lane(work_lane_contract) and agent_counts.get("monitor", 0) > 0 and agent_counts.get("advancement", 0) == 0 - and ( - selectable_frontier_advancement == 0 - if agent_id - else sum(frontier_counts.values()) == 0 - ) + and (selectable_frontier_advancement == 0 if agent_id else sum(frontier_counts.values()) == 0) ) projection = build_goal_frontier_projection( goal_id=goal_id, agent_id=agent_id, user_counts=user_counts, agent_counts=agent_counts, - current_agent_claimed_advancement_count=frontier_counts[ - "current_agent_claimed_advancement_count" - ], + current_agent_claimed_advancement_count=frontier_counts["current_agent_claimed_advancement_count"], unclaimed_advancement_count=frontier_counts["unclaimed_advancement_count"], - other_agent_claimed_advancement_count=frontier_counts[ - "other_agent_claimed_advancement_count" - ], + other_agent_claimed_advancement_count=frontier_counts["other_agent_claimed_advancement_count"], monitor_only_lane=monitor_only_lane, replan_obligation=replan_obligation, acceptance_gaps=acceptance_gaps, vision_wait_state=vision_wait_state, fallback_gaps=fallback_gaps, - deferred_successors=_deferred_successors( - agent_todo_summary, - agent_id=agent_id, - ), + deferred_successors=_deferred_successors(agent_todo_summary, agent_id=agent_id), ) source_completeness, terminal_state = derive_goal_terminal_state( - user_todo_summary=user_todo_summary, - agent_todo_summary=agent_todo_summary, - projection=projection, + user_todo_summary=user_todo_summary, agent_todo_summary=agent_todo_summary, projection=projection, ) work_counts = (agent_todo_summary or {}).get("work_counts") - projection["normalized_progress"].update({ - "agent_counts_complete": isinstance(work_counts, dict) and work_counts.get("complete") is True, - "agent_unclassified_open_count": work_counts.get("hidden") if isinstance(work_counts, dict) else None, - }) + normalized_progress = projection.get("normalized_progress") + if isinstance(normalized_progress, dict): + normalized_progress.update({ + "agent_counts_complete": isinstance(work_counts, dict) and work_counts.get("complete") is True, + "agent_unclassified_open_count": work_counts.get("hidden") if isinstance(work_counts, dict) else None, + }) if terminal_state: projection["source_completeness"] = source_completeness projection["terminal_state"] = terminal_state return projection +def _obligation_satisfied_by_ack( + obligation: Payload | None, + ack: Payload | None, + *, + acceptance_gaps: list[Payload], + todo_succession_gap_open: bool, + stride_strategy: str, +) -> bool: + return bool( + autonomous_replan_is_required(obligation) + and autonomous_replan_ack_satisfies_obligation( + ack, + replan_obligation=obligation, + acceptance_gaps=acceptance_gaps, + todo_succession_gap_open=todo_succession_gap_open, + stride_strategy=stride_strategy, + ) + and autonomous_replan_ack_matches_frontier(ack, obligation) + ) + + +def _collect_receipt_bound_candidates( + *, + scoped_ack_history: list[Payload] | None, + latest_agent_replan_ack: Payload | None, + frontier_replan_obligation: Payload | None, + frontier_transition_candidate: Payload, + receipt_bound_replan_obligation_id: str | None, + receipt_bound_guard_recorded_at: str | None, + user_todo_summary: Payload | None, + agent_todo_summary: Payload | None, + work_lane_contract: Payload | None, + agent_id: str | None, + agent_todo_source_items: list[Payload] | None, + effective_replan_ack: Payload | None, + acceptance_gaps: list[Payload], + frontier_counts: dict[str, int], + stride_strategy: str, +) -> tuple[list[Payload], Payload, Payload | None]: + # A later durable Turn can have already acknowledged the exact review that + # an older receipt still owes. Keep that run-derived ACK distinct from a + # current-frontier transition: the settlement owner validates its exact + # Goal, Agent, obligation, chronology, and Turn before it can close the old + # writeback. Projected asset ACKs never enter this candidate. + historical_ack_candidates: list[Payload] = [ + {"historical_ack": dict(candidate)} + for candidate in (scoped_ack_history if isinstance(scoped_ack_history, list) else ())[:8] + if isinstance(candidate, dict) + ] + if latest_agent_replan_ack is not None and receipt_bound_replan_obligation_id: + historical_ack_candidates.append({"historical_ack": latest_agent_replan_ack}) + if frontier_replan_obligation is None and receipt_bound_replan_obligation_id: + source = derive_goal_frontier_replan_obligation_from_summaries( + user_todo_summary=user_todo_summary, agent_todo_summary=agent_todo_summary, + work_lane_contract=work_lane_contract, agent_id=agent_id, + existing_replan_obligation=None, agent_todo_source_items=agent_todo_source_items, + latest_replan_ack=effective_replan_ack, acceptance_gaps=acceptance_gaps, + vision_settlement_query=True, _frontier_counts=frontier_counts, + ) + if (source or {}).get("obligation_id") == receipt_bound_replan_obligation_id: + source_ack = replan_successor_transition_ack( + agent_todo_summary, agent_id=agent_id, replan_obligation=source, + agent_todo_items=agent_todo_source_items, stride_strategy=stride_strategy, + ) + frontier_transition_candidate = { + "obligation": source, "ack": source_ack, "reconstructed_vision_review": True, + } + + lifecycle_candidate = None + if receipt_bound_replan_obligation_id and receipt_bound_guard_recorded_at: + from ...work_items.lifecycle_recovery import receipt_bound_lifecycle_candidate + + lifecycle_candidate = receipt_bound_lifecycle_candidate( + selected_obligation_id=receipt_bound_replan_obligation_id, + guard_recorded_at=receipt_bound_guard_recorded_at, + agent_id=agent_id, + items=agent_todo_source_items or [], + derive=lambda summary: derive_goal_frontier_replan_obligation_from_summaries( + user_todo_summary=None, agent_todo_summary=summary, + work_lane_contract=work_lane_contract, agent_id=agent_id, + existing_replan_obligation=None, agent_todo_source_items=agent_todo_source_items, + # Reconstruct the admitted closed-row source, not the current + # frontier: independent agent work or user gates may have arrived + # after admission. This candidate still requires the original + # obligation digest; live gates retain authority over new work. + ), + ) + return historical_ack_candidates, frontier_transition_candidate, lifecycle_candidate + + def build_goal_frontier_projection_context_from_status( *, goal_id: str, agent_id: str | None, - status_payload: dict[str, Any], - item: dict[str, Any], - project_asset: dict[str, Any] | None, - user_todo_summary: dict[str, Any] | None, - agent_todo_summary: dict[str, Any] | None, - work_lane_contract: dict[str, Any] | None, + status_payload: Payload, + item: Payload, + project_asset: Payload | None, + user_todo_summary: Payload | None, + agent_todo_summary: Payload | None, + work_lane_contract: Payload | None, neutral_replan_ack_classifications: set[str], - agent_todo_source_items: list[dict[str, Any]] | None = None, + agent_todo_source_items: list[Payload] | None = None, fallback_todo_source_items: FallbackTodoSource = None, - available_capabilities: Any = None, + available_capabilities: object = None, registered_agent_ids: list[str] | None = None, goal_status: str | None = None, - agent_profile: dict[str, Any] | None = None, + agent_profile: Payload | None = None, receipt_bound_replan_obligation_id: str | None = None, receipt_bound_guard_recorded_at: str | None = None, - replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None = None, -) -> dict[str, Any]: - """Build the quota-facing goal-frontier read model. + replan_explore_reader: Callable[[str, str | None], PayloadView | None] | None = None, +) -> Payload: + """Build the quota-facing goal-frontier read model.""" - Quota decides delivery permission, but this helper owns the goal-frontier - state reduction: existing obligation scope, latest replan ACK, open - per-agent vision gaps, derived replan obligation, and final projection. - """ + def _scope(obligation: Payload | None) -> Payload: + return autonomous_replan_scope_decision( + obligation, agent_id=agent_id, registered_agent_ids=registered_agent_ids, + ) - replan_obligation = select_autonomous_replan_obligation( - item, - project_asset, - agent_id=agent_id, - ) + execution_profile_raw = (project_asset or {}).get("execution_profile") + execution_profile = execution_profile_raw if isinstance(execution_profile_raw, dict) else {} + stride_strategy = str(execution_profile.get("stride_strategy", "off")) + + def _transition_ack(obligation: Payload | None) -> Payload | None: + return replan_successor_transition_ack( + agent_todo_summary, agent_id=agent_id, replan_obligation=obligation, + agent_todo_items=agent_todo_source_items, stride_strategy=stride_strategy, + ) + + replan_obligation = select_autonomous_replan_obligation(item, project_asset, agent_id=agent_id) if replan_obligation: replan_obligation = ensure_replan_novelty_policy(replan_obligation) - replan_scope = autonomous_replan_scope_decision( - replan_obligation, - agent_id=agent_id, - registered_agent_ids=registered_agent_ids, - ) + replan_scope = _scope(replan_obligation) if replan_scope.get("required") and not replan_scope.get("applies"): replan_obligation = None latest_agent_replan_ack, scoped_ack_history = receipt_bound_replan_ack_history( - status_payload, - goal_id=goal_id, - agent_id=agent_id, + status_payload, goal_id=goal_id, agent_id=agent_id, neutral_classifications=neutral_replan_ack_classifications, receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id, ) latest_replan_ack_feedback = latest_replan_ack_feedback_from_status_payload( - status_payload, - goal_id=goal_id, - agent_id=agent_id, + status_payload, goal_id=goal_id, agent_id=agent_id, ) ack_time = parse_timestamp((latest_agent_replan_ack or {}).get("generated_at")) - feedback_time = parse_timestamp( - (latest_replan_ack_feedback or {}).get("generated_at") - ) + feedback_time = parse_timestamp((latest_replan_ack_feedback or {}).get("generated_at")) if ack_time is not None and feedback_time is not None and ack_time >= feedback_time: latest_replan_ack_feedback = None - latest_agent_vision = latest_agent_vision_from_status_payload( - status_payload, - goal_id=goal_id, - agent_id=agent_id, - ) + latest_agent_vision = latest_agent_vision_from_status_payload(status_payload, goal_id=goal_id, agent_id=agent_id) latest_missing_vision_checkpoint = latest_missing_vision_checkpoint_from_status_payload( - status_payload, - goal_id=goal_id, - agent_id=agent_id, + status_payload, goal_id=goal_id, agent_id=agent_id, ) - latest_vision_checkpoint = ( - outcome_continuity.latest_outcome_vision_checkpoint_from_status_payload( - status_payload, - goal_id=goal_id, - agent_id=agent_id, - ) + latest_vision_checkpoint = outcome_continuity.latest_outcome_vision_checkpoint_from_status_payload( + status_payload, goal_id=goal_id, agent_id=agent_id, ) source_acceptance_gaps = ( acceptance_gaps_from_agent_profile_requirement( - agent_profile, - agent_id=agent_id, - agent_vision=latest_agent_vision, - missing_checkpoint=latest_missing_vision_checkpoint, - ) - + acceptance_gaps_from_agent_vision( - latest_agent_vision, - goal_status=goal_status, - ) - + outcome_continuity.acceptance_gaps_from_vision_checkpoint( - latest_missing_vision_checkpoint - ) - + outcome_continuity.acceptance_gaps_from_outcome_checkpoint( - latest_agent_vision, - latest_vision_checkpoint, + agent_profile, agent_id=agent_id, + agent_vision=latest_agent_vision, missing_checkpoint=latest_missing_vision_checkpoint, ) + + acceptance_gaps_from_agent_vision(latest_agent_vision, goal_status=goal_status) + + outcome_continuity.acceptance_gaps_from_vision_checkpoint(latest_missing_vision_checkpoint) + + outcome_continuity.acceptance_gaps_from_outcome_checkpoint(latest_agent_vision, latest_vision_checkpoint) + ( [] - if ((project_asset or {}).get("execution_profile") or {}).get( - "replan_after_effective_turns" - ) is not None + if execution_profile.get("replan_after_effective_turns") is not None else outcome_continuity.acceptance_gaps_from_todo_completion_checkpoint( - latest_agent_vision, - latest_vision_checkpoint, - agent_todo_summary=agent_todo_summary, - agent_id=agent_id, - completed_todo_threshold=completed_todo_replan_threshold( - (project_asset or {}).get("execution_profile") - ), + latest_agent_vision, latest_vision_checkpoint, + agent_todo_summary=agent_todo_summary, agent_id=agent_id, + completed_todo_threshold=completed_todo_replan_threshold(execution_profile), ) ) + acceptance_gaps_from_outcomes(agent_todo_summary, agent_id=agent_id) - + acceptance_gaps_from_held_goal_binding( - agent_todo_summary, agent_todo_source_items, agent_id=agent_id, - ) + + acceptance_gaps_from_held_goal_binding(agent_todo_summary, agent_todo_source_items, agent_id=agent_id) ) if _terminal_no_followup_resolves_vision_checkpoint( - user_todo_summary=user_todo_summary, - agent_todo_summary=agent_todo_summary, + user_todo_summary=user_todo_summary, agent_todo_summary=agent_todo_summary, checkpoint=latest_missing_vision_checkpoint, ): source_acceptance_gaps = [ - gap - for gap in source_acceptance_gaps - if gap.get("kind") - != outcome_continuity.VISION_CHECKPOINT_MISSING_TRIGGER + gap for gap in source_acceptance_gaps + if gap.get("kind") != outcome_continuity.VISION_CHECKPOINT_MISSING_TRIGGER ] - todo_succession_gap_open = bool( - todo_succession_gap_items( - agent_todo_summary, - agent_id=agent_id, - ) - ) + todo_succession_gap_open = bool(todo_succession_gap_items(agent_todo_summary, agent_id=agent_id)) replan_obligation = align_autonomous_replan_guidance_with_acceptance_policy( - replan_obligation, - acceptance_gaps=source_acceptance_gaps, - ) - frontier_counts = _frontier_advancement_counts( - agent_todo_summary=agent_todo_summary, - agent_id=agent_id, + replan_obligation, acceptance_gaps=source_acceptance_gaps, ) + frontier_counts = _frontier_advancement_counts(agent_todo_summary=agent_todo_summary, agent_id=agent_id) # Commitment floors include open work held by a receipt-owned retry. The # typed selection projection, when complete for this lane, owns how much # work is actually runnable; a commitment is not an execution candidate. - selectable_advancement_count = todo_scoped_runnable_advancement_count( - agent_todo_summary, agent_id=agent_id, - ) + selectable_advancement_count = todo_scoped_runnable_advancement_count(agent_todo_summary, agent_id=agent_id) if selectable_advancement_count is None: selectable_advancement_count = ( frontier_counts["current_agent_claimed_advancement_count"] + frontier_counts["unclaimed_advancement_count"] ) vision_wait_state = build_goal_vision_wait_state( - agent_todo_summary=agent_todo_summary, - source_items=agent_todo_source_items, - agent_id=agent_id, - acceptance_gaps=source_acceptance_gaps, - selectable_advancement_count=selectable_advancement_count, + agent_todo_summary=agent_todo_summary, source_items=agent_todo_source_items, agent_id=agent_id, + acceptance_gaps=source_acceptance_gaps, selectable_advancement_count=selectable_advancement_count, ) acceptance_gaps = ( [gap for gap in source_acceptance_gaps if gap.get("kind") in GOAL_ACCEPTANCE_HOLD_TRIGGERS] - if vision_wait_state else source_acceptance_gaps - ) - declared_fallback_gaps = [ - gap - for gap in ( - declared_fallback_gap_from_agent_vision( - latest_agent_vision, - agent_todo_summary=agent_todo_summary, - agent_id=agent_id, - agent_todo_source_items=fallback_todo_source_items, - rollout_events=_latest_runs_for_goal( - status_payload, - goal_id=goal_id, - ), - available_capabilities=available_capabilities, - ), - ) - if isinstance(gap, dict) - ] - projected_replan_ack = projected_autonomous_replan_ack_for_agent( - item, - project_asset, - agent_id=agent_id, - ) + if vision_wait_state + else source_acceptance_gaps + ) + declared_fallback_gap = declared_fallback_gap_from_agent_vision( + latest_agent_vision, agent_todo_summary=agent_todo_summary, agent_id=agent_id, + agent_todo_source_items=fallback_todo_source_items, + rollout_events=_latest_runs_for_goal(status_payload, goal_id=goal_id), + available_capabilities=available_capabilities, + ) + declared_fallback_gaps = [declared_fallback_gap] if isinstance(declared_fallback_gap, dict) else [] + projected_replan_ack = projected_autonomous_replan_ack_for_agent(item, project_asset, agent_id=agent_id) + raw_runtime_root = status_payload.get("runtime_root") effective_replan_ack = project_legacy_acceptance_hold_ack( latest_agent_replan_ack or projected_replan_ack, acceptance_gaps=source_acceptance_gaps, goal_id=goal_id, agent_id=agent_id, - runtime_root=status_payload.get("runtime_root"), - ) - stride_strategy = ((project_asset or {}).get("execution_profile") or {}).get( - "stride_strategy", "off" - ) - replan_transition_ack = replan_successor_transition_ack( - agent_todo_summary, - agent_id=agent_id, - replan_obligation=replan_obligation, - agent_todo_items=agent_todo_source_items, - stride_strategy=stride_strategy, + runtime_root=raw_runtime_root if isinstance(raw_runtime_root, str) else None, ) + replan_transition_ack = _transition_ack(replan_obligation) # Keep the validated history-obligation transition distinct from any # successor frontier obligation derived below. Exact Turn settlement may # still owe this receipt even when the next decision has another duty. run_replan_transition_ack = replan_transition_ack run_transition_candidate = {"obligation": replan_obligation, "ack": replan_transition_ack} - obligation_ack = replan_transition_ack or effective_replan_ack - if ( - autonomous_replan_is_required(replan_obligation) - and autonomous_replan_ack_satisfies_obligation( - obligation_ack, - replan_obligation=replan_obligation, - acceptance_gaps=source_acceptance_gaps, - todo_succession_gap_open=todo_succession_gap_open, - stride_strategy=stride_strategy, - ) - and autonomous_replan_ack_matches_frontier( - obligation_ack, - replan_obligation, - ) + if _obligation_satisfied_by_ack( + replan_obligation, replan_transition_ack or effective_replan_ack, + acceptance_gaps=source_acceptance_gaps, todo_succession_gap_open=todo_succession_gap_open, + stride_strategy=stride_strategy, ): replan_obligation = None - replan_scope = autonomous_replan_scope_decision( - replan_obligation, - agent_id=agent_id, - registered_agent_ids=registered_agent_ids, - ) - frontier_replan_obligation = derive_goal_frontier_replan_obligation_from_summaries( - user_todo_summary=user_todo_summary, - agent_todo_summary=agent_todo_summary, - work_lane_contract=work_lane_contract, - agent_id=agent_id, - existing_replan_obligation=replan_obligation, - agent_todo_source_items=agent_todo_source_items, - latest_replan_ack=effective_replan_ack, - current_transition_replan_ack=replan_transition_ack, - _frontier_counts=frontier_counts, - acceptance_gaps=acceptance_gaps, - monitor_lane_semantically_valid=not goal_vision_state_is_closed( - (latest_agent_vision or {}).get("state") - ), - capability_obligation=(status_payload.get("bounded_research_frontier") or {}).get("obligation"), - ) - capability_transitions = (status_payload.get("bounded_research_frontier") or {}).get("settlement_transitions") or [] - frontier_transition_ack = next((candidate.get("ack") for candidate in capability_transitions - if candidate.get("obligation", {}).get("obligation_id") == (frontier_replan_obligation or {}).get("obligation_id")), None) if ( - frontier_replan_obligation or {} - ).get("capability_guard") else replan_successor_transition_ack( - agent_todo_summary, - agent_id=agent_id, - replan_obligation=frontier_replan_obligation, - agent_todo_items=agent_todo_source_items, - stride_strategy=stride_strategy, - ) - frontier_obligation_ack = frontier_transition_ack or effective_replan_ack - frontier_transition_candidate = {"obligation": frontier_replan_obligation, "ack": frontier_transition_ack} - # A later durable Turn can have already acknowledged the exact review that - # an older receipt still owes. Keep that run-derived ACK distinct from a - # current-frontier transition: the settlement owner validates its exact - # Goal, Agent, obligation, chronology, and Turn before it can close the old - # writeback. Projected asset ACKs never enter this candidate. - raw_historical_ack_candidates = scoped_ack_history - historical_ack_candidates = [ - {"historical_ack": dict(candidate)} - for candidate in ( - raw_historical_ack_candidates - if isinstance(raw_historical_ack_candidates, list) - else [] - )[:8] - if isinstance(candidate, dict) - ] - if latest_agent_replan_ack is not None and receipt_bound_replan_obligation_id: - historical_ack_candidates.append( - {"historical_ack": latest_agent_replan_ack} - ) - if frontier_replan_obligation is None and receipt_bound_replan_obligation_id: - source = derive_goal_frontier_replan_obligation_from_summaries( - user_todo_summary=user_todo_summary, agent_todo_summary=agent_todo_summary, - work_lane_contract=work_lane_contract, agent_id=agent_id, - existing_replan_obligation=None, agent_todo_source_items=agent_todo_source_items, - latest_replan_ack=effective_replan_ack, acceptance_gaps=acceptance_gaps, - vision_settlement_query=True, _frontier_counts=frontier_counts, - ) - if (source or {}).get("obligation_id") == receipt_bound_replan_obligation_id: - source_ack = replan_successor_transition_ack( - agent_todo_summary, agent_id=agent_id, replan_obligation=source, - agent_todo_items=agent_todo_source_items, - stride_strategy=stride_strategy, - ) - frontier_transition_candidate = { - "obligation": source, - "ack": source_ack, - "reconstructed_vision_review": True, - } + replan_scope = _scope(None) - lifecycle_candidate = None - if receipt_bound_replan_obligation_id and receipt_bound_guard_recorded_at: - from ...work_items.lifecycle_recovery import receipt_bound_lifecycle_candidate - lifecycle_candidate = receipt_bound_lifecycle_candidate( - selected_obligation_id=receipt_bound_replan_obligation_id, - guard_recorded_at=receipt_bound_guard_recorded_at, agent_id=agent_id, - items=agent_todo_source_items or [], - derive=lambda summary: derive_goal_frontier_replan_obligation_from_summaries( - user_todo_summary=None, agent_todo_summary=summary, - work_lane_contract=work_lane_contract, agent_id=agent_id, - existing_replan_obligation=None, agent_todo_source_items=agent_todo_source_items, - # Reconstruct the admitted closed-row source, not the current - # frontier: independent agent work or user gates may have arrived - # after admission. This candidate still requires the original - # obligation digest; live gates retain authority over new work. + raw_frontier = status_payload.get("bounded_research_frontier") + bounded_research_frontier = raw_frontier if isinstance(raw_frontier, dict) else {} + raw_capability_obligation = bounded_research_frontier.get("obligation") + frontier_replan_obligation = derive_goal_frontier_replan_obligation_from_summaries( + user_todo_summary=user_todo_summary, agent_todo_summary=agent_todo_summary, + work_lane_contract=work_lane_contract, agent_id=agent_id, + existing_replan_obligation=replan_obligation, agent_todo_source_items=agent_todo_source_items, + latest_replan_ack=effective_replan_ack, current_transition_replan_ack=replan_transition_ack, + _frontier_counts=frontier_counts, acceptance_gaps=acceptance_gaps, + monitor_lane_semantically_valid=not goal_vision_state_is_closed((latest_agent_vision or {}).get("state")), + capability_obligation=cast(Payload, raw_capability_obligation) if isinstance(raw_capability_obligation, dict) else None, + ) + raw_transitions = bounded_research_frontier.get("settlement_transitions") + capability_transitions = [c for c in raw_transitions if isinstance(c, dict)] if isinstance(raw_transitions, list) else [] + frontier_transition_ack = ( + next( + ( + cast(Payload | None, c.get("ack")) for c in capability_transitions + if isinstance(c.get("obligation"), dict) + and c["obligation"].get("obligation_id") == (frontier_replan_obligation or {}).get("obligation_id") ), + None, ) - - if ( - frontier_replan_obligation - and autonomous_replan_ack_satisfies_obligation( - frontier_obligation_ack, - replan_obligation=frontier_replan_obligation, - acceptance_gaps=source_acceptance_gaps, - todo_succession_gap_open=todo_succession_gap_open, - stride_strategy=stride_strategy, - ) - and autonomous_replan_ack_matches_frontier( - frontier_obligation_ack, - frontier_replan_obligation, - ) + if (frontier_replan_obligation or {}).get("capability_guard") + else _transition_ack(frontier_replan_obligation) + ) + frontier_transition_candidate: Payload = { + "obligation": frontier_replan_obligation, "ack": frontier_transition_ack, + } + historical_ack_candidates, frontier_transition_candidate, lifecycle_candidate = _collect_receipt_bound_candidates( + scoped_ack_history=scoped_ack_history, latest_agent_replan_ack=latest_agent_replan_ack, + frontier_replan_obligation=frontier_replan_obligation, + frontier_transition_candidate=frontier_transition_candidate, + receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id, + receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, + user_todo_summary=user_todo_summary, agent_todo_summary=agent_todo_summary, + work_lane_contract=work_lane_contract, agent_id=agent_id, + agent_todo_source_items=agent_todo_source_items, effective_replan_ack=effective_replan_ack, + acceptance_gaps=acceptance_gaps, frontier_counts=frontier_counts, stride_strategy=stride_strategy, + ) + if _obligation_satisfied_by_ack( + frontier_replan_obligation, frontier_transition_ack or effective_replan_ack, + acceptance_gaps=source_acceptance_gaps, todo_succession_gap_open=todo_succession_gap_open, + stride_strategy=stride_strategy, ): frontier_replan_obligation = None replan_transition_ack = frontier_transition_ack if frontier_replan_obligation: - replan_obligation = ensure_replan_novelty_policy( - frontier_replan_obligation - ) - replan_scope = autonomous_replan_scope_decision( - replan_obligation, - agent_id=agent_id, - registered_agent_ids=registered_agent_ids, - ) + replan_obligation = ensure_replan_novelty_policy(frontier_replan_obligation) + replan_scope = _scope(replan_obligation) replan_obligation = attach_rejected_replan_feedback(replan_obligation, latest_replan_ack_feedback) - + raw_goal_acceptance = (agent_todo_summary or {}).get("goal_acceptance_contract") replan_obligation = attach_receipt_replan_context( replan_obligation, lifecycle_candidate, goal_id=goal_id, agent_id=agent_id, source_status=status_payload, stride_strategy=stride_strategy, explore_reader=replan_explore_reader, todo_items=agent_todo_source_items, - goal_acceptance_contract=(agent_todo_summary or {}).get("goal_acceptance_contract"), + goal_acceptance_contract=raw_goal_acceptance if isinstance(raw_goal_acceptance, dict) else None, receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id, ) - goal_frontier_projection = build_goal_frontier_projection_from_summaries( - goal_id=goal_id, - agent_id=agent_id, - user_todo_summary=user_todo_summary, - agent_todo_summary=agent_todo_summary, - work_lane_contract=work_lane_contract, - replan_obligation=replan_obligation, - acceptance_gaps=acceptance_gaps, - vision_wait_state=vision_wait_state, - fallback_gaps=declared_fallback_gaps, + goal_id=goal_id, agent_id=agent_id, user_todo_summary=user_todo_summary, + agent_todo_summary=agent_todo_summary, work_lane_contract=work_lane_contract, + replan_obligation=replan_obligation, acceptance_gaps=acceptance_gaps, + vision_wait_state=vision_wait_state, fallback_gaps=declared_fallback_gaps, _frontier_counts=frontier_counts, ) if latest_replan_ack_feedback: - goal_frontier_projection["replan_ack_feedback"] = ( - latest_replan_ack_feedback - ) + goal_frontier_projection["replan_ack_feedback"] = latest_replan_ack_feedback return { "schema_version": "goal_frontier_projection_context_v0", "replan_obligation": replan_obligation, @@ -1792,170 +966,3 @@ def build_goal_frontier_projection_context_from_status( *([lifecycle_candidate] if lifecycle_candidate else []), ], } - - -def compact_replan_obligation(replan_obligation: dict[str, Any]) -> dict[str, Any]: - compact = { - "schema_version": replan_obligation.get("schema_version"), - "obligation_id": replan_obligation.get("obligation_id"), - "stall_threshold": replan_obligation.get("stall_threshold"), - "trigger_count": replan_obligation.get("trigger_count"), - "triggers": replan_obligation.get("triggers") or [], - "stop_condition": replan_obligation.get("stop_condition"), - } - if replan_obligation.get("frontier_identity"): - compact["frontier_identity"] = replan_obligation.get("frontier_identity") - if isinstance(replan_obligation.get("replan_novelty_policy"), dict): - # Keep hot quota/status packets on the two authoritative seams. The - # detailed selection hint remains available on the full obligation. - compact["replan_novelty_policy"] = { - "evidence_source": "compact_run_history", - "delivery": "host_projected", - "writeback": "typed_semantic_delta", - } - if isinstance(replan_obligation.get("replan_ack_feedback"), dict): - compact["replan_ack_feedback"] = replan_obligation["replan_ack_feedback"] - compact["recommended_action"] = replan_obligation.get("recommended_action") - return compact - - -def build_autonomous_replan_recommendation( - replan_obligation: dict[str, Any], - *, - reason: str | None = None, -) -> dict[str, Any]: - return { - "recommended_mode": AUTONOMOUS_REPLAN_REQUIRED_MODE, - "notify": "NOTIFY", - "replan_obligation": compact_replan_obligation(replan_obligation), - "spend_policy": ( - "append exactly one heartbeat spend only after executing the selected " - "replan slice, validating it, and writing back todo split/add/retire state" - ), - "reason": reason - or ( - "status exposes an autonomous replan obligation; advance the goal-level " - "planning-trigger slice before monitor-only or agent-scope wait " - "classification; replan turns always notify because DONT_NOTIFY would " - "mislead agents into a quiet no-op" - ), - } - - -def build_autonomous_replan_decision(replan_obligation: dict[str, Any]) -> dict[str, Any]: - triggers = ( - cast(list[Any], replan_obligation.get("triggers")) - if isinstance(replan_obligation.get("triggers"), list) - else [] - ) - return { - "schema_version": AUTONOMOUS_REPLAN_DECISION_SCHEMA_VERSION, - "required": True, - "decision": AUTONOMOUS_REPLAN_REQUIRED_MODE, - "decision_plane": "goal_frontier_before_lane_quiet_or_agent_scope_wait", - "not_disturbed_by": [ - "monitor_quiet_skip", - "agent_scope_wait", - "agent_scope_exhausted", - ], - "trigger_count": safe_non_negative_int(replan_obligation.get("trigger_count")), - "triggers": [ - trigger.get("kind") - for trigger in triggers - if isinstance(trigger, dict) and trigger.get("kind") - ], - } - - -def build_goal_frontier_projection( - *, - goal_id: str, - agent_id: str | None, - user_counts: dict[str, int], - agent_counts: dict[str, int], - current_agent_claimed_advancement_count: int, - unclaimed_advancement_count: int, - other_agent_claimed_advancement_count: int, - monitor_only_lane: bool, - replan_obligation: dict[str, Any] | None, - acceptance_gaps: list[dict[str, Any]] | None = None, - deferred_successors: dict[str, Any] | None = None, - vision_wait_state: dict[str, Any] | None = None, - fallback_gaps: list[dict[str, Any]] | None = None, -) -> dict[str, Any]: - replan_required = autonomous_replan_is_required(replan_obligation) - blockers: list[str] = [] - if monitor_only_lane: - blockers.append("monitor_only_lane") - if ( - current_agent_claimed_advancement_count == 0 - and unclaimed_advancement_count == 0 - and other_agent_claimed_advancement_count > 0 - ): - blockers.append("other_agent_claimed_advancement") - if replan_required: - blockers.append("autonomous_replan_obligation") - if isinstance(vision_wait_state, dict): - if vision_wait_state.get("reason_code") == "current_agent_blocker": - blockers.append("current_agent_blocker") - else: - blockers.append("vision_blocked_successor_wait") - - compact_acceptance_gaps = [ - item for item in (acceptance_gaps or []) if isinstance(item, dict) - ] - vision_continuation_audit = build_vision_continuation_audit( - goal_id=goal_id, - agent_id=agent_id, - acceptance_gaps=compact_acceptance_gaps, - ) - projection: dict[str, Any] = { - "schema_version": GOAL_FRONTIER_PROJECTION_SCHEMA_VERSION, - "goal_id": goal_id, - "agent_id": agent_id, - "source": "quota_should_run", - "normalized_progress": { - "user_open_count": user_counts.get("open", 0), - "agent_open_count": agent_counts.get("open", 0), - "agent_advancement_open_count": agent_counts.get("advancement", 0), - "agent_monitor_open_count": agent_counts.get("monitor", 0), - "agent_monitor_due_count": agent_counts.get("monitor_due", 0), - "agent_watch_only_monitor_due_count": agent_counts.get( - "watch_only_monitor_due", 0 - ), - }, - "remaining_advancement_frontier": { - "current_agent_claimed_advancement_count": current_agent_claimed_advancement_count, - "unclaimed_advancement_count": unclaimed_advancement_count, - "other_agent_claimed_advancement_count": other_agent_claimed_advancement_count, - }, - "monitor_only_lanes": { - "present": monitor_only_lane, - "quiet_until_material_transition": monitor_only_lane, - }, - "deferred_successors": deferred_successors - if isinstance(deferred_successors, dict) - else { - "ready_count": 0, - "blocked_count": 0, - "current_agent_ready_count": 0, - "ready_todo_ids": [], - }, - "acceptance_gaps": compact_acceptance_gaps[:5], - "autonomy_blockers": blockers, - "replan_required": replan_required, - } - if vision_continuation_audit: - projection["vision_continuation_audit"] = vision_continuation_audit - # Advisory-only field: unlike acceptance_gaps it is never cleared by the - # blocked-successor wait state, which is exactly when a declared fallback - # would otherwise disappear silently. - if fallback_gaps: - projection["fallback_gaps"] = fallback_gaps[:1] - if isinstance(vision_wait_state, dict): - projection["vision_wait_state"] = vision_wait_state - if replan_required and isinstance(replan_obligation, dict): - projection["autonomous_replan_decision"] = build_autonomous_replan_decision( - replan_obligation - ) - return projection diff --git a/loopx/control_plane/goals/goal_frontier/acceptance.py b/loopx/control_plane/goals/goal_frontier/acceptance.py index 9d7e9b145c..0a5fc09fcb 100644 --- a/loopx/control_plane/goals/goal_frontier/acceptance.py +++ b/loopx/control_plane/goals/goal_frontier/acceptance.py @@ -5,31 +5,79 @@ """ from __future__ import annotations -from typing import Any, cast - +from collections.abc import Mapping, Sequence import hashlib import json +from typing import cast from ...agents.agent_scope import agent_scope_item_claimed_by_agent_or_unclaimed +from ...agents.profile import agent_profile_requires_vision from ...effect_runtime import CANONICAL_AUTHORITY_READ_TIMEOUT_SECONDS, effect_runtime_result from ...todos.contract import normalize_todo_replan_obligation_id from ..acceptance_readback import configured_checks +Payload = dict[str, object] +PayloadView = Mapping[str, object] + GOAL_ACCEPTANCE_HOLD_TRIGGERS = frozenset({"goal_acceptance_stale", "goal_acceptance_unbound"}) +VISION_PROFILE_MISSING_TRIGGER = "required_agent_vision_missing" + + +def _as_mapping(value: object) -> PayloadView: + return cast(PayloadView, value) if isinstance(value, Mapping) else {} + + +def _as_list(value: object) -> list[object]: + return cast(list[object], value) if isinstance(value, list) else [] + + +def acceptance_gaps_from_agent_profile_requirement( + agent_profile: PayloadView | None, + *, + agent_id: str | None, + agent_vision: PayloadView | None, + missing_checkpoint: PayloadView | None, +) -> list[Payload]: + """Require a vision baseline for registered long-lived peer lanes.""" + + if ( + not agent_id + or not agent_profile_requires_vision(agent_profile) + or isinstance(agent_vision, dict) + or isinstance(missing_checkpoint, dict) + ): + return [] + return [ + { + "kind": VISION_PROFILE_MISSING_TRIGGER, + "source": "agent_profile", + "agent_id": agent_id, + "replan_trigger_summary": ( + "the registered long-lived agent lane requires a persisted vision " + "baseline before ordinary delivery or monitor-only quiet wait" + ), + "acceptance_summary": ( + "Write a bounded agent vision with objective, acceptance evidence, " + "advancement policy, and replan trigger; or explicitly mark the " + "profile vision requirement optional." + ), + "advancement_policy": "repeat_until_closed", + } + ] -def _hold_checkpoint_revision(identity: list[Any]) -> str: +def _hold_checkpoint_revision(identity: list[object]) -> str: return hashlib.sha256(json.dumps( identity, ensure_ascii=True, separators=(",", ":"), default=str, ).encode("utf-8")).hexdigest() def acceptance_gaps_from_held_goal_binding( - agent_todo_summary: dict[str, Any] | None, - source_items: list[dict[str, Any]] | None, + agent_todo_summary: PayloadView | None, + source_items: Sequence[PayloadView] | None, *, agent_id: str | None, -) -> list[dict[str, Any]]: +) -> list[Payload]: """Route missing or stale acceptance through this agent's replan lane. This is a read-only trigger, not an acceptance rebind. Other runnable work @@ -44,12 +92,12 @@ def acceptance_gaps_from_held_goal_binding( return [] held_states = { task.get("todo_id"): task.get("state") - for task in contract.get("tasks", []) + for task in _as_list(contract.get("tasks")) if isinstance(task, dict) and task.get("state") in {"stale", "unbound"} and task.get("applicable") is True } - gaps: list[dict[str, Any]] = [] + gaps: list[Payload] = [] for item in source_items or []: if ( not isinstance(item, dict) @@ -69,7 +117,7 @@ def acceptance_gaps_from_held_goal_binding( # useful readback, but only a real contract revision changes this basis. owner_basis = [contract.get("digest"), contract.get("revision"), state] frontier_revision = _hold_checkpoint_revision([todo_id, *owner_basis]) - gap = { + gap: Payload = { "kind": kind, "source": "goal_acceptance_contract", "agent_id": agent_id, @@ -102,23 +150,26 @@ def acceptance_gaps_from_held_goal_binding( return gaps -def acceptance_gaps_from_outcomes(agent_todo_summary: dict[str, Any] | None, *, agent_id: str | None) -> list[dict[str, Any]]: +def acceptance_gaps_from_outcomes(agent_todo_summary: PayloadView | None, *, agent_id: str | None) -> list[Payload]: """Transport the typed owner's scoped coverage gaps to existing replan.""" - contract = (agent_todo_summary or {}).get("goal_acceptance_contract") or {} - declarations = contract.get("outcome_requirements") or {} - objective = contract.get("goal_objective") or {} - return [dict(gap) for gap in [*declarations.get("acceptance_gaps", []), *objective.get("acceptance_gaps", [])] - if isinstance(gap, dict) and agent_id and gap.get("agent_id") == agent_id] + contract = _as_mapping((agent_todo_summary or {}).get("goal_acceptance_contract")) + declarations = _as_mapping(contract.get("outcome_requirements")) + objective = _as_mapping(contract.get("goal_objective")) + return [ + {str(k): v for k, v in gap.items()} + for gap in [*_as_list(declarations.get("acceptance_gaps")), *_as_list(objective.get("acceptance_gaps"))] + if isinstance(gap, dict) and agent_id and gap.get("agent_id") == agent_id + ] def project_legacy_acceptance_hold_ack( - ack: dict[str, Any] | None, + ack: Payload | None, *, - acceptance_gaps: list[dict[str, Any]], + acceptance_gaps: Sequence[PayloadView], goal_id: str, agent_id: str | None, runtime_root: str | None, -) -> dict[str, Any] | None: +) -> Payload | None: """Read an old ACK against its exact canonical source, without rewriting it. The old checkpoint included the Todo timestamp. Its run's retained source @@ -128,19 +179,20 @@ def project_legacy_acceptance_hold_ack( same Todo, owner contract digest/revision and hold state. No historical source, unknown checkpoint or changed owner basis can acquire this mapping. """ - delta = (ack or {}).get("semantic_delta") or {} + delta = _as_mapping((ack or {}).get("semantic_delta")) checkpoints = delta.get("trigger_checkpoints") current = {(gap.get("kind"), gap.get("frontier_revision")) for gap in acceptance_gaps if gap.get("kind") in GOAL_ACCEPTANCE_HOLD_TRIGGERS} if (not current or not isinstance(checkpoints, list) or not runtime_root or - (ack or {}).get("recorded") is not True or delta.get("accepted") is not True or - (ack or {}).get("agent_id") != agent_id or + not isinstance(ack, dict) or + ack.get("recorded") is not True or delta.get("accepted") is not True or + ack.get("agent_id") != agent_id or not normalize_todo_replan_obligation_id(delta.get("obligation_id"))): return ack legacy = [checkpoint for checkpoint in checkpoints if isinstance(checkpoint, dict) and checkpoint.get("kind") in GOAL_ACCEPTANCE_HOLD_TRIGGERS and (checkpoint.get("kind"), checkpoint.get("frontier_revision")) not in current] - anchor = (ack or {}).get("todo_source") + anchor = ack.get("todo_source") if not legacy or not isinstance(anchor, dict): return ack source = effect_runtime_result("coordination.local_authority.todo_source", { @@ -151,10 +203,13 @@ def project_legacy_acceptance_hold_ack( source.get("source") != anchor or source.get("decision_read_from_provider") is not True or source.get("legacy_fallback_used") is not False): return ack + raw_todos = source.get("todos") + todos_seq = [item for item in raw_todos if isinstance(item, dict)] if isinstance(raw_todos, list) else None + raw_contract = source.get("goal_acceptance_contract") old = {(gap["kind"], gap["frontier_revision"]): gap["legacy_frontier_revision"] for gap in acceptance_gaps_from_held_goal_binding( - {"goal_acceptance_contract": source.get("goal_acceptance_contract")}, - source.get("todos"), agent_id=agent_id, + {"goal_acceptance_contract": raw_contract}, + todos_seq, agent_id=agent_id, )} verified = {(kind, previous): revision for (kind, revision), previous in old.items() if (kind, revision) in current} @@ -163,4 +218,4 @@ def project_legacy_acceptance_hold_ack( )} if isinstance(checkpoint, dict) else checkpoint for checkpoint in checkpoints] # This ephemeral projection feeds the existing exact typed ACK comparison. # Keep the original obligation identity, outcomes, durable record and debit. - return {**cast(dict[str, Any], ack), "semantic_delta": {**delta, "trigger_checkpoints": projected}} + return {**ack, "semantic_delta": {**delta, "trigger_checkpoints": projected}} diff --git a/loopx/control_plane/goals/goal_frontier/ack_policy.py b/loopx/control_plane/goals/goal_frontier/ack_policy.py index a7ca7268bc..388e766d46 100644 --- a/loopx/control_plane/goals/goal_frontier/ack_policy.py +++ b/loopx/control_plane/goals/goal_frontier/ack_policy.py @@ -1,10 +1,9 @@ from __future__ import annotations -from typing import Any, TypeGuard, cast - - -from collections.abc import Iterable +from collections.abc import Iterable, Mapping, Sequence +from typing import TypeGuard, cast +from ...runtime.time import parse_timestamp from ...todos.contract import ( TODO_TASK_CLASS_ADVANCEMENT, normalize_todo_claimed_by, @@ -14,6 +13,10 @@ ) from ...todos.todo_semantics import todo_item_is_actionable_open, todo_item_task_class from ...todos.succession_warning import TODO_SUCCESSION_WARNING_REASON_CODE +from ...work_items.autonomous_replan_ack import ( + autonomous_replan_ack_matches_agent, + normalize_projected_autonomous_replan_ack, +) from ...work_items.progress_observation import ( replan_obligation_trigger_checkpoints, replan_obligation_trigger_kinds, @@ -21,13 +24,18 @@ required_semantic_outcomes, ) from ...work_items.autonomous_replan_obligation import ensure_replan_novelty_policy +from ...work_items.replan_semantics_codec import project_replan_semantics from .long_todo_chain import ( LONG_TODO_CHAIN_TRIGGER, long_todo_chain_successor_checkpoints, ) -def autonomous_replan_ack_has_frontier_delta(ack: dict[str, Any] | None) -> TypeGuard[dict[str, Any]]: +Payload = dict[str, object] +PayloadView = Mapping[str, object] + + +def autonomous_replan_ack_has_frontier_delta(ack: PayloadView | None) -> TypeGuard[Payload]: if not isinstance(ack, dict) or ack.get("recorded") is not True: return False semantic_delta = ack.get("semantic_delta") @@ -39,10 +47,10 @@ def autonomous_replan_ack_has_frontier_delta(ack: dict[str, Any] | None) -> Type def autonomous_replan_ack_satisfies_obligation( - ack: dict[str, Any] | None, + ack: PayloadView | None, *, - replan_obligation: dict[str, Any] | None, - acceptance_gaps: list[dict[str, Any]] | None, + replan_obligation: PayloadView | None, + acceptance_gaps: Sequence[PayloadView] | None, todo_succession_gap_open: bool = False, stride_strategy: str = "off", ) -> bool: @@ -50,12 +58,13 @@ def autonomous_replan_ack_satisfies_obligation( if not autonomous_replan_ack_has_frontier_delta(ack): return False + obligation = replan_obligation or {} if ack.get("source") == "todo_replan_successor_transition" and not replan_successor_transition_allowed( - replan_obligation or {}, stride_strategy=stride_strategy, + obligation, stride_strategy=stride_strategy, ): return False semantic_delta = ack.get("semantic_delta") if isinstance(ack, dict) else {} - obligation_id = str((replan_obligation or {}).get("obligation_id") or "").strip() + obligation_id = str(obligation.get("obligation_id") or "").strip() acknowledged_obligation_id = str( semantic_delta.get("obligation_id") if isinstance(semantic_delta, dict) @@ -63,35 +72,32 @@ def autonomous_replan_ack_satisfies_obligation( ).strip() if not obligation_id or acknowledged_obligation_id != obligation_id: return False + raw_outcomes = semantic_delta.get("outcomes") if isinstance(semantic_delta, dict) else None outcomes = { str(item or "").strip() - for item in ( - semantic_delta.get("outcomes") or [] - if isinstance(semantic_delta, dict) - else [] - ) + for item in (raw_outcomes if isinstance(raw_outcomes, list) else ()) if str(item or "").strip() } - required = set(required_semantic_outcomes(replan_obligation or {})) + required = set(required_semantic_outcomes(obligation)) # Other completed work keeps its own succession duty. It must not veto an # exact accepted receipt for an independent monitor or review obligation. if ( todo_succession_gap_open and TODO_SUCCESSION_WARNING_REASON_CODE - in replan_obligation_trigger_kinds(replan_obligation or {}) + in replan_obligation_trigger_kinds(obligation) ): outcomes.intersection_update({"new_runnable_successor"}) return bool(outcomes & required) def replan_successor_transition_ack( - agent_todo_summary: dict[str, Any] | None, + agent_todo_summary: PayloadView | None, *, agent_id: str | None, - replan_obligation: dict[str, Any] | None, - agent_todo_items: Iterable[dict[str, Any]] | None = None, + replan_obligation: PayloadView | None, + agent_todo_items: Iterable[PayloadView] | None = None, stride_strategy: str = "off", -) -> dict[str, Any] | None: +) -> Payload | None: """Project an exact runnable-successor Todo as the replan receipt. The Todo row is the durable fact. No prose classification and no second @@ -99,24 +105,28 @@ def replan_successor_transition_ack( still open, advancement-class, runnable, and owned by the same agent. """ + obligation = replan_obligation or {} obligation_id = normalize_todo_replan_obligation_id( - (replan_obligation or {}).get("obligation_id") + obligation.get("obligation_id") ) safe_agent_id = normalize_todo_claimed_by(agent_id) if not obligation_id or not safe_agent_id: return None if agent_todo_items is None: - source_items = ( - cast(list[Any], agent_todo_summary.get("first_executable_items")) + raw_executable = ( + agent_todo_summary.get("first_executable_items") if isinstance(agent_todo_summary, dict) - and isinstance(agent_todo_summary.get("first_executable_items"), list) - else [] + else None ) + source_items: list[Payload] = [ + item for item in (raw_executable if isinstance(raw_executable, list) else ()) + if isinstance(item, dict) + ] else: source_items = [ - item for item in agent_todo_items if isinstance(item, dict) + cast(Payload, item) for item in agent_todo_items if isinstance(item, dict) ] - trigger_kinds = replan_obligation_trigger_kinds(replan_obligation or {}) + trigger_kinds = replan_obligation_trigger_kinds(obligation) candidates = [item for item in source_items if todo_item_is_actionable_open(item) and todo_item_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT @@ -130,10 +140,12 @@ def replan_successor_transition_ack( trigger_checkpoints: list[dict[str, str]] | None = None eligible_ids = {item["todo_id"] for item in candidates if item["replan_obligation_id"] == obligation_id} if LONG_TODO_CHAIN_TRIGGER in trigger_kinds: + raw_triggers = obligation.get("triggers") + triggers_arg = [item for item in raw_triggers if isinstance(item, dict)] if isinstance(raw_triggers, list) else [] source_checkpoint = long_todo_chain_successor_checkpoints( source_items, agent_id=safe_agent_id, - triggers=(replan_obligation or {}).get("triggers") or [], + triggers=triggers_arg, obligation_id=obligation_id, candidates=[{"todo_id": item["todo_id"], "updated_at": item.get("updated_at"), "origin_obligation_id": item["replan_obligation_id"]} for item in candidates], @@ -150,10 +162,10 @@ def replan_successor_transition_ack( if binding["kind"] == "exact": eligible_ids.add(binding["todo_id"]) elif binding["kind"] == "predecessor": - prior = ensure_replan_novelty_policy({**(replan_obligation or {}), "triggers": [ + prior = ensure_replan_novelty_policy({**obligation, "triggers": [ {**trigger, "frontier_revision": binding["frontier_revision"], "obligation_identity_revision": binding["obligation_identity_revision"]} - for trigger in (replan_obligation or {}).get("triggers") or []]}) + for trigger in triggers_arg]}) if prior["obligation_id"] == origins[binding["todo_id"]]: eligible_ids.add(binding["todo_id"]) successor = next((item for item in candidates if item["todo_id"] in eligible_ids), None) @@ -168,17 +180,17 @@ def replan_successor_transition_ack( if successor_binding is None: return None if not replan_successor_transition_allowed( - replan_obligation or {}, stride_strategy=stride_strategy, + obligation, stride_strategy=stride_strategy, ): return None if trigger_checkpoints is None: - trigger_checkpoints = replan_obligation_trigger_checkpoints(replan_obligation or {}) + trigger_checkpoints = replan_obligation_trigger_checkpoints(obligation) semantic_delta = { "schema_version": "replan_semantic_delta_v0", "accepted": True, "outcomes": ["new_runnable_successor"], "satisfying_outcomes": ["new_runnable_successor"], - "required_any_of": required_semantic_outcomes(replan_obligation or {}), + "required_any_of": required_semantic_outcomes(obligation), "trigger_kinds": trigger_kinds, "trigger_checkpoints": trigger_checkpoints, "obligation_id": obligation_id, @@ -190,7 +202,7 @@ def replan_successor_transition_ack( "successor" ), } - ack = { + ack: Payload = { "schema_version": "autonomous_replan_ack_v0", "recorded": True, "source": "todo_replan_successor_transition", @@ -199,7 +211,7 @@ def replan_successor_transition_ack( "semantic_delta": semantic_delta, } frontier_identity = str( - (replan_obligation or {}).get("frontier_identity") or "" + obligation.get("frontier_identity") or "" ).strip() if frontier_identity: ack["frontier_identity"] = frontier_identity @@ -207,18 +219,115 @@ def replan_successor_transition_ack( def attach_rejected_replan_feedback( - obligation: dict[str, Any] | None, feedback: dict[str, Any] | None, -) -> dict[str, Any] | None: + obligation: PayloadView | None, feedback: PayloadView | None, +) -> Payload | None: """Preserve the existing rejected-claim readback without changing the duty.""" if not obligation or not feedback: - return obligation - obligation = dict(obligation) - obligation["replan_ack_feedback"] = feedback - first_claim = next((item for item in feedback.get("rejected_claims") or [] + return dict(obligation) if isinstance(obligation, dict) else None + updated: Payload = dict(obligation) + updated["replan_ack_feedback"] = feedback + raw_claims = feedback.get("rejected_claims") + first_claim = next((item for item in (raw_claims if isinstance(raw_claims, list) else ()) if isinstance(item, dict)), None) if first_claim: - obligation["recommended_action"] = ( + updated["recommended_action"] = ( "previous replan ACK was rejected: " f"{first_claim.get('kind')}: {first_claim.get('reason')}; " - + str(obligation.get("recommended_action") or "replan again")) - return obligation + + str(updated.get("recommended_action") or "replan again")) + return updated + + +def _ack_semantic_delta(latest_replan_ack: PayloadView | None) -> PayloadView: + if not isinstance(latest_replan_ack, Mapping): + return {} + semantic_delta = latest_replan_ack.get("semantic_delta") + return cast(PayloadView, semantic_delta) if isinstance(semantic_delta, Mapping) else {} + + +def projected_autonomous_replan_ack_for_agent( + item: PayloadView, + project_asset: PayloadView | None, + *, + agent_id: str | None, +) -> Payload | None: + """Return the current projected replan ACK when it belongs to this agent.""" + + asset = project_asset if isinstance(project_asset, dict) else {} + for candidate in (item.get("autonomous_replan_ack"), asset.get("autonomous_replan_ack")): + if not isinstance(candidate, dict): + continue + normalized = normalize_projected_autonomous_replan_ack(candidate) + if autonomous_replan_ack_matches_agent(normalized, agent_id=agent_id): + return cast(Payload, normalized) + return None + + +def _replan_evidence_acknowledged( + items: Sequence[Mapping[str, object]], + latest_replan_ack: Mapping[str, object] | None, + *, + time_key: str, +) -> bool: + """Return true when a valid replan ack postdates the newest evidence item. + + A gap that the agent already acknowledged with a repair delta must not + re-derive an endless replan obligation: without this, any stale gap turns + quota into a permanent run-now loop that no acknowledgement can settle. + """ + + if not items or not isinstance(latest_replan_ack, Mapping): + return False + ack_time = parse_timestamp(latest_replan_ack.get("generated_at")) + if ack_time is None: + return False + newest = max( + ( + timestamp + for item in items + if isinstance(item, dict) + if (timestamp := parse_timestamp(item.get(time_key))) is not None + ), + default=None, + ) + return newest is not None and ack_time >= newest + + +def _succession_gap_acknowledged( + gap_items: Sequence[Mapping[str, object]], + latest_replan_ack: Mapping[str, object] | None, +) -> bool: + """Return true when a valid replan ack postdates the newest succession gap.""" + + outcomes = _ack_semantic_delta(latest_replan_ack).get("outcomes") + if "new_runnable_successor" not in set(outcomes if isinstance(outcomes, list) else ()): + return False + return _replan_evidence_acknowledged( + gap_items, + latest_replan_ack, + time_key="completed_at", + ) + + +def _vision_gap_acknowledged( + acceptance_gaps: Sequence[PayloadView], + latest_replan_ack: PayloadView | None, +) -> bool: + """Delegate exact acceptance holds and ordinary evidence freshness to TS.""" + + if not acceptance_gaps or not isinstance(latest_replan_ack, dict): + return False + return project_replan_semantics({ + "operation": "vision_ack", + "acceptance_gaps": list(acceptance_gaps), + "ack": latest_replan_ack, + })["acknowledged"] is True + + +def _acknowledged_replan_obligation_id( + latest_replan_ack: Mapping[str, object] | None, +) -> str | None: + """Return the exact obligation generation closed by the latest ACK.""" + + return normalize_todo_replan_obligation_id( + _ack_semantic_delta(latest_replan_ack).get("obligation_id") + ) diff --git a/loopx/control_plane/goals/goal_frontier/projection.py b/loopx/control_plane/goals/goal_frontier/projection.py new file mode 100644 index 0000000000..f12b75452a --- /dev/null +++ b/loopx/control_plane/goals/goal_frontier/projection.py @@ -0,0 +1,305 @@ +"""Read-model projection and vision-audit payload builders for goal_frontier.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +from ..goal_vision_read_model import _compact_projection_text + +Payload = dict[str, object] +PayloadView = Mapping[str, object] + +GOAL_FRONTIER_PROJECTION_SCHEMA_VERSION = "goal_frontier_projection_v0" +VISION_CONTINUATION_AUDIT_SCHEMA_VERSION = "vision_continuation_audit_v0" +VISION_GAP_JUDGE_SCHEMA_VERSION = "vision_gap_judge_v0" +AUTONOMOUS_REPLAN_DECISION_SCHEMA_VERSION = "autonomous_replan_decision_v0" +AUTONOMOUS_REPLAN_REQUIRED_MODE = "autonomous_replan_required" + + +def safe_non_negative_int(value: object) -> int: + if not value or not isinstance(value, (int, float, str, bytes, bytearray)): + return 0 + try: + return max(0, int(value)) + except (TypeError, ValueError): + return 0 + + +def autonomous_replan_is_required(replan_obligation: PayloadView | None) -> bool: + return bool(replan_obligation and replan_obligation.get("required")) + + +def build_vision_gap_judge( + *, + goal_id: str | None = None, + agent_id: str | None, + acceptance_gaps: Sequence[PayloadView] | None, +) -> Payload: + """Return the strict done/continue judge for active per-agent vision gaps.""" + + first_gap = next((g for g in (acceptance_gaps or ()) if isinstance(g, dict)), {}) + reason = _compact_projection_text( + first_gap.get("replan_trigger_summary") + or "active per-agent vision still has an open acceptance gap", + limit=220, + ) + return { + "schema_version": VISION_GAP_JUDGE_SCHEMA_VERSION, + "goal_id": goal_id, + "agent_id": agent_id, + "done": False, + "decision": "continue", + "reason": reason or "active per-agent vision still has an open acceptance gap", + "agent_judge_instruction": ( + "Judge vision closure: compare active vision acceptance_summary " + "with the host-projected agent-scoped coverage ledger. " + "Inspect permitted registry-declared material references before bounded " + "public web research. " + "Mark done only when evidence proves completion, a blocker/user " + "gate, or superseding/no-follow-up closure; otherwise continue." + ), + "evidence_read_instruction": ( + "Use the host-projected compact coverage ledger and uncovered frontier. " + "The agent-scoped evidence log remains the durable source and an optional " + "diagnostic readback, not a model-executed closure gate." + ), + "registry_read_instruction": ( + "Before external research, inspect the selected goal's registry-declared " + "topic_authority and project_materials metadata, preferring any projected " + "replan_context or agent_material_frontier. Use role, freshness, revision, " + "boundary, gate_status, and conflict_rule to choose permitted references. " + "Registration guides discovery; it neither grants access nor proves acceptance." + ), + "external_research_instruction": ( + "If projected evidence, the evidence log, and permitted registry-declared " + "references remain missing, stale, or too weak and the acceptance question " + "depends on public facts, run bounded public web research using primary or " + "authoritative sources; record confirmed/refuted findings as public-safe " + "evidence or a compact vision replan trigger before judging." + ), + "research_writeback_required_when_used": [ + "source_url_or_public_reference", "confirmed_or_refuted_finding", + "supports_or_refutes_acceptance_gap", "successor_todo_or_vision_replan_trigger", + ], + "done_only_when": [ + "authoritative_evidence_satisfies_acceptance", + "final_deliverable_or_eval_output_satisfies_acceptance", + "blocker_or_user_gate_is_projected", + "superseding_vision_or_no_followup_closes_the_frontier", + ], + "continue_when": [ + "evidence_is_missing_weak_or_stale", + "todo_lifecycle_or_protocol_status_is_the_only_proof", + "acceptance_gap_is_still_projected", + ], + "otherwise": "continue", + } + + +def build_vision_continuation_audit( + *, + goal_id: str | None = None, + agent_id: str | None, + acceptance_gaps: Sequence[PayloadView] | None, +) -> Payload | None: + """Return the closeout audit contract for an open per-agent vision gap.""" + + compact_gaps = [gap for gap in (acceptance_gaps or ()) if isinstance(gap, dict)] + if not compact_gaps: + return None + acceptance_requirements = [ + t for g in compact_gaps + if (t := _compact_projection_text(g.get("acceptance_summary"), limit=180)) + ] + trigger_kinds = [ + k for g in compact_gaps + if (k := _compact_projection_text(g.get("kind"), limit=80)) + ] + audit: Payload = { + "schema_version": VISION_CONTINUATION_AUDIT_SCHEMA_VERSION, + "required": True, + "agent_id": agent_id, + "decision": "acceptance_gap_open", + "selected_todo_is_goal_completion": False, + "closeout_allowed_without_evidence": False, + "trigger_count": len(compact_gaps), + "trigger_kinds": list(dict.fromkeys(trigger_kinds))[:5], + "acceptance_gaps": compact_gaps[:5], + "vision_gap_judge": build_vision_gap_judge( + goal_id=goal_id, agent_id=agent_id, acceptance_gaps=compact_gaps, + ), + "authoritative_evidence_kinds": [ + "changed_files", "public_safe_evidence_records", "public_web_research_findings", + "evaluation_outputs", "successor_state", "blocker_state", "superseding_agent_vision", + ], + "not_satisfied_by": [ + "todo_completion_alone", "autonomous_replan_ack_alone", "vision_checkpoint_alone", + "registry_registration_alone", "no_followup_without_acceptance_evidence", + ], + "required_before_closeout": [ + "derive_requirements_from_active_vision_and_current_todo", + "name_authoritative_evidence_for_each_requirement", + "inspect_registry_declared_materials_before_external_research", + "run_bounded_public_research_when_local_evidence_is_missing", + "create_successor_or_write_vision_replan_trigger_when_unproven", + ], + "recommended_action": ( + "audit active per-agent vision acceptance before todo closeout; " + "if evidence is weak or missing, inspect registry-declared material " + "references before bounded public research, then keep the vision " + "active with a successor todo or --vision-replan-trigger" + ), + } + if acceptance_requirements: + audit["acceptance_requirements"] = acceptance_requirements[:5] + diagnostics = [ + {key: gap[key] for key in ("reason_code", "component_checks", "resolution_hint")} + for gap in compact_gaps + if gap.get("reason_code") and gap.get("component_checks") and gap.get("resolution_hint") + ] + if diagnostics: + audit["outcome_checkpoint_diagnostics"] = diagnostics[:5] + return audit + + +def compact_replan_obligation(replan_obligation: PayloadView) -> Payload: + compact: Payload = { + "schema_version": replan_obligation.get("schema_version"), + "obligation_id": replan_obligation.get("obligation_id"), + "stall_threshold": replan_obligation.get("stall_threshold"), + "trigger_count": replan_obligation.get("trigger_count"), + "triggers": replan_obligation.get("triggers") or [], + "stop_condition": replan_obligation.get("stop_condition"), + } + if replan_obligation.get("frontier_identity"): + compact["frontier_identity"] = replan_obligation.get("frontier_identity") + if isinstance(replan_obligation.get("replan_novelty_policy"), dict): + # Keep hot quota/status packets on the two authoritative seams. The + # detailed selection hint remains available on the full obligation. + compact["replan_novelty_policy"] = { + "evidence_source": "compact_run_history", + "delivery": "host_projected", + "writeback": "typed_semantic_delta", + } + feedback = replan_obligation.get("replan_ack_feedback") + if isinstance(feedback, dict): + compact["replan_ack_feedback"] = feedback + compact["recommended_action"] = replan_obligation.get("recommended_action") + return compact + + +def build_autonomous_replan_recommendation( + replan_obligation: PayloadView, *, reason: str | None = None, +) -> Payload: + return { + "recommended_mode": AUTONOMOUS_REPLAN_REQUIRED_MODE, + "notify": "NOTIFY", + "replan_obligation": compact_replan_obligation(replan_obligation), + "spend_policy": ( + "append exactly one heartbeat spend only after executing the selected " + "replan slice, validating it, and writing back todo split/add/retire state" + ), + "reason": reason + or ( + "status exposes an autonomous replan obligation; advance the goal-level " + "planning-trigger slice before monitor-only or agent-scope wait " + "classification; replan turns always notify because DONT_NOTIFY would " + "mislead agents into a quiet no-op" + ), + } + + +def build_autonomous_replan_decision(replan_obligation: PayloadView) -> Payload: + raw_triggers = replan_obligation.get("triggers") + triggers = raw_triggers if isinstance(raw_triggers, list) else [] + return { + "schema_version": AUTONOMOUS_REPLAN_DECISION_SCHEMA_VERSION, + "required": True, + "decision": AUTONOMOUS_REPLAN_REQUIRED_MODE, + "decision_plane": "goal_frontier_before_lane_quiet_or_agent_scope_wait", + "not_disturbed_by": ["monitor_quiet_skip", "agent_scope_wait", "agent_scope_exhausted"], + "trigger_count": safe_non_negative_int(replan_obligation.get("trigger_count")), + "triggers": [t.get("kind") for t in triggers if isinstance(t, dict) and t.get("kind")], + } + + +def build_goal_frontier_projection( + *, + goal_id: str, + agent_id: str | None, + user_counts: Mapping[str, int], + agent_counts: Mapping[str, int], + current_agent_claimed_advancement_count: int, + unclaimed_advancement_count: int, + other_agent_claimed_advancement_count: int, + monitor_only_lane: bool, + replan_obligation: PayloadView | None, + acceptance_gaps: Sequence[PayloadView] | None = None, + deferred_successors: PayloadView | None = None, + vision_wait_state: PayloadView | None = None, + fallback_gaps: Sequence[PayloadView] | None = None, +) -> Payload: + replan_required = autonomous_replan_is_required(replan_obligation) + blockers: list[str] = [] + if monitor_only_lane: + blockers.append("monitor_only_lane") + if ( + current_agent_claimed_advancement_count == 0 + and unclaimed_advancement_count == 0 + and other_agent_claimed_advancement_count > 0 + ): + blockers.append("other_agent_claimed_advancement") + if replan_required: + blockers.append("autonomous_replan_obligation") + if isinstance(vision_wait_state, dict): + blockers.append( + "current_agent_blocker" + if vision_wait_state.get("reason_code") == "current_agent_blocker" + else "vision_blocked_successor_wait" + ) + + compact_acceptance_gaps = [item for item in (acceptance_gaps or ()) if isinstance(item, dict)] + vision_continuation_audit = build_vision_continuation_audit( + goal_id=goal_id, agent_id=agent_id, acceptance_gaps=compact_acceptance_gaps, + ) + projection: Payload = { + "schema_version": GOAL_FRONTIER_PROJECTION_SCHEMA_VERSION, + "goal_id": goal_id, + "agent_id": agent_id, + "source": "quota_should_run", + "normalized_progress": { + "user_open_count": user_counts.get("open", 0), + "agent_open_count": agent_counts.get("open", 0), + "agent_advancement_open_count": agent_counts.get("advancement", 0), + "agent_monitor_open_count": agent_counts.get("monitor", 0), + "agent_monitor_due_count": agent_counts.get("monitor_due", 0), + "agent_watch_only_monitor_due_count": agent_counts.get("watch_only_monitor_due", 0), + }, + "remaining_advancement_frontier": { + "current_agent_claimed_advancement_count": current_agent_claimed_advancement_count, + "unclaimed_advancement_count": unclaimed_advancement_count, + "other_agent_claimed_advancement_count": other_agent_claimed_advancement_count, + }, + "monitor_only_lanes": { + "present": monitor_only_lane, + "quiet_until_material_transition": monitor_only_lane, + }, + "deferred_successors": deferred_successors + if isinstance(deferred_successors, dict) + else {"ready_count": 0, "blocked_count": 0, "current_agent_ready_count": 0, "ready_todo_ids": []}, + "acceptance_gaps": compact_acceptance_gaps[:5], + "autonomy_blockers": blockers, + "replan_required": replan_required, + } + if vision_continuation_audit: + projection["vision_continuation_audit"] = vision_continuation_audit + # Advisory-only field: unlike acceptance_gaps it is never cleared by the + # blocked-successor wait state, which is exactly when a declared fallback + # would otherwise disappear silently. + if fallback_gaps: + projection["fallback_gaps"] = list(fallback_gaps[:1]) + if isinstance(vision_wait_state, dict): + projection["vision_wait_state"] = vision_wait_state + if replan_required and isinstance(replan_obligation, dict): + projection["autonomous_replan_decision"] = build_autonomous_replan_decision(replan_obligation) + return projection diff --git a/loopx/control_plane/goals/goal_frontier/replan_rules.py b/loopx/control_plane/goals/goal_frontier/replan_rules.py index 9ab75c8f1d..503644b868 100644 --- a/loopx/control_plane/goals/goal_frontier/replan_rules.py +++ b/loopx/control_plane/goals/goal_frontier/replan_rules.py @@ -3,11 +3,39 @@ from __future__ import annotations +from collections.abc import Mapping, Sequence from dataclasses import dataclass from enum import Enum +from typing import cast -GOAL_FRONTIER_REPLAN_RULE_DECISION_SCHEMA_VERSION = ( - "goal_frontier_replan_rule_decision_v0" +from ...todos.succession_warning import TODO_SUCCESSION_WARNING_REASON_CODE +from ...work_items.autonomous_replan_obligation import ( + MONITOR_NO_CHANGE_STREAK_THRESHOLD, + TODO_LIFECYCLE_SETTLEMENT_RESOLUTION_MODE, + build_autonomous_replan_obligation_payload, +) +from ..goal_vision_read_model import VISION_ACCEPTANCE_GAP_TRIGGER +from .acceptance import GOAL_ACCEPTANCE_HOLD_TRIGGERS +from .ack_policy import _acknowledged_replan_obligation_id +from .long_todo_chain import ( + LONG_TODO_CHAIN_TRIGGER, + LongTodoChainAckDecision, + LongTodoChainObservation, +) + +Payload = dict[str, object] +PayloadView = Mapping[str, object] + +GOAL_FRONTIER_REPLAN_RULE_DECISION_SCHEMA_VERSION = "goal_frontier_replan_rule_decision_v0" +AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION = "autonomous_replan_obligation_v0" +FRONTIER_EXHAUSTED_MONITOR_TRIGGER = "frontier_exhausted_monitor_lane" +TODO_SUCCESSION_GAP_TRIGGER = TODO_SUCCESSION_WARNING_REASON_CODE + +_VISION_GAP_TRIGGER_KEYS = ( + "generated_at", "completed_todo_id", "completed_todo_count", "completed_todo_threshold", + "completed_todo_ids", "vision_todo_ids", "frontier_revision", "outcome_id", + "requirement_ids", "legacy_frontier_revision", "reason_code", "component_checks", + "resolution_hint", ) @@ -218,3 +246,280 @@ def select_goal_frontier_replan_rule( reason=reason, ) raise AssertionError("goal-frontier replan rules must have a terminal rule") + + +def _agent_add_todo_action(text: str, *, priority: str = "P0") -> Payload: + return {"action": "add", "role": "agent", "priority": priority, "text": text} + + +def _frontier_obligation_payload( + *, + triggers: list[Payload], + guidance_actions: list[str], + todo_actions: list[Payload], + stop_subject: str, + recommended_action: str, + agent_id: str | None = None, + include_agent_id: bool = True, + stall_threshold: int = 1, + trigger_count: int = 1, + rearmed_after_obligation_id: str | None = None, + extra_fields: Payload | None = None, +) -> Payload: + return cast( + Payload, + build_autonomous_replan_obligation_payload( + schema_version=AUTONOMOUS_REPLAN_OBLIGATION_SCHEMA_VERSION, + agent_id=agent_id, + include_agent_id=include_agent_id, + stall_threshold=stall_threshold, + trigger_count=trigger_count, + triggers=triggers, + guidance_actions=guidance_actions, + todo_actions=todo_actions, + stop_condition=( + f"stop if {stop_subject} requires private material, credentials, " + "destructive git, production actions, or owner-only decisions" + ), + recommended_action=recommended_action, + rearmed_after_obligation_id=rearmed_after_obligation_id, + extra_fields=extra_fields, + ), + ) + + +def _build_todo_succession_obligation( + succession_gap_items: Sequence[PayloadView], + *, + agent_id: str | None, +) -> Payload: + settlement_items = list(succession_gap_items[:3]) + settlement_todo_ids = [ + tid for item in settlement_items if (tid := str(item.get("todo_id") or "").strip()) + ] + return _frontier_obligation_payload( + agent_id=agent_id, + trigger_count=len(succession_gap_items), + triggers=[ + { + "kind": TODO_SUCCESSION_GAP_TRIGGER, + "section": "agent_todo_summary.todo_succession_warning", + "todo_id": item.get("todo_id"), + "text": item.get("text") + or item.get("title") + or "completed advancement needs a successor or no-followup rationale", + "agent_id": agent_id, + "claimed_by": item.get("claimed_by"), + "completion_turn_key": item.get("completion_turn_key"), + } + for item in settlement_items + ], + guidance_actions=["record_no_followup", "link_successor", "create_successor"], + todo_actions=[ + { + "action": "settle", + "role": "agent", + "priority": "P0", + "todo_ids": settlement_todo_ids, + "text": ( + "settle the completed scope using its original completion identity, or " + "record a genuine dependency on the mutable successor; do not update terminal links" + ), + }, + _agent_add_todo_action( + "create a typed runnable successor only when concrete " + "technical or validation work remains" + ), + ], + stop_subject="the successor decision", + recommended_action=( + f"settle the exact completed Todo(s) {', '.join(settlement_todo_ids)} " + "through loopx todo complete --no-follow-up with the original completion " + "identity when no follow-up remains in that scope. Independent open/deferred " + "work remains active. For genuine dependent work, record its real readiness " + "dependency on the mutable successor, preserving gates; never add links to a " + "terminal Todo; do not invent a user gate or lifecycle-only filler Todo" + ), + extra_fields={ + "resolution_mode": TODO_LIFECYCLE_SETTLEMENT_RESOLUTION_MODE, + "satisfying_semantic_outcomes": ["new_runnable_successor"], + }, + ) + + +def _build_vision_acceptance_obligation( + compact_acceptance_gaps: Sequence[PayloadView], + *, + agent_id: str | None, + latest_replan_ack: PayloadView | None, +) -> Payload: + acceptance_held = any( + gap.get("kind") in GOAL_ACCEPTANCE_HOLD_TRIGGERS for gap in compact_acceptance_gaps + ) + trigger_gaps = list(compact_acceptance_gaps[:3]) + # Three independent holds may fill the detail slots. Preserve the canonical + # outcome owner's complete agent-set checkpoint as one more bounded trigger, + # so the same ACK can cover both sources without dropping a held Todo or + # acknowledging an unseen outcome revision. + outcome_gap = next( + ( + gap + for gap in compact_acceptance_gaps + if gap.get("kind") == "goal_outcome_uncovered" and gap.get("agent_id") == agent_id + ), + None, + ) + if outcome_gap is not None and outcome_gap not in trigger_gaps: + trigger_gaps.append(outcome_gap) + recommended = ( + " ".join(str(g["resolution_hint"]) for g in compact_acceptance_gaps if g.get("resolution_hint")) + if all(g.get("resolution_hint") for g in compact_acceptance_gaps) + else ( + "run a bounded vision-gap replan before another quiet poll: create " + "successor work, update the agent vision, record evidence gap, or " + "record no-follow-up" + ) + ) + return _frontier_obligation_payload( + agent_id=agent_id, + trigger_count=len(compact_acceptance_gaps), + triggers=[ + { + "kind": gap.get("kind") or VISION_ACCEPTANCE_GAP_TRIGGER, + "section": "goal_frontier_projection.acceptance_gaps", + "text": gap.get("replan_trigger_summary") + or "bounded agent vision reports an open acceptance gap", + "agent_id": agent_id, + "acceptance_summary": gap.get("acceptance_summary"), + "advancement_policy": gap.get("advancement_policy"), + **{k: gap.get(k) for k in _VISION_GAP_TRIGGER_KEYS if gap.get(k) is not None}, + } + for gap in trigger_gaps + ], + guidance_actions=( + ["inspect_acceptance_binding", "select_eligible_successor", "record_evidence_gap"] + if acceptance_held + else ["create_successor", "update_agent_vision", "record_evidence_gap", "record_no_followup"] + ), + # Another unbound advancement Todo cannot repair this admission hold. + # Keep authoring suggestions aligned with the typed exits. + todo_actions=( + [] + if acceptance_held + else [ + _agent_add_todo_action( + "run a bounded vision-gap replan: create the next runnable " + "advancement todo or record an explicit no-follow-up rationale" + ) + ] + ), + stop_subject="the gap", + recommended_action=recommended, + rearmed_after_obligation_id=_acknowledged_replan_obligation_id(latest_replan_ack), + ) + + +def build_rule_replan_obligation( + rule: GoalFrontierReplanRule, + *, + agent_id: str | None, + agent_counts: Mapping[str, int], + future_schedule_present: bool, + latest_replan_ack: PayloadView | None, + compact_acceptance_gaps: Sequence[PayloadView], + succession_gap_items: Sequence[PayloadView], + capability_obligation: Payload | None, + long_chain_observation: LongTodoChainObservation | None, + long_chain_ack_decision: LongTodoChainAckDecision | None, + monitor_no_change_trigger: Payload | None, +) -> Payload | None: + """Build the autonomous replan obligation payload for a deriving frontier rule.""" + + if rule is GoalFrontierReplanRule.CAPABILITY_EVIDENCE_GAP: + return capability_obligation + if rule is GoalFrontierReplanRule.TODO_SUCCESSION_GAP: + return _build_todo_succession_obligation(succession_gap_items, agent_id=agent_id) + if rule is GoalFrontierReplanRule.VISION_ACCEPTANCE_GAP: + return _build_vision_acceptance_obligation( + compact_acceptance_gaps, agent_id=agent_id, latest_replan_ack=latest_replan_ack, + ) + if rule is GoalFrontierReplanRule.LONG_TODO_CHAIN: + assert long_chain_observation is not None and long_chain_ack_decision is not None + trigger = long_chain_observation.trigger + return _frontier_obligation_payload( + agent_id=agent_id, + stall_threshold=cast(int, trigger.get("threshold")), + trigger_count=cast(int, trigger.get("trigger_count")), + triggers=[{ + "kind": LONG_TODO_CHAIN_TRIGGER, + "section": "agent_todo_summary", + "text": ( + "current agent lane has a long claimed todo chain; " + "run a vision checkpoint/replan before continuing linearly" + ), + **trigger, + }], + guidance_actions=[ + "use_replan_context", "run_bounded_public_research_if_local_evidence_is_missing", + "group_or_prune_todo_chain", "update_agent_vision", "create_successor", + ], + todo_actions=[], + stop_subject="pruning or external research", + recommended_action=( + "run a bounded long-chain vision replan before continuing a 15+ " + "todo lane: read evidence, use public research if local evidence " + "is weak, group/prune work, and record an evidence-linked vision " + "path through replan_action_packet.writeback_contract using the " + "current Turn settlement binding; retain existing runnable work " + "when appropriate instead of adding a Todo whose only action is replan" + ), + rearmed_after_obligation_id=long_chain_ack_decision.rearmed_after_obligation_id, + ) + if rule is GoalFrontierReplanRule.MONITOR_NO_CHANGE_STREAK: + assert monitor_no_change_trigger is not None + return _frontier_obligation_payload( + agent_id=agent_id, + stall_threshold=MONITOR_NO_CHANGE_STREAK_THRESHOLD, + triggers=[monitor_no_change_trigger], + guidance_actions=["set_watch_expiry", "write_blocker", "supersede_monitor", "create_successor"], + todo_actions=[_agent_add_todo_action( + "resolve the stalled monitor lane with an expiry, blocker, " + "supersede transition, or runnable successor", + priority="P1", + )], + stop_subject="the replan", + recommended_action=( + "resolve the current agent's stalled monitor lane before another " + "quiet poll: set an expiry, write a blocker, supersede the monitor, " + "or create runnable successor work" + ), + ) + assert rule is GoalFrontierReplanRule.MONITOR_FRONTIER_EXHAUSTED + return _frontier_obligation_payload( + include_agent_id=False, + triggers=[{ + "kind": FRONTIER_EXHAUSTED_MONITOR_TRIGGER, + "section": "goal_frontier_projection", + "text": ( + "current goal frontier has no current, unclaimed, or other-agent " + "advancement todo while only monitor work remains" + ), + "agent_id": agent_id, + "agent_open_count": agent_counts.get("open", 0), + "agent_monitor_open_count": agent_counts.get("monitor", 0), + "future_monitor_schedule_present": future_schedule_present, + }], + guidance_actions=["create_successor", "supersede_monitor", "set_watch_expiry", "record_no_followup"], + todo_actions=[_agent_add_todo_action( + "run a compact goal-frontier replan: create a successor runnable " + "todo, supersede stale monitor work, set watch-lane expiry, or " + "record an explicit no-follow-up rationale", + priority="P1", + )], + stop_subject="the replan", + recommended_action=( + "run a bounded goal-frontier replan before another monitor-only quiet " + "poll: create successor work, supersede the monitor lane, set an expiry, " + "or record an evidence-backed no-follow-up outcome" + ), + )