diff --git a/loopx/control_plane/work_items/external_progress_review.py b/loopx/control_plane/work_items/external_progress_review.py index 3fb6d8b19e..9f22d67b83 100644 --- a/loopx/control_plane/work_items/external_progress_review.py +++ b/loopx/control_plane/work_items/external_progress_review.py @@ -387,7 +387,7 @@ def external_progress_review_trigger( continue if baseline_run is None: baseline_run = run - window_fingerprints.add(observation["fingerprint"]) + window_fingerprints.add(str(observation["fingerprint"])) window.append(observation) if baseline_run is None or not window: return None diff --git a/loopx/control_plane/work_items/progress_observation.py b/loopx/control_plane/work_items/progress_observation.py index 3ea2132eb9..7ed17cb119 100644 --- a/loopx/control_plane/work_items/progress_observation.py +++ b/loopx/control_plane/work_items/progress_observation.py @@ -1,15 +1,15 @@ -from __future__ import annotations +"""Host validation, digest, and semantic writeback adapters for progress observations.""" -from typing import Any, cast +from __future__ import annotations import hashlib import json import shlex -from collections.abc import Iterable, Mapping +from collections.abc import Iterable, Mapping, Sequence +from typing import cast from ...turn_identity import normalize_turn_instance_id from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result -from .replan_semantics_codec import project_replan_semantics from ..goals.goal_vision_state import normalize_goal_vision_state from ..todos.contract import ( normalize_todo_task_domain, @@ -20,89 +20,89 @@ ProgressResultClass, normalize_progress_identifier, ) +from .replan_semantics_codec import project_replan_semantics + +Payload = dict[str, object] +PayloadView = Mapping[str, object] REPLAN_ACTION_PACKET_SCHEMA_VERSION = "replan_action_packet_v0" PROGRESS_REPEAT_TRIGGER_KIND = "typed_progress_repeat" PROGRESS_REPEAT_THRESHOLD = 2 MAX_PROGRESS_EVIDENCE_IDS = 12 -SEMANTIC_DIMENSIONS = ( - "surface_id", - "hypothesis_id", - "probe_kind", -) +SEMANTIC_DIMENSIONS = ("surface_id", "hypothesis_id", "probe_kind") TERMINAL_RESULT_CLASSES = { ProgressResultClass.BLOCKED.value, ProgressResultClass.EXPLORATION_EXHAUSTED.value, ProgressResultClass.NO_FOLLOWUP.value, } # Legacy ACK readback vocabulary; discharge authority lives in replan_semantics.ts. -FRESH_VISION_PATH_DISPOSITIONS = frozenset( - {"continue", "no_change", "replan"} +FRESH_VISION_PATH_DISPOSITIONS = frozenset({"continue", "no_change", "replan"}) +_BOUNDED_FRONTIER_KEYS: tuple[str, ...] = ( + "schema_version", + "gap_id", + "experiment_node_ref", + "input_node_refs", + "required_outcome", + "input_observations", + "frontier_revision", +) +_IDENTITY_FIELD_KEYS: tuple[str, ...] = ( + "work_item_id", + *SEMANTIC_DIMENSIONS, + "result_class", + "blocker_id", + "coverage_scope_id", + "evidence_ids", + "coverage_complete", ) -def _stable_id(value: Any, *, field: str, required: bool = False) -> str | None: +def _stable_id(value: object, *, field: str, required: bool = False) -> str | None: normalized = str(value or "").strip() if not normalized: if required: raise ValueError(f"{field} is required") return None if normalize_progress_identifier(normalized) is None: - raise ValueError( - f"{field} must be an opaque 1-128 character public-safe identifier" - ) + raise ValueError(f"{field} must be an opaque 1-128 character public-safe identifier") return normalized -def _stable_ids(values: Iterable[Any] | None, *, field: str) -> list[str]: - normalized: list[str] = [] - for value in values or []: +def _stable_ids(values: Iterable[object] | None, *, field: str) -> list[str]: + seen: set[str] = set() + for value in values or (): item = _stable_id(value, field=field, required=True) - if item and item not in normalized: - normalized.append(item) - if len(normalized) > MAX_PROGRESS_EVIDENCE_IDS: - raise ValueError( - f"{field} accepts at most {MAX_PROGRESS_EVIDENCE_IDS} identifiers" - ) - return sorted(normalized) + if item: + seen.add(item) + if len(seen) > MAX_PROGRESS_EVIDENCE_IDS: + raise ValueError(f"{field} accepts at most {MAX_PROGRESS_EVIDENCE_IDS} identifiers") + return sorted(seen) -def _digest(value: Mapping[str, Any]) -> str: - return hashlib.sha256( - json.dumps( - dict(value), - sort_keys=True, - ensure_ascii=True, - separators=(",", ":"), - ).encode("utf-8") - ).hexdigest()[:16] +def _digest(value: PayloadView) -> str: + encoded = json.dumps(dict(value), sort_keys=True, ensure_ascii=True, separators=(",", ":")) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:16] def normalize_progress_observation( - value: Mapping[str, Any], + value: PayloadView, *, work_item_id: str | None = None, -) -> dict[str, Any]: +) -> Payload: """Validate one explicit progress observation without interpreting prose.""" - if not isinstance(value, Mapping): raise TypeError("progress observation must be an object") - schema_version = str( - value.get("schema_version") or PROGRESS_OBSERVATION_SCHEMA_VERSION - ).strip() + schema_version = str(value.get("schema_version") or PROGRESS_OBSERVATION_SCHEMA_VERSION).strip() if schema_version != PROGRESS_OBSERVATION_SCHEMA_VERSION: - raise ValueError( - "progress observation must use " - f"{PROGRESS_OBSERVATION_SCHEMA_VERSION}" - ) + raise ValueError(f"progress observation must use {PROGRESS_OBSERVATION_SCHEMA_VERSION}") try: result_class = ProgressResultClass(str(value.get("result_class") or "")) except ValueError as exc: choices = ", ".join(item.value for item in ProgressResultClass) raise ValueError(f"result_class must be one of: {choices}") from exc - observation: dict[str, Any] = { + observation: Payload = { "schema_version": PROGRESS_OBSERVATION_SCHEMA_VERSION, "result_class": result_class.value, } @@ -110,42 +110,24 @@ def normalize_progress_observation( normalized = _stable_id(value.get(field), field=field) if normalized: observation[field] = normalized - normalized_work_item = _stable_id( - value.get("work_item_id") or work_item_id, - field="work_item_id", - ) - if normalized_work_item: - observation["work_item_id"] = normalized_work_item - blocker_id = _stable_id(value.get("blocker_id"), field="blocker_id") - if blocker_id: - observation["blocker_id"] = blocker_id - coverage_scope_id = _stable_id( - value.get("coverage_scope_id"), - field="coverage_scope_id", - ) - if coverage_scope_id: - observation["coverage_scope_id"] = coverage_scope_id - evidence_ids = _stable_ids(value.get("evidence_ids"), field="evidence_ids") + for field, candidate in ( + ("work_item_id", value.get("work_item_id") or work_item_id), + ("blocker_id", value.get("blocker_id")), + ("coverage_scope_id", value.get("coverage_scope_id")), + ): + normalized = _stable_id(candidate, field=field) + if normalized: + observation[field] = normalized + evidence_ids = _stable_ids(cast(Iterable[object] | None, value.get("evidence_ids")), field="evidence_ids") if evidence_ids: observation["evidence_ids"] = evidence_ids - if value.get("coverage_complete") is not None: - if not isinstance(value.get("coverage_complete"), bool): + coverage_complete = value.get("coverage_complete") + if coverage_complete is not None: + if not isinstance(coverage_complete, bool): raise ValueError("coverage_complete must be a boolean") - observation["coverage_complete"] = value.get("coverage_complete") - - identity_fields = { - key: observation[key] - for key in ( - "work_item_id", - *SEMANTIC_DIMENSIONS, - "result_class", - "blocker_id", - "coverage_scope_id", - "evidence_ids", - "coverage_complete", - ) - if key in observation - } + observation["coverage_complete"] = coverage_complete + + identity_fields = {key: observation[key] for key in _IDENTITY_FIELD_KEYS if key in observation} if len(identity_fields) == 1: # result_class alone is not attributable. raise ValueError( "progress observation requires at least one stable work, coverage, " @@ -155,7 +137,7 @@ def normalize_progress_observation( return observation -def progress_observation_from_run(run: Mapping[str, Any]) -> dict[str, Any] | None: +def progress_observation_from_run(run: PayloadView) -> Payload | None: value = run.get("progress_observation") if not isinstance(value, Mapping): return None @@ -166,14 +148,12 @@ def progress_observation_from_run(run: Mapping[str, Any]) -> dict[str, Any] | No return None -def _progress_turn_instance_id(run: Mapping[str, Any]) -> str | None: +def _progress_turn_instance_id(run: PayloadView) -> str | None: """Return a trustworthy logical-turn id for retry de-duplication.""" - def normalize(value: Any) -> str | None: + def normalize(value: object) -> str | None: try: - return normalize_turn_instance_id( - str(value) if value is not None else None - ) + return normalize_turn_instance_id(str(value) if value is not None else None) except ValueError: return None @@ -187,26 +167,25 @@ def normalize(value: Any) -> str | None: def typed_progress_repeat_trigger( - newest_first_runs: Iterable[Mapping[str, Any]], + newest_first_runs: Iterable[PayloadView], *, agent_id: str | None, threshold: int = PROGRESS_REPEAT_THRESHOLD, -) -> dict[str, Any] | None: +) -> Payload | None: """Compatibility entrypoint for the shared TypeScript history window.""" from .replan_history_codec import project_replan_history - return project_replan_history( - newest_first_runs, operation="progress", agent_id=agent_id, - stall_threshold=threshold, + return cast( + Payload | None, + project_replan_history( + newest_first_runs, operation="progress", agent_id=agent_id, stall_threshold=threshold + ), ) -def _normalized_window( - window: Iterable[Mapping[str, Any]] | None, -) -> list[dict[str, Any]]: +def _normalized_window(window: Iterable[PayloadView] | None) -> list[Payload]: """Normalize the typed observations an obligation window already holds.""" - - normalized: list[dict[str, Any]] = [] + normalized: list[Payload] = [] for item in window or (): if not isinstance(item, Mapping): continue @@ -217,14 +196,10 @@ def _normalized_window( return normalized -def replan_writeback_requirements( - obligation: Mapping[str, Any], -) -> dict[str, Any]: +def replan_writeback_requirements(obligation: PayloadView) -> Payload: """Adapt the shared typed discharge policy for CLI and host projection.""" try: - result = project_replan_semantics({ - "operation": "requirements", "obligation": dict(obligation), - }) + result = project_replan_semantics({"operation": "requirements", "obligation": dict(obligation)}) except EffectRuntimeRejected as exc: raise ValueError(str(exc)) from None if not isinstance(result, Mapping): @@ -232,16 +207,14 @@ def replan_writeback_requirements( return dict(result) -def required_semantic_outcomes(obligation: Mapping[str, Any]) -> list[str]: - return list(replan_writeback_requirements(obligation)["required_any_of"]) +def required_semantic_outcomes(obligation: PayloadView) -> list[str]: + return list(cast(Iterable[str], replan_writeback_requirements(obligation)["required_any_of"])) -def replan_successor_transition_allowed(obligation: Mapping[str, Any]) -> bool: +def replan_successor_transition_allowed(obligation: PayloadView) -> bool: """Ask the typed owner whether a Todo transition can settle this review.""" try: - result = project_replan_semantics({ - "operation": "transition_eligibility", "obligation": dict(obligation), - }) + result = project_replan_semantics({"operation": "transition_eligibility", "obligation": dict(obligation)}) except EffectRuntimeRejected as exc: raise ValueError(str(exc)) from None if not isinstance(result, Mapping) or not isinstance(result.get("allowed"), bool): @@ -250,22 +223,22 @@ def replan_successor_transition_allowed(obligation: Mapping[str, Any]) -> bool: def guarded_replan_transition_delta( - *, guard_scoped: bool, selected_obligation_id: str | None, - transition_candidates: list[dict[str, Any]], - goal_id: str | None = None, agent_id: str | None = None, + *, + guard_scoped: bool, + selected_obligation_id: str | None, + transition_candidates: Sequence[PayloadView], + goal_id: str | None = None, + agent_id: str | None = None, guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, -) -> dict[str, Any] | None: +) -> Payload | None: """Adapt revalidated canonical receipts to the TS-owned exact Turn gate.""" try: result = project_replan_semantics({ "operation": "turn_transition", "guard_scoped": guard_scoped, - "selected_obligation_id": selected_obligation_id, - "transition_candidates": transition_candidates, - "goal_id": goal_id, - "agent_id": agent_id, - "guard_recorded_at": guard_recorded_at, - "guard_turn_instance_id": guard_turn_instance_id, + "selected_obligation_id": selected_obligation_id, "transition_candidates": transition_candidates, + "goal_id": goal_id, "agent_id": agent_id, + "guard_recorded_at": guard_recorded_at, "guard_turn_instance_id": guard_turn_instance_id, }) except EffectRuntimeRejected as exc: raise ValueError(str(exc)) from None @@ -277,127 +250,123 @@ def guarded_replan_transition_delta( return dict(delta) if delta is not None else None -def replan_obligation_trigger_kinds( - obligation: Mapping[str, Any], -) -> list[str]: +def replan_obligation_trigger_kinds(obligation: PayloadView) -> list[str]: """Return the typed trigger sources owned by one obligation generation.""" - - return list( - dict.fromkeys( - str(trigger.get("kind") or "").strip() - for trigger in (obligation.get("triggers") or []) - if isinstance(trigger, Mapping) - and str(trigger.get("kind") or "").strip() - ) - ) + triggers = obligation.get("triggers") + if not isinstance(triggers, list): + return [] + return list(dict.fromkeys( + kind for trigger in triggers + if isinstance(trigger, Mapping) and (kind := str(trigger.get("kind") or "").strip()) + )) -def replan_obligation_trigger_checkpoints( - obligation: Mapping[str, Any], -) -> list[dict[str, str]]: +def replan_obligation_trigger_checkpoints(obligation: PayloadView) -> list[dict[str, str]]: """Bind an ACK to typed trigger revisions supplied by the obligation.""" - triggers = obligation.get("triggers") if not triggers: return [] - checkpoints = effect_runtime_result("todo.frontier_revision.project", { - "schema_version": "todo_frontier_revision_request_v0", - "operation": "trigger_checkpoints", "triggers": triggers, - })["trigger_checkpoints"] + checkpoints = effect_runtime_result( + "todo.frontier_revision.project", + {"schema_version": "todo_frontier_revision_request_v0", "operation": "trigger_checkpoints", "triggers": triggers}, + )["trigger_checkpoints"] if not isinstance(checkpoints, list): raise TypeError("typed frontier checkpoint response must be a list") - return checkpoints + return cast(list[dict[str, str]], checkpoints) + + +def _validated_replan_context(obligation: PayloadView) -> Payload: + from .replan_context_codec import validate_replan_context + + context = validate_replan_context(obligation.get("replan_context")) + if context["obligation_id"] != obligation.get("obligation_id"): + raise ValueError("replan context obligation identity mismatch") + return cast(Payload, context) + + +def _obligation_baseline_and_window(obligation: PayloadView) -> tuple[PayloadView | None, list[object] | None]: + raw_baseline = obligation.get("progress_baseline") + baseline: PayloadView | None = cast(PayloadView, raw_baseline) if isinstance(raw_baseline, Mapping) else None + raw_window = obligation.get("progress_window") + window: list[object] | None = raw_window if isinstance(raw_window, list) else None + if baseline is None or window is None: + triggers = obligation.get("triggers") + if isinstance(triggers, list): + for trigger in triggers: + if not isinstance(trigger, Mapping): + continue + if baseline is None and isinstance(trigger.get("progress_baseline"), Mapping): + baseline = cast(PayloadView, trigger.get("progress_baseline")) + if window is None and isinstance(trigger.get("progress_window"), list): + window = cast(list[object], trigger.get("progress_window")) + if baseline is not None and window is not None: + break + return baseline, window def semantic_delta_from_writeback( *, - obligation: Mapping[str, Any], - progress_observation: Mapping[str, Any] | None, - agent_vision: Mapping[str, Any] | None = None, - history_runs: Iterable[Mapping[str, Any]] | None = None, + obligation: PayloadView, + progress_observation: PayloadView | None, + agent_vision: PayloadView | None = None, + history_runs: Iterable[PayloadView] | None = None, recovering_writeback_path: str | None = None, -) -> dict[str, Any]: +) -> Payload: """Qualify concrete typed writeback evidence against one obligation. Legacy ACK and repair-delta claims never count on this write path. Only a typed observation grounded in current state, or a fresh evidence-linked vision path, can contribute outcomes. """ - - # The same source serves novelty and cited-outcome replay; consume an - # iterable once without reopening or modifying its authority store. - runs = list(history_runs) if history_runs is not None else None - baseline = obligation.get("progress_baseline") - if not isinstance(baseline, Mapping): - baseline = next( - ( - trigger.get("progress_baseline") - for trigger in (obligation.get("triggers") or []) - if isinstance(trigger, Mapping) - and isinstance(trigger.get("progress_baseline"), Mapping) - ), - None, - ) - window = obligation.get("progress_window") - if not isinstance(window, list): - window = next( - ( - trigger.get("progress_window") - for trigger in (obligation.get("triggers") or []) - if isinstance(trigger, Mapping) - and isinstance(trigger.get("progress_window"), list) - ), - None, - ) - context = obligation.get("replan_context") - if context is not None: - from .replan_context_codec import validate_replan_context - context = validate_replan_context(context) - if context["obligation_id"] != obligation.get("obligation_id"): - raise ValueError("replan context obligation identity mismatch") + # Consume an iterable once without reopening or modifying its authority store. + runs: Sequence[PayloadView] | None = ( + None if history_runs is None + else (history_runs if isinstance(history_runs, (list, tuple)) else list(history_runs)) + ) + baseline, window = _obligation_baseline_and_window(obligation) + context = _validated_replan_context(obligation) if obligation.get("replan_context") is not None else None coverage = context["coverage_ledger"] if context is not None else None - claimed = list(window) if isinstance(window, list) else [] - # During an exact supplement, the current observation is already in the - # displayed ledger. The full index below can distinguish its source row - # from every other occurrence of the same observation. + claimed: list[object] = list(window) if window is not None else [] + # During an exact supplement, the current observation is already in the displayed + # ledger; the full index below distinguishes its source row from prior repeats. if isinstance(coverage, list) and recovering_writeback_path is None: claimed.extend(coverage) if runs is not None and context is not None: from .replan_context_codec import replan_evidence_rows - # The readable context has a display budget; admission does not forget - # an older claim merely because it was omitted from that display. - novelty_runs = runs + novelty_runs: Sequence[PayloadView] = runs if recovering_writeback_path is not None: - # The settlement owner bound this supplement to an existing - # unqualified observation. It is the input being qualified. novelty_runs = [run for run in runs if run.get("json_path") != recovering_writeback_path] if len(novelty_runs) != len(runs) - 1: raise ValueError("the original blocked writeback is not unique in replan history") claimed.extend( row["progress_observation"] - for row in replan_evidence_rows(novelty_runs, goal_id=context["goal_id"], agent_id=context["agent_id"]) + for row in replan_evidence_rows( + novelty_runs, goal_id=cast(str, context["goal_id"]), agent_id=cast(str | None, context["agent_id"]) + ) if row["progress_observation"] is not None ) elif recovering_writeback_path is not None: raise ValueError("blocked writeback recovery requires the original replan context and full history") elif context is not None and context.get("coverage_truncated"): raise ValueError("replan writeback requires the complete evidence history when coverage is truncated") - progress_source = None - if isinstance(progress_observation, Mapping): - progress_source = { + + progress_source = ( + { "current": normalize_progress_observation(progress_observation), - "baseline": normalize_progress_observation(baseline) if isinstance(baseline, Mapping) else None, - "window": _normalized_window(claimed), + "baseline": normalize_progress_observation(baseline) if baseline is not None else None, + "window": _normalized_window(cast(Iterable[PayloadView], claimed)), } + if isinstance(progress_observation, Mapping) + else None + ) vision = dict(agent_vision) if isinstance(agent_vision, Mapping) else {} if vision: vision["state"] = normalize_goal_vision_state(vision.get("state")) source_review = None stride = vision.get("stride_decision") review = stride.get("previous_review") if isinstance(stride, Mapping) else None - if (runs is not None and context is not None - and context.get("decision_followthrough") and isinstance(review, Mapping)): + if runs is not None and context is not None and context.get("decision_followthrough") and isinstance(review, Mapping): from .replan_context_codec import replay_stride_review_evidence source_review = replay_stride_review_evidence(context=context, review=review, runs=runs) @@ -418,119 +387,96 @@ def semantic_delta_from_writeback( def build_replan_context( - obligation: Mapping[str, Any], *, goal_id: str, agent_id: str | None, - newest_first_runs: Iterable[Mapping[str, Any]], - source_status: Mapping[str, Any] | None = None, - explore_context: Mapping[str, Any] | None = None, - goal_acceptance_contract: Mapping[str, Any] | None = None, - todo_items: Iterable[Mapping[str, Any]] | None = None, -) -> dict[str, Any]: + obligation: PayloadView, *, goal_id: str, agent_id: str | None, + newest_first_runs: Iterable[PayloadView], source_status: PayloadView | None = None, + explore_context: PayloadView | None = None, goal_acceptance_contract: PayloadView | None = None, + todo_items: Iterable[PayloadView] | None = None, +) -> Payload: from .replan_context_codec import project_replan_context - return project_replan_context( - goal_id=goal_id, agent_id=agent_id or obligation.get("agent_id"), - runs=newest_first_runs, obligation=obligation, source_status=source_status, - goal_acceptance_contract=goal_acceptance_contract, - history_newest_first=True, explore_context=explore_context, - todo_items=todo_items, + raw_agent_id = agent_id or obligation.get("agent_id") + resolved_agent = raw_agent_id if raw_agent_id is None or isinstance(raw_agent_id, str) else str(raw_agent_id) + return cast(Payload, project_replan_context( + goal_id=goal_id, agent_id=resolved_agent, runs=newest_first_runs, + obligation=obligation, source_status=source_status, + goal_acceptance_contract=goal_acceptance_contract, history_newest_first=True, + explore_context=explore_context, todo_items=todo_items, + )) + + +def _successor_writeback_contract( + *, obligation_id: object, goal_id: str | None, agent_id: object, + selected_gap: PayloadView, priority: str, +) -> Payload | None: + raw_binding = selected_gap.get("successor_binding") + raw_successor_binding: PayloadView = raw_binding if isinstance(raw_binding, Mapping) else {} + successor_binding = replan_successor_semantic_binding( + action_kind=raw_successor_binding.get("action_kind"), + target_key=raw_successor_binding.get("target_key"), + explore_result_node_refs=raw_successor_binding.get("explore_result_node_refs"), + ) + successor_summary = str(selected_gap.get("successor_summary") or "").strip()[:240] + if not (successor_summary and successor_binding): + return None + safe_goal_id = _stable_id(goal_id, field="goal_id") or "" + safe_agent_id = _stable_id(agent_id, field="agent_id") or "" + successor_text = shlex.quote(f"[{priority}] {successor_summary}") + successor_ref_args = "".join( + f" --explore-result-node-ref {shlex.quote(ref)}" + for ref in successor_binding.get("explore_result_node_refs") or () ) + target_key_arg = ( + " --target-key " + shlex.quote(str(successor_binding["target_key"])) + if successor_binding.get("target_key") + else "" + ) + task_domain = normalize_todo_task_domain(raw_successor_binding.get("task_domain")) + task_domain_arg = " --task-domain " + shlex.quote(task_domain) if task_domain else "" + return { + "successor_command": ( + "loopx todo add " + f"--goal-id {safe_goal_id} --role agent --task-class advancement_task " + f"--action-kind {shlex.quote(str(successor_binding['action_kind']))}" + f"{task_domain_arg}{target_key_arg} --text {successor_text} " + f"--claimed-by {safe_agent_id} --replan-obligation-id {obligation_id}{successor_ref_args}" + ), + "successor_host_action": "end_current_heartbeat", + } def build_replan_action_packet( - obligation: Mapping[str, Any], - *, - goal_id: str | None = None, - agent_id: str | None = None, - bounded_research_frontier: Mapping[str, Any] | None = None, -) -> dict[str, Any]: + obligation: PayloadView, *, goal_id: str | None = None, + agent_id: str | None = None, bounded_research_frontier: PayloadView | None = None, +) -> Payload: settlement_packet = obligation.get("settlement_action_packet") if isinstance(settlement_packet, Mapping): return dict(settlement_packet) - context = obligation.get("replan_context") - from .replan_context_codec import validate_replan_context - context = validate_replan_context(context) - if context["obligation_id"] != obligation.get("obligation_id"): - raise ValueError("replan context obligation identity mismatch") + context = _validated_replan_context(obligation) todo_actions = obligation.get("todo_actions") - todo_action = next( - ( - dict(item) - for item in todo_actions or [] - if isinstance(item, Mapping) - and item.get("action") == "add" - and item.get("role") == "agent" - and str(item.get("text") or "").strip() - ), - {}, - ) + todo_action: PayloadView = next(( + cast(PayloadView, item) + for item in (todo_actions if isinstance(todo_actions, list) else ()) + if isinstance(item, Mapping) and item.get("action") == "add" + and item.get("role") == "agent" and str(item.get("text") or "").strip() + ), {}) successor_priority = str(todo_action.get("priority") or "P1").strip() if successor_priority not in {"P0", "P1", "P2", "P3", "P4"}: successor_priority = "P1" - raw_selected_gap = ( - bounded_research_frontier.get("selected_gap") - if isinstance(bounded_research_frontier, Mapping) - else None - ) - selected_gap: Mapping[str, Any] | None = ( - raw_selected_gap if isinstance(raw_selected_gap, Mapping) else None - ) - selected_gap_values: Mapping[str, Any] = selected_gap or {} - raw_binding = selected_gap_values.get("successor_binding") - raw_successor_binding: Mapping[str, Any] = ( - raw_binding if isinstance(raw_binding, Mapping) else {} - ) - successor_binding = replan_successor_semantic_binding( - action_kind=raw_successor_binding.get("action_kind"), - target_key=raw_successor_binding.get("target_key"), - explore_result_node_refs=raw_successor_binding.get( - "explore_result_node_refs" - ), - ) + raw_gap = bounded_research_frontier.get("selected_gap") if isinstance(bounded_research_frontier, Mapping) else None + selected_gap: PayloadView | None = cast(PayloadView, raw_gap) if isinstance(raw_gap, Mapping) else None requirements = replan_writeback_requirements(obligation) writeback_contract = requirements["writeback_contract"] - successor_summary = str( - selected_gap_values.get("successor_summary") or "" - ).strip()[:240] - if selected_gap is not None and successor_summary and successor_binding: - safe_goal_id = _stable_id(goal_id, field="goal_id") or "" - safe_agent_id = ( - _stable_id(agent_id or obligation.get("agent_id"), field="agent_id") - or "" - ) - successor_text = shlex.quote( - f"[{successor_priority}] {successor_summary}" - ) - successor_ref_args = "".join( - f" --explore-result-node-ref {shlex.quote(ref)}" - for ref in successor_binding.get("explore_result_node_refs") or [] + if selected_gap is not None: + override = _successor_writeback_contract( + obligation_id=obligation.get("obligation_id"), goal_id=goal_id, + agent_id=agent_id or obligation.get("agent_id"), + selected_gap=selected_gap, priority=successor_priority, ) - target_key_arg = ( - " --target-key " + shlex.quote(str(successor_binding["target_key"])) - if successor_binding.get("target_key") - else "" - ) - task_domain = normalize_todo_task_domain( - raw_successor_binding.get("task_domain") - ) - task_domain_arg = ( - " --task-domain " + shlex.quote(task_domain) if task_domain else "" - ) - writeback_contract = { - "successor_command": ( - "loopx todo add " - f"--goal-id {safe_goal_id} --role agent " - "--task-class advancement_task " - f"--action-kind {shlex.quote(str(successor_binding['action_kind']))}" - f"{task_domain_arg}{target_key_arg} " - f"--text {successor_text} " - f"--claimed-by {safe_agent_id} " - "--replan-obligation-id " - f"{obligation.get('obligation_id')}" - f"{successor_ref_args}" - ), - "successor_host_action": "end_current_heartbeat", - } - packet = { + if override is not None: + writeback_contract = override + else: + replan_successor_semantic_binding(action_kind=None, target_key=None, explore_result_node_refs=None) + packet: Payload = { "schema_version": REPLAN_ACTION_PACKET_SCHEMA_VERSION, "decision": "replan_required", "obligation_id": obligation.get("obligation_id"), @@ -546,21 +492,12 @@ def build_replan_action_packet( } if "stride_control" in requirements: packet["stride_control"] = requirements["stride_control"] - if isinstance(obligation.get("capability_guard"), Mapping): - packet["capability_guard"] = dict(obligation["capability_guard"]) + capability_guard = obligation.get("capability_guard") + if isinstance(capability_guard, Mapping): + packet["capability_guard"] = dict(capability_guard) packet["allowed_terminal"] = [] - if isinstance(selected_gap, Mapping): + if selected_gap is not None: packet["bounded_frontier"] = { - key: selected_gap[key] - for key in ( - "schema_version", - "gap_id", - "experiment_node_ref", - "input_node_refs", - "required_outcome", - "input_observations", - "frontier_revision", - ) - if key in selected_gap + key: selected_gap[key] for key in _BOUNDED_FRONTIER_KEYS if key in selected_gap } return packet diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index 8c4eb6edad..71cce84978 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -482,9 +482,10 @@ def qualify_replan_writeback( history_runs=newest_first_runs, recovering_writeback_path=recovering_writeback_path, ) + raw_outcomes = semantic_delta.get("outcomes") if ( - "coverage_backed_no_followup" - in set(semantic_delta.get("outcomes") or []) + isinstance(raw_outcomes, (list, tuple, set)) + and "coverage_backed_no_followup" in raw_outcomes and todo_succession_gap_items(agent_todos, agent_id=safe_agent_id) ): semantic_delta = { diff --git a/tests/control_plane/test_progress_observation_contract.py b/tests/control_plane/test_progress_observation_contract.py new file mode 100644 index 0000000000..22742993ed --- /dev/null +++ b/tests/control_plane/test_progress_observation_contract.py @@ -0,0 +1,327 @@ +"""Contract, Zero-Any, and malformed-input fail-closed tests for progress_observation.""" + +from __future__ import annotations + +import ast +import json +from pathlib import Path +import tokenize +from types import MappingProxyType +from typing import cast + +import pytest + +from loopx.control_plane.effect_runtime import EffectRuntimeRejected +from loopx.control_plane.work_items import progress_observation, replan_context_codec + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _ast_any_lines(path: Path) -> list[int]: + tree = ast.parse(path.read_text(encoding="utf-8")) + return [node.lineno for node in ast.walk(tree) if isinstance(node, ast.Name) and node.id == "Any"] + + +def _suppression_lines(path: Path) -> list[int]: + lines: list[int] = [] + with path.open("r", encoding="utf-8") as handle: + for tok in tokenize.generate_tokens(handle.readline): + if tok.type == tokenize.COMMENT and ("type: ignore" in tok.string or "noqa" in tok.string): + lines.append(tok.start[0]) + return lines + + +def test_progress_observation_meets_ceiling_zero_any_and_pin_invariants() -> None: + module_path = REPO_ROOT / "loopx/control_plane/work_items/progress_observation.py" + test_path = Path(__file__).resolve() + + assert len(module_path.read_text(encoding="utf-8").splitlines()) <= 550 + assert len(test_path.read_text(encoding="utf-8").splitlines()) < 500 + for path in (module_path, test_path): + assert _ast_any_lines(path) == [], str(path) + assert _suppression_lines(path) == [], str(path) + + pins = json.loads( + (REPO_ROOT / "tests/architecture/package_kernel_import_pins.json").read_text(encoding="utf-8") + ) + assert "loopx.control_plane.work_items.progress_observation" in pins["imports"]["loopx-jev"] + + for name in ( + "REPLAN_ACTION_PACKET_SCHEMA_VERSION", + "PROGRESS_REPEAT_TRIGGER_KIND", + "PROGRESS_REPEAT_THRESHOLD", + "MAX_PROGRESS_EVIDENCE_IDS", + "SEMANTIC_DIMENSIONS", + "TERMINAL_RESULT_CLASSES", + "FRESH_VISION_PATH_DISPOSITIONS", + "normalize_progress_observation", + "progress_observation_from_run", + "_progress_turn_instance_id", + "typed_progress_repeat_trigger", + "_normalized_window", + "replan_writeback_requirements", + "required_semantic_outcomes", + "replan_successor_transition_allowed", + "guarded_replan_transition_delta", + "replan_obligation_trigger_kinds", + "replan_obligation_trigger_checkpoints", + "semantic_delta_from_writeback", + "build_replan_context", + "build_replan_action_packet", + ): + assert hasattr(progress_observation, name), name + + +def test_normalize_progress_observation_validation_dedup_and_historical_guard() -> None: + with pytest.raises(TypeError, match="must be an object"): + progress_observation.normalize_progress_observation(cast(dict[str, object], ["bad"])) + + with pytest.raises(ValueError, match="progress observation must use"): + progress_observation.normalize_progress_observation( + {"schema_version": "legacy_v0", "result_class": "advanced", "surface_id": "s1"} + ) + + with pytest.raises(ValueError, match="result_class must be one of"): + progress_observation.normalize_progress_observation({"result_class": "invalid", "surface_id": "s1"}) + + with pytest.raises(ValueError, match="must be a boolean"): + progress_observation.normalize_progress_observation( + {"result_class": "advanced", "surface_id": "s1", "coverage_complete": "yes"} + ) + + with pytest.raises(ValueError, match="requires at least one stable"): + progress_observation.normalize_progress_observation({"result_class": "advanced"}) + + with pytest.raises(ValueError, match="public-safe identifier"): + progress_observation.normalize_progress_observation({"result_class": "advanced", "surface_id": "bad id / space"}) + + too_many = [f"ev-{i}" for i in range(progress_observation.MAX_PROGRESS_EVIDENCE_IDS + 1)] + with pytest.raises(ValueError, match="at most 12 identifiers"): + progress_observation.normalize_progress_observation({"result_class": "advanced", "evidence_ids": too_many}) + + first = progress_observation.normalize_progress_observation( + MappingProxyType({ + "result_class": "advanced", + "surface_id": " s1 ", + "evidence_ids": ["ev-b", "ev-a", "ev-b"], + "coverage_complete": False, + }), + work_item_id="todo_1", + ) + second = progress_observation.normalize_progress_observation( + { + "result_class": "advanced", + "surface_id": "s1", + "work_item_id": "todo_1", + "evidence_ids": ["ev-a", "ev-b"], + "coverage_complete": False, + } + ) + assert first == second + assert first["evidence_ids"] == ["ev-a", "ev-b"] + assert len(str(first["fingerprint"])) == 16 + + assert progress_observation.progress_observation_from_run({"progress_observation": "raw"}) is None + assert progress_observation.progress_observation_from_run({"progress_observation": {"result_class": "bad"}}) is None + assert ( + progress_observation.progress_observation_from_run( + {"progress_observation": {"result_class": "blocked", "blocker_id": "b1"}} + ) + is not None + ) + + assert progress_observation._progress_turn_instance_id( + {"turn_instance_id": "turn_1", "settlement_identity": {"turn_instance_id": "turn_2"}} + ) is None + assert progress_observation._progress_turn_instance_id({"turn_instance_id": "turn_1"}) == "turn_1" + + +def test_replan_semantics_wrappers_and_error_boundaries(monkeypatch: pytest.MonkeyPatch) -> None: + def _reject(*_a: object, **_kw: object) -> dict[str, object]: + raise EffectRuntimeRejected("denied by ts", diagnostic_code="rejected") + + monkeypatch.setattr(progress_observation, "project_replan_semantics", _reject) + with pytest.raises(ValueError, match="denied by ts"): + progress_observation.replan_writeback_requirements({}) + with pytest.raises(ValueError, match="denied by ts"): + progress_observation.replan_successor_transition_allowed({}) + with pytest.raises(ValueError, match="denied by ts"): + progress_observation.guarded_replan_transition_delta( + guard_scoped=True, selected_obligation_id="ob-1", transition_candidates=[] + ) + + monkeypatch.setattr(progress_observation, "project_replan_semantics", lambda _p: "bad") + with pytest.raises(RuntimeError, match="requirements must be an object"): + progress_observation.replan_writeback_requirements({}) + with pytest.raises(RuntimeError, match="eligibility shape mismatch"): + progress_observation.replan_successor_transition_allowed({}) + with pytest.raises(RuntimeError, match="transition shape mismatch"): + progress_observation.guarded_replan_transition_delta( + guard_scoped=False, selected_obligation_id=None, transition_candidates=[] + ) + + monkeypatch.setattr(progress_observation, "project_replan_semantics", lambda _p: {"semantic_delta": "bad"}) + with pytest.raises(RuntimeError, match="object or null"): + progress_observation.guarded_replan_transition_delta( + guard_scoped=False, selected_obligation_id=None, transition_candidates=[] + ) + + monkeypatch.setattr( + progress_observation, + "project_replan_semantics", + lambda _p: {"required_any_of": ["semantic_delta", "vision_update"]}, + ) + assert progress_observation.required_semantic_outcomes({}) == ["semantic_delta", "vision_update"] + + assert progress_observation.replan_obligation_trigger_kinds( + {"triggers": [{"kind": "repeat"}, {"kind": "repeat"}, {"kind": "blocker"}]} + ) == ["repeat", "blocker"] + assert progress_observation.replan_obligation_trigger_checkpoints({"triggers": []}) == [] + + monkeypatch.setattr( + progress_observation, + "effect_runtime_result", + lambda *_a, **_kw: {"trigger_checkpoints": "bad"}, + ) + with pytest.raises(TypeError, match="must be a list"): + progress_observation.replan_obligation_trigger_checkpoints({"triggers": [{"kind": "repeat"}]}) + + +def test_semantic_delta_writeback_and_action_packet_edges(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + replan_context_codec, + "validate_replan_context", + lambda ctx: { + "obligation_id": "ob-ctx", + "goal_id": "g-1", + "agent_id": "a-1", + "coverage_ledger": [{"result_class": "advanced", "surface_id": "s-cov"}], + **(dict(ctx) if isinstance(ctx, dict) else {}), + }, + ) + with pytest.raises(ValueError, match="identity mismatch"): + progress_observation.semantic_delta_from_writeback( + obligation={"obligation_id": "ob-other", "replan_context": {}}, + progress_observation=None, + ) + + with pytest.raises(ValueError, match="original replan context and full history"): + progress_observation.semantic_delta_from_writeback( + obligation={"obligation_id": "ob-1"}, + progress_observation=None, + recovering_writeback_path="runs/1.json", + ) + + with pytest.raises(ValueError, match="complete evidence history"): + progress_observation.semantic_delta_from_writeback( + obligation={"obligation_id": "ob-ctx", "replan_context": {"coverage_truncated": True}}, + progress_observation=None, + ) + + with pytest.raises(ValueError, match="not unique in replan history"): + progress_observation.semantic_delta_from_writeback( + obligation={"obligation_id": "ob-ctx", "replan_context": {}}, + progress_observation=None, + history_runs=[{"json_path": "runs/other.json"}], + recovering_writeback_path="runs/missing.json", + ) + + captured_calls: list[dict[str, object]] = [] + + def _qualify(params: dict[str, object]) -> dict[str, object]: + captured_calls.append(params) + if params["operation"] == "qualify": + return {"accepted": True, "outcomes": ["semantic_delta"]} + return { + "planning_guidance": "Pick another surface", + "writeback_contract": {"successor_command": "base"}, + "stride_control": {"max_steps": 3}, + } + + monkeypatch.setattr(progress_observation, "project_replan_semantics", _qualify) + monkeypatch.setattr( + replan_context_codec, + "replan_evidence_rows", + lambda runs, **_kw: [ + {"progress_observation": {"result_class": "advanced", "surface_id": str(r.get("s") or "")}} + for r in runs + ], + ) + monkeypatch.setattr( + replan_context_codec, + "replay_stride_review_evidence", + lambda **_kw: {"cited": True}, + ) + monkeypatch.setattr( + progress_observation, + "effect_runtime_result", + lambda *_a, **_kw: {"trigger_checkpoints": [{"kind": "repeat", "revision": "r1"}]}, + ) + + gen_runs = ( + row + for row in ( + {"json_path": "runs/skip.json", "s": "s-skip"}, + {"json_path": "runs/keep.json", "s": "s-keep"}, + ) + ) + qual = progress_observation.semantic_delta_from_writeback( + obligation={ + "obligation_id": "ob-ctx", + "replan_context": {"decision_followthrough": True}, + "triggers": [ + { + "kind": "repeat", + "progress_baseline": {"result_class": "advanced", "surface_id": "s-base"}, + "progress_window": [{"result_class": "advanced", "surface_id": "s-win"}], + } + ], + }, + progress_observation={"result_class": "advanced", "surface_id": "s-curr"}, + agent_vision={"state": "active", "stride_decision": {"previous_review": {"verdict": "ok"}}}, + history_runs=gen_runs, + recovering_writeback_path="runs/skip.json", + ) + assert qual["accepted"] is True + assert qual["trigger_kinds"] == ["repeat"] + assert qual["trigger_checkpoints"] == [{"kind": "repeat", "revision": "r1"}] + qual_source = captured_calls[0]["progress_source"] + assert isinstance(qual_source, dict) + window_surfaces = [item["surface_id"] for item in qual_source["window"]] + assert window_surfaces == ["s-win", "s-keep"] + assert captured_calls[0]["stride_review_evidence"] == {"cited": True} + + shortcut = progress_observation.build_replan_action_packet({"settlement_action_packet": {"decision": "cached"}}) + assert shortcut == {"decision": "cached"} + + packet = progress_observation.build_replan_action_packet( + { + "obligation_id": "ob-ctx", + "agent_id": "agent-1", + "replan_context": {"uncovered_frontier": ["f1"]}, + "todo_actions": [{"action": "add", "role": "agent", "text": "next step", "priority": "P0"}], + "capability_guard": {"kind": "require_evidence"}, + }, + goal_id="goal-1", + bounded_research_frontier={ + "selected_gap": { + "schema_version": "gap_v0", + "gap_id": "gap-1", + "successor_summary": "Run fresh probe", + "successor_binding": { + "action_kind": "verify", + "task_domain": "software", + "target_key": "target:1", + "explore_result_node_refs": ["node-1"], + }, + } + }, + ) + assert packet["allowed_terminal"] == [] + assert packet["capability_guard"] == {"kind": "require_evidence"} + assert packet["stride_control"] == {"max_steps": 3} + assert packet["bounded_frontier"] == {"schema_version": "gap_v0", "gap_id": "gap-1"} + wb = packet["writeback_contract"] + assert isinstance(wb, dict) + assert "--goal-id goal-1" in str(wb["successor_command"]) + assert "--explore-result-node-ref node-1" in str(wb["successor_command"])