Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions loopx/control_plane/goals/goal_frontier/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
latest_autonomous_replan_ack_from_status_payload,
latest_missing_vision_checkpoint_from_status_payload,
latest_replan_ack_feedback_from_status_payload,
receipt_bound_vision_history_candidate,
)
from .terminal import (
GOAL_TERMINAL_SOURCE_COMPLETENESS_SCHEMA_VERSION, # noqa: F401
Expand Down Expand Up @@ -1427,6 +1428,7 @@ def build_goal_frontier_projection_context_from_status(
agent_profile: dict[str, Any] | None = None,
receipt_bound_replan_obligation_id: str | None = None,
receipt_bound_guard_recorded_at: str | None = None,
receipt_bound_history_runs: list[dict[str, Any]] | 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.
Expand Down Expand Up @@ -1705,6 +1707,19 @@ def build_goal_frontier_projection_context_from_status(
"reconstructed_vision_review": True,
}

if (receipt_bound_replan_obligation_id and receipt_bound_history_runs is not None
and (frontier_transition_candidate.get("obligation") or {}).get("obligation_id")
!= receipt_bound_replan_obligation_id):
historical = receipt_bound_vision_history_candidate(
receipt_bound_history_runs, goal_id=goal_id, agent_id=agent_id or "",
selected_obligation_id=receipt_bound_replan_obligation_id,
guard_recorded_at=receipt_bound_guard_recorded_at,
neutral_classifications=neutral_replan_ack_classifications,
goal_status=goal_status,
)
if historical:
frontier_transition_candidate = historical

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
Expand Down
56 changes: 56 additions & 0 deletions loopx/control_plane/goals/goal_frontier/semantic_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,59 @@ def latest_lane_recommendation_from_status(
row = context.get("latest_lane_step_run") if isinstance(context, dict) else None
return latest_bound_recommendation([row], agent_id) if isinstance(row, dict) else None
return latest_bound_recommendation(_latest_runs_for_goal(status_payload, goal_id=goal_id), agent_id)


def receipt_bound_vision_history_candidate(
runs: list[dict[str, Any]], *, goal_id: str, agent_id: str,
selected_obligation_id: str, guard_recorded_at: str | None,
neutral_classifications: set[str], goal_status: str | None,
) -> dict[str, Any] | None:
"""Recover only a plain Vision source from canonical history at admission.

This is a write-time query over the complete scoped history, not the
current status window or its already folded semantic slots. A later
checkpoint supplement is not an ACK of the admitted review. Reuse the
ordinary source reducers, preserve their full triggers and stop, and leave
fresh outcome qualification and once-only settlement to their owners.
"""
from ...runtime.time import parse_timestamp
from . import (
acceptance_gaps_from_agent_vision, derive_goal_frontier_replan_obligation_from_summaries,
outcome_continuity,
)

cutoff = parse_timestamp(guard_recorded_at)
if not agent_id or cutoff is None or cutoff.tzinfo is None:
return None
historical = []
for run in runs:
timestamp = parse_timestamp(run.get("generated_at"))
if (run.get("goal_id") == goal_id and run.get("agent_id") == agent_id
and timestamp is not None and timestamp.tzinfo is not None and timestamp <= cutoff):
historical.append((timestamp, run))
if not historical:
return None
historical.sort(key=lambda item: item[0], reverse=True)
status = {"run_history": {"goals": [{"id": goal_id,
"latest_runs": [run for _, run in historical]}]}}
vision = latest_agent_vision_from_status_payload(status, goal_id=goal_id, agent_id=agent_id)
missing = latest_missing_vision_checkpoint_from_status_payload(status, goal_id=goal_id, agent_id=agent_id)
checkpoint = outcome_continuity.latest_outcome_vision_checkpoint_from_status_payload(
status, goal_id=goal_id, agent_id=agent_id)
gaps = (acceptance_gaps_from_agent_vision(vision, goal_status=goal_status)
+ outcome_continuity.acceptance_gaps_from_vision_checkpoint(missing)
+ outcome_continuity.acceptance_gaps_from_outcome_checkpoint(vision, checkpoint))
if not gaps or any(gap.get("kind") not in {
"vision_acceptance_gap", "vision_checkpoint_missing", "vision_outcome_checkpoint_required",
} for gap in gaps):
return None
ack = latest_autonomous_replan_ack_from_status_payload(status, goal_id=goal_id,
agent_id=agent_id, neutral_classifications=neutral_classifications)
source = derive_goal_frontier_replan_obligation_from_summaries(
user_todo_summary=None, agent_todo_summary=None, work_lane_contract=None,
agent_id=agent_id, existing_replan_obligation=None,
latest_replan_ack=ack, acceptance_gaps=gaps,
vision_settlement_query=True)
if not source or source.get("obligation_id") != selected_obligation_id:
return None
return {"obligation": source, "ack": None, "reconstructed_vision_review": True}
26 changes: 22 additions & 4 deletions loopx/control_plane/quota/live_decision.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,32 @@ def _project_receipt_replan_settlement(
goal_ref: Mapping[str, Any] | None,
) -> None:
"""Project closeout from the original readback, never the current selection."""
if not readback or not _original_replan_settlement_required(payload, readback):
if not readback:
return
attach_settlement_progress(payload, readback, registry_path=registry_path,
runtime_root=runtime_root, goal_ref=goal_ref)
closeout_required = _original_replan_settlement_required(payload, readback)
identity = readback.identity.value
guard = getattr(readback, "semantic_replan_guard", None)
semantic_id = replan_obligation_id_from_packet(payload.get("replan_action_packet"))
open_todo_review = (
readback.replay_phase is ReceiptBoundReplayPhase.OPEN
and identity is not None and identity.todo_id is not None
and readback.heartbeat_receipt is not None
and isinstance(guard, Mapping) and guard.get("scope") == "turn_guard"
and semantic_id is not None and guard.get("selected_obligation_id") == semantic_id
and payload.get("should_run") is True
and payload.get("effective_action") == EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED.value
)
if not closeout_required and not open_todo_review:
return
if closeout_required:
attach_settlement_progress(payload, readback, registry_path=registry_path,
runtime_root=runtime_root, goal_ref=goal_ref)
if identity is None:
raise ValueError("original replan settlement identity is unavailable")
payload["heartbeat_receipt"] = {**(readback.heartbeat_receipt or {}), "settlement_identity": identity.as_dict()}
receipt = {**(readback.heartbeat_receipt or {}), "settlement_identity": identity.as_dict()}
if isinstance(guard, Mapping) and guard.get("scope") == "turn_guard":
receipt.setdefault("semantic_replan_obligation_id", guard.get("selected_obligation_id"))
payload["heartbeat_receipt"] = receipt
payload["interaction_contract"] = build_interaction_contract(payload,
available_capabilities=available_capabilities, scheduler_execution_context=scheduler_execution_context,
turn_instance_id=turn_instance_id, registry_path=str(registry_path), runtime_root=str(runtime_root))
Expand Down
11 changes: 11 additions & 0 deletions loopx/control_plane/quota/should_run_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from ..goals.goal_frontier.fallback_source import FallbackTodoSource

from ...materials import goal_state_path
from ...history import load_index

from ...quota import (
AUTONOMOUS_REPLAN_ACK_NEUTRAL_CLASSIFICATIONS,
Expand Down Expand Up @@ -260,6 +261,15 @@ def _prepare_quota_replan_context(
replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None,
) -> tuple[dict[str, Any], dict[str, Any] | None]:
"""Project the current frontier and contextualize its receipt-bound review."""
history_runs = None
runtime = status_payload.get("runtime_root")
if (receipt_bound_replan_guard_scoped and receipt_bound_replan_obligation_id
and receipt_bound_replay_phase is ReceiptBoundReplayPhase.OPEN
and isinstance(runtime, str) and Path(runtime).is_absolute()):
# A compact status window has already folded checkpoint supplements.
# Recovery needs the same full canonical source as write qualification.
history_runs, _ = load_index(
Path(runtime) / "goals" / safe_goal_id / "runs" / "index.jsonl")
goal_frontier_context = build_goal_frontier_projection_context_from_status(
replan_explore_reader=replan_explore_reader,
goal_id=safe_goal_id,
Expand All @@ -279,6 +289,7 @@ def _prepare_quota_replan_context(
agent_profile=_quota_agent_profile(agent_identity),
receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id,
receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at,
receipt_bound_history_runs=history_runs,
)
replan_obligation = (
None
Expand Down
18 changes: 14 additions & 4 deletions loopx/control_plane/work_items/interaction_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,15 +488,23 @@ def _turn_scoped_cli_settlement_context(
receipt = payload.get("heartbeat_receipt")
replan_packet = payload.get("replan_action_packet")
replan_settlement_only = isinstance(replan_packet, Mapping) and replan_packet.get("settlement_only") is True
if (replan_settlement_only and isinstance(receipt, Mapping)
semantic_replan_obligation_id = replan_obligation_id_from_packet(replan_packet)
receipt_identity = None
if (semantic_replan_obligation_id is not None and isinstance(receipt, Mapping)
and receipt.get("settlement_identity") is not None):
identity = SettlementIdentity.from_runtime_payload(receipt["settlement_identity"])
if (identity.goal_id, identity.agent_id, identity.turn_instance_id) != (goal_id, agent_id, turn_instance_id):
raise ValueError("receipt settlement projection does not match the original Goal/Agent/Turn")
guard = normalize_todo_replan_obligation_id(receipt.get("semantic_replan_obligation_id"))
if ("semantic_replan_obligation_id" in receipt and guard != semantic_replan_obligation_id) or (
identity.todo_id is not None and not replan_settlement_only and guard != semantic_replan_obligation_id
) or (identity.replan_obligation_id is not None
and identity.replan_obligation_id != semantic_replan_obligation_id):
raise ValueError("receipt settlement projection does not match the original semantic guard")
if selected_todo_id is not None and selected_todo_id != identity.todo_id:
raise ValueError("receipt settlement projection cannot replace the original Todo binding")
receipt_identity = identity
selected_todo_id = identity.todo_id
semantic_replan_obligation_id = replan_obligation_id_from_packet(
payload.get("replan_action_packet")
)
replan_settlement_contract = None
todo_id = selected_todo_id
replan_obligation_id = None
Expand Down Expand Up @@ -547,6 +555,8 @@ def _turn_scoped_cli_settlement_context(
)
if plan is None:
return None, replan_settlement_contract
if receipt_identity is not None and plan.identity.effect_id != receipt_identity.effect_id:
raise ValueError("receipt settlement projection changed the original effect identity")
cli_plan = plan.as_dict()
owed = payload.get("settlement_owed")
if (replan_settlement_only and isinstance(owed, Mapping)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ def qualify_replan_writeback(
goal_status=str((registry_goal or {}).get("status") or "active"),
receipt_bound_replan_obligation_id=(guard_semantic_replan_obligation_id if guard_scoped else None),
receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at,
receipt_bound_history_runs=list(newest_first_runs or []) if guard_scoped else None,
agent_profile=(
cast(dict[str, Any], cast(dict[str, Any], agent_identity).get("agent_profile"))
if isinstance(cast(dict[str, Any], agent_identity).get("agent_profile"), dict)
Expand Down
19 changes: 19 additions & 0 deletions tests/control_plane/test_replan_receipt_empty_guard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Legacy missing fields do not authorize an explicitly absent/invalid guard."""
import pytest

from loopx.control_plane.effect_program import SettlementIdentity
from test_replan_receipt_projection import AGENT, GOAL, TURN, OBLIGATION, _payload, _project


@pytest.mark.parametrize("guard", [None, "", "malformed"])
@pytest.mark.parametrize("binding", ["todo", "replan"])
def test_explicit_invalid_guard_cannot_enter_legacy_settlement_compatibility(guard, binding):
payload, _ = _payload()
payload["replan_action_packet"]["settlement_only"] = True
payload["heartbeat_receipt"]["semantic_replan_obligation_id"] = guard
if binding == "replan":
payload["heartbeat_receipt"]["settlement_identity"] = SettlementIdentity(
goal_id=GOAL, agent_id=AGENT, todo_id=None, replan_obligation_id=OBLIGATION,
turn_instance_id=TURN).as_dict()
with pytest.raises(ValueError, match="semantic guard"):
_project(payload)
64 changes: 64 additions & 0 deletions tests/control_plane/test_replan_receipt_live_projection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Live construction sees the existing receipt before the CLI publishes it."""
from copy import deepcopy
from types import SimpleNamespace

import pytest

from loopx.control_plane.effect_program import ReceiptBoundReplayPhase
from loopx.control_plane.quota.live_decision import _project_receipt_replan_settlement
from loopx.control_plane.scheduler.execution_context import scheduler_execution_context_for_runtime_profile
from test_replan_receipt_projection import TURN, OBLIGATION, _payload


def _source():
payload, identity = _payload()
receipt = payload.pop("heartbeat_receipt")
del receipt["semantic_replan_obligation_id"]
payload.update(ok=True, should_run=True, effective_action="autonomous_replan_required",
normal_delivery_allowed=False, execution_obligation={"kind": "autonomous_replan_required",
"must_attempt_work": True, "delivery_allowed": False})
readback = SimpleNamespace(identity=SimpleNamespace(value=identity), heartbeat_receipt=receipt,
replay_phase=ReceiptBoundReplayPhase.OPEN,
semantic_replan_guard={"scope": "turn_guard", "selected_obligation_id": OBLIGATION})
return payload, readback, identity


def _project(payload, readback, tmp_path):
_project_receipt_replan_settlement(payload, readback, available_capabilities=None,
scheduler_execution_context=scheduler_execution_context_for_runtime_profile("generic_cli"),
turn_instance_id=TURN, registry_path=tmp_path / "registry.json", runtime_root=tmp_path,
goal_ref=None)


def test_open_review_projects_its_existing_receipt_before_cli_publication(tmp_path):
payload, readback, identity = _source()
before = deepcopy(readback.heartbeat_receipt)
_project(payload, readback, tmp_path)
assert payload["interaction_contract"]["cli_channel"]["settlement_plan"]["identity"] == identity.as_dict()
assert payload["heartbeat_receipt"]["semantic_replan_obligation_id"] == OBLIGATION
assert payload["normal_delivery_allowed"] is False
assert payload["replan_action_packet"]["settlement_only"] is False
assert readback.heartbeat_receipt == before


@pytest.mark.parametrize("mismatch", ["phase", "guard", "scope", "identity"])
def test_open_projection_requires_exact_canonical_receipt(tmp_path, mismatch):
payload, readback, _ = _source()
if mismatch == "phase":
readback.replay_phase = ReceiptBoundReplayPhase.SETTLED
elif mismatch == "guard":
readback.semantic_replan_guard["selected_obligation_id"] = "replan-2222222222222222"
elif mismatch == "scope":
readback.semantic_replan_guard["scope"] = "unscoped"
else:
readback.identity.value = None
_project(payload, readback, tmp_path)
assert "heartbeat_receipt" not in payload
assert "interaction_contract" not in payload


def test_open_projection_does_not_replace_an_explicit_conflicting_guard(tmp_path):
payload, readback, _ = _source()
readback.heartbeat_receipt["semantic_replan_obligation_id"] = ""
with pytest.raises(ValueError, match="semantic guard"):
_project(payload, readback, tmp_path)
60 changes: 60 additions & 0 deletions tests/control_plane/test_replan_receipt_projection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""A semantic review never changes the original causal settlement binding."""
from copy import deepcopy

import pytest

from loopx.control_plane.effect_program import SettlementIdentity
from loopx.control_plane.scheduler.execution_context import scheduler_execution_context_for_runtime_profile
from loopx.control_plane.work_items.interaction_contract import _turn_scoped_cli_settlement_context

GOAL, AGENT, TURN, TODO = "receipt-review-fixture", "review-agent", "original-turn", "todo_original"
OBLIGATION = "replan-1111111111111111"


def _payload():
identity = SettlementIdentity(goal_id=GOAL, agent_id=AGENT, todo_id=TODO, turn_instance_id=TURN)
return {"goal_id": GOAL, "agent_identity": {"agent_id": AGENT},
"selected_todo": None,
"replan_action_packet": {"obligation_id": OBLIGATION, "settlement_only": False},
"heartbeat_receipt": {"status": "replayed", "turn_instance_id": TURN,
"semantic_replan_obligation_id": OBLIGATION, "settlement_identity": identity.as_dict()}}, identity


def _project(payload):
return _turn_scoped_cli_settlement_context(payload, available_capabilities=None,
scheduler_execution_context=scheduler_execution_context_for_runtime_profile("generic_cli"),
turn_instance_id=TURN)


def test_fresh_vision_review_keeps_terminal_todos_original_receipt_binding():
payload, identity = _payload()
before = deepcopy(payload)
plan, _ = _project(payload)
assert plan["identity"] == identity.as_dict()
for step in plan["ordered_steps"]:
if command := step.get("command_template"):
assert "--todo-id " + TODO in command
assert "--replan-obligation-id" not in command
assert payload == before


@pytest.mark.parametrize("field,value", [
("goal_id", "another-goal"), ("agent_id", "another-agent"),
("turn_instance_id", "another-turn"), ("semantic_replan_obligation_id", "replan-2222222222222222"),
])
def test_review_projection_rejects_a_conflicting_receipt(field, value):
payload, _ = _payload()
if field == "semantic_replan_obligation_id":
payload["heartbeat_receipt"][field] = value
else:
payload["heartbeat_receipt"]["settlement_identity"][field] = value
with pytest.raises((ValueError, RuntimeError)):
_project(payload)


def test_unbound_first_review_still_has_a_direct_replan_plan():
payload, _ = _payload()
del payload["heartbeat_receipt"]
plan, _ = _project(payload)
assert plan["identity"]["replan_obligation_id"] == OBLIGATION
assert plan["identity"].get("todo_id") is None
Loading
Loading