diff --git a/loopx/chat_codex_goal.py b/loopx/chat_codex_goal.py index 36b8599ec3..11ff6f8453 100644 --- a/loopx/chat_codex_goal.py +++ b/loopx/chat_codex_goal.py @@ -184,6 +184,7 @@ def _response(self, goal: dict[str, Any] | None, text: str = "", *, messages: li def run( self, command: NativeGoalCommand, emit: Callable[[str, dict[str, Any]], None], *, execution_context: str | None = None, + on_resume_activated: Callable[[], None] | None = None, ) -> dict[str, Any]: if command.operation == "help": return parse_agent_response(USAGE, protected_paths=[self.session.work_dir]) @@ -240,6 +241,8 @@ def run( **({"objective": objective} if objective is not None else {}), }, ) + if command.operation == "resume" and on_resume_activated is not None: + on_resume_activated() except Exception: # A lost response does not prove that activation failed. self._stop_owned_transport_on_failure() diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py index b951543d3b..5fabe79c59 100644 --- a/loopx/chat_runtime.py +++ b/loopx/chat_runtime.py @@ -1913,7 +1913,60 @@ def event_sink(kind: str, payload: dict[str, Any]) -> None: execution_context = execution_guidance(self.store.load_turn(session_id, turn_id)) + "\nFresh scoped evidence:\n" + json.dumps(context, ensure_ascii=False) if execution_ended(): return - response = adapter.goal_driver.run(native_command, event_sink, execution_context=execution_context) + on_resume_activated = None + loopx_request = current_turn.get("loopx_request") + delegation_wake = ( + isinstance(loopx_request, Mapping) + and loopx_request.get("operation") == "wake" + ) + registry_path = self.registry_path + if ( + native_command.operation == "resume" + and not delegation_wake + and registry_path is not None + ): + from .agent_registry import load_goal_from_registry + from .control_plane.goals.activation_service import ( + GoalActivationState, + goal_activation_state, + set_goal_activation_state, + ) + + registered_goal = load_goal_from_registry( + registry_path, session["goal_id"] + ) + if ( + registered_goal is not None + and goal_activation_state(registered_goal) + is GoalActivationState.ACTIVE + ): + def record_owner_resume() -> None: + activation = set_goal_activation_state( + registry_path=registry_path, + goal_id=session["goal_id"], + state="active", + reason="Explicit Codex Goal resume", + actor_kind="owner", + owner_resume_action=True, + execute=True, + ) + if not activation.get("ok"): + raise CodexChatAgentError( + str( + activation.get("error") + or "LoopX owner resume epoch could not be recorded" + ), + error_code="goal_owner_resume_write_failed", + gate=None, + ) + + on_resume_activated = record_owner_resume + response = adapter.goal_driver.run( + native_command, + event_sink, + execution_context=execution_context, + on_resume_activated=on_resume_activated, + ) finally: if execution_lock is not None: execution_lock.__exit__(None, None, None) diff --git a/loopx/cli_commands/todo.py b/loopx/cli_commands/todo.py index 0aba5dff57..ea55679ebc 100644 --- a/loopx/cli_commands/todo.py +++ b/loopx/cli_commands/todo.py @@ -15,6 +15,16 @@ local_authority_is_promoted, ) from ..control_plane.effect_runtime import effect_runtime_result +from ..control_plane.quota.effect_program import SettlementBindingKind +from ..control_plane.quota.settlement import ( + SettlementFailureKind, + SettlementIdentity, + read_heartbeat_settlement, + settlement_result_payload, +) +from ..control_plane.quota.heartbeat_receipt import ( + bind_replan_successor_heartbeat_receipt, +) from ..control_plane.goals.first_party_host_admission import ( FirstPartyHostGoalAdmission, capture_first_party_host_goal_ref, @@ -24,11 +34,6 @@ build_task_planning_packet, render_task_planning_packet, ) -from ..control_plane.quota.settlement import ( - SettlementIdentity, - read_heartbeat_settlement, - settlement_result_payload, -) from ..control_plane.todos.completion_result import read_completion_result from ..control_plane.todos.list_readback import list_goal_todos from ..control_plane.todos.markdown import render_todo_markdown @@ -274,35 +279,8 @@ def handle_todo_command( registry_path=registry_path, runtime_root_arg=runtime_root_arg, ) - successor_settlement = None - if replan_obligation_id and args.turn_instance_id: - runtime_root = resolve_runtime_root( - load_registry(registry_path), runtime_root_arg - ) - successor_settlement = read_heartbeat_settlement( - runtime_root, - goal_id=args.goal_id, - agent_id=args.claimed_by, - todo_id=None, - turn_instance_id=args.turn_instance_id, - resolve_original_binding=True, - registry_path=registry_path, - goal_ref=goal_ref, - ) - if successor_settlement is None or successor_settlement.identity.value is None: - raise ValueError( - "replan successor requires the original admitted Turn binding" - ) - if successor_settlement.identity.failure is not None: - raise ValueError(successor_settlement.identity.failure.reason) - selected = (successor_settlement.semantic_replan_guard or {}).get( - "selected_obligation_id" - ) - if selected != replan_obligation_id: - raise ValueError( - "replan successor does not match the original Turn obligation" - ) - payload = add_goal_todo( + add_todo = partial( + add_goal_todo, operation_id=args.operation_id, registry_path=registry_path, runtime_root_arg=runtime_root_arg, @@ -350,8 +328,81 @@ def handle_todo_command( if value is not None }, **_todo_path_args(args), - dry_run=bool(args.dry_run), ) + successor_settlement = None + runtime_root = None + if replan_obligation_id and args.turn_instance_id and not args.dry_run: + # A failed Todo validation must not leave an otherwise ordinary + # Turn receipt irreversibly bound to a successor that was never + # created. Preview through the same mutation owner first. + preview = add_todo(dry_run=True) + if preview.get("ok") is not True: + raise ValueError( + str( + preview.get("error") + or "replan successor could not be validated" + ) + ) + runtime_root = resolve_runtime_root( + load_registry(registry_path), runtime_root_arg + ) + successor_settlement = read_heartbeat_settlement( + runtime_root, + goal_id=args.goal_id, + agent_id=args.claimed_by, + todo_id=None, + turn_instance_id=args.turn_instance_id, + resolve_original_binding=True, + registry_path=registry_path, + goal_ref=goal_ref, + ) + if ( + successor_settlement is not None + and successor_settlement.identity.value is None + and successor_settlement.identity.failure is not None + and successor_settlement.identity.failure.kind + is SettlementFailureKind.RECEIPT_UNBOUND + ): + bind_replan_successor_heartbeat_receipt( + runtime_root, + goal_id=args.goal_id, + agent_id=args.claimed_by, + turn_instance_id=args.turn_instance_id, + replan_obligation_id=replan_obligation_id, + goal_ref=goal_ref, + ) + successor_settlement = read_heartbeat_settlement( + runtime_root, + goal_id=args.goal_id, + agent_id=args.claimed_by, + todo_id=None, + turn_instance_id=args.turn_instance_id, + resolve_original_binding=True, + registry_path=registry_path, + goal_ref=goal_ref, + ) + if successor_settlement is None or successor_settlement.identity.value is None: + raise ValueError( + "replan successor requires the original admitted Turn binding" + ) + if successor_settlement.identity.failure is not None: + raise ValueError(successor_settlement.identity.failure.reason) + identity = successor_settlement.identity.value + if ( + identity.binding_kind is not SettlementBindingKind.AUTONOMOUS_REPLAN + or identity.replan_obligation_id != replan_obligation_id + ): + raise ValueError( + "replan successor has a different settlement identity" + ) + selected = (successor_settlement.semantic_replan_guard or {}).get( + "selected_obligation_id" + ) + if selected != replan_obligation_id: + raise ValueError( + "replan successor does not match the original Turn obligation" + ) + payload = add_todo(dry_run=bool(args.dry_run)) if replan_obligation_id and payload.get("ok"): payload["replan_transition"] = { "schema_version": "replan_successor_transition_v0", @@ -365,6 +416,7 @@ def handle_todo_command( if successor_settlement is None: payload["host_action"] = "end_current_heartbeat" else: + assert runtime_root is not None identity = successor_settlement.identity.value assert identity is not None payload["settlement_identity"] = identity.as_dict() diff --git a/loopx/control_plane/goals/activation_service.py b/loopx/control_plane/goals/activation_service.py index ce1a9672e7..b67a82024a 100644 --- a/loopx/control_plane/goals/activation_service.py +++ b/loopx/control_plane/goals/activation_service.py @@ -271,6 +271,7 @@ def set_goal_activation_state( runtime_root_override: str | None = None, expected_state_fingerprint: str | None = None, actor_kind: str | None = None, + owner_resume_action: bool = False, execute: bool = False, ) -> dict[str, Any]: """Preview or apply one reversible Goal activation transition.""" @@ -280,6 +281,13 @@ def set_goal_activation_state( raise ValueError("goal id is required") actor = normalize_owner_controller_actor(actor_kind, required=execute) target_state = normalize_goal_activation_state(state) + if owner_resume_action and not ( + target_state is GoalActivationState.ACTIVE + and actor is OwnerControllerActorKind.OWNER + ): + raise ValueError( + "owner resume action requires active state and the owner actor" + ) authority_route = _source_and_target( registry_path=registry_path, goal_id=normalized_goal_id, @@ -313,6 +321,7 @@ def set_goal_activation_state( ) before_state = goal_activation_state(source_goal) changed = before_state is not target_state + write_required = changed or owner_resume_action actor_label = actor.value if actor is not None else "owner" default_reason = ( f"Stopped by {actor_label}" @@ -335,6 +344,8 @@ def set_goal_activation_state( "before_state": before_state.value, "after_state": target_state.value, "changed": changed, + "owner_resume_action": owner_resume_action, + "owner_resume_advanced": False, "written": False, "partial_write": False, "source_registry": str(source_registry), @@ -350,8 +361,8 @@ def set_goal_activation_state( "actor_kind": actor.value if actor is not None else None, "readback": { "schema_version": GOAL_ACTIVATION_READBACK_SCHEMA_VERSION, - "status": "not_executed" if changed else "not_required", - "verified": not changed, + "status": "not_executed" if write_required else "not_required", + "verified": not write_required, }, } if ( @@ -476,14 +487,17 @@ def set_goal_activation_state( ) return payload owner_resume_id = goal_owner_resume_id(locked_goal) - if changed: + if write_required: # Preserve the owner resume across later lifecycle writes. - # Mint it inside the source lock for an actual owner resume. + # Mint it inside the source lock for an actual owner resume, + # including an explicit host resume while the LoopX Goal is + # already active. Ordinary guard entry never sets this flag. if ( target_state is GoalActivationState.ACTIVE and actor is OwnerControllerActorKind.OWNER ): owner_resume_id = uuid4().hex + payload["owner_resume_advanced"] = True if owner_resume_id is not None: proposed_activation["owner_resume_id"] = owner_resume_id locked_goal["activation"] = proposed_activation @@ -520,7 +534,9 @@ def set_goal_activation_state( payload["ok"] = bool(sync_ok and readback.get("verified")) payload["partial_write"] = bool(payload["written"] and not payload["ok"]) payload["projection_reconciled"] = bool( - not changed and registries_are_distinct and readback.get("verified") + not write_required + and registries_are_distinct + and readback.get("verified") ) if not payload["ok"]: payload["error"] = "goal activation shared registry readback did not verify" diff --git a/loopx/control_plane/quota/heartbeat_receipt.py b/loopx/control_plane/quota/heartbeat_receipt.py index 6d7fdd4c53..fe40b09a8d 100644 --- a/loopx/control_plane/quota/heartbeat_receipt.py +++ b/loopx/control_plane/quota/heartbeat_receipt.py @@ -448,6 +448,7 @@ def upgrade_identityless_heartbeat_receipt( summary: str, details: Mapping[str, object], goal_ref: Mapping[str, object] | None = None, + required_semantic_replan_obligation_id: str | None = None, ) -> tuple[dict[str, object], bool]: """Append one settlement-bound receipt after an identity-less same-turn guard. @@ -461,6 +462,18 @@ def upgrade_identityless_heartbeat_receipt( replan_obligation_id ) normalized_effect_id = str(settlement_effect_id).strip() + normalized_required_semantic_replan_obligation_id = ( + normalize_todo_replan_obligation_id( + required_semantic_replan_obligation_id + ) + ) + if ( + required_semantic_replan_obligation_id is not None + and normalized_required_semantic_replan_obligation_id is None + ): + raise HeartbeatReceiptIdentityConflictError( + "heartbeat receipt upgrade requires a valid semantic replan obligation" + ) if bool(normalized_todo_id) == bool(normalized_replan_obligation_id): raise HeartbeatReceiptIdentityConflictError( "heartbeat receipt upgrade requires exactly one deterministic " @@ -503,6 +516,35 @@ def upgrade_identityless_heartbeat_receipt( raise ValueError( "identity-less heartbeat receipt is missing; rerun the original guard" ) + effective_details_value = effective.get("details") + effective_details: Mapping[str, object] = ( + effective_details_value + if isinstance(effective_details_value, Mapping) + else {} + ) + if normalized_required_semantic_replan_obligation_id is not None: + selected_semantic_replan_obligation_id = ( + heartbeat_receipt_semantic_replan_obligation_id(effective) + ) + if ( + selected_semantic_replan_obligation_id + != normalized_required_semantic_replan_obligation_id + ): + raise HeartbeatReceiptIdentityConflictError( + "heartbeat receipt semantic replan guard conflicts with the " + "requested successor obligation" + ) + if not ( + effective_details.get("interaction_mode") == "autonomous_replan" + and effective_details.get("ok") is True + and effective_details.get("should_run") is True + and effective_details.get("must_attempt_work") is True + and effective_details.get("delivery_allowed") is False + and effective_details.get("quiet_noop_allowed") is False + ): + raise HeartbeatReceiptIdentityConflictError( + "heartbeat receipt did not admit an autonomous replan successor" + ) existing_identity = _receipt_settlement_identity(effective) expected_identity = ( expected_identity_value.binding_kind, @@ -536,7 +578,11 @@ def upgrade_identityless_heartbeat_receipt( if str(existing_details.get("settlement_effect_id") or "").strip(): return effective, False - corrected_details = dict(details) + # The effective receipt was read while holding the rollout lock. Keep + # fields appended by a concurrent same-Turn revision unless this + # correction explicitly replaces them. + corrected_details = dict(effective_details) + corrected_details.update(details) corrected_details.update( { "turn_instance_id": turn_instance_id, @@ -564,6 +610,50 @@ def upgrade_identityless_heartbeat_receipt( return corrected, True +def bind_replan_successor_heartbeat_receipt( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, + turn_instance_id: str, + replan_obligation_id: str, + goal_ref: Mapping[str, object] | None = None, +) -> tuple[dict[str, object], bool]: + """Bind an identity-less admitted replan when its successor is selected. + + Multi-candidate planning guards deliberately avoid binding a recommended + Todo. Creating a concrete successor is nevertheless an explicit semantic + replan choice. Upgrade that exact Turn to the already selected obligation + before the Todo mutation so later writeback and spend reuse one causal + identity. The upgrade rechecks the effective guard while holding the + rollout lock; stale or non-admitted semantic targets fail closed. + """ + + identity = SettlementIdentity( + goal_id=goal_id, + agent_id=agent_id, + todo_id=None, + turn_instance_id=turn_instance_id, + replan_obligation_id=replan_obligation_id, + ) + return upgrade_identityless_heartbeat_receipt( + runtime_root, + goal_id=goal_id, + agent_id=agent_id, + turn_instance_id=turn_instance_id, + replan_obligation_id=replan_obligation_id, + settlement_effect_id=identity.effect_id, + status="autonomous_replan_required", + summary=( + "heartbeat quota receipt bound by explicit replan successor selection " + f"for turn={turn_instance_id}" + ), + details={}, + goal_ref=goal_ref, + required_semantic_replan_obligation_id=replan_obligation_id, + ) + + def requalify_bound_heartbeat_receipt( runtime_root: Path, *, diff --git a/tests/control_plane/test_goal_activation.py b/tests/control_plane/test_goal_activation.py index b72f4ab98a..7db05f5a32 100644 --- a/tests/control_plane/test_goal_activation.py +++ b/tests/control_plane/test_goal_activation.py @@ -406,6 +406,39 @@ def test_controller_transitions_retain_legacy_owner_resume( assert _goal(global_registry)["activation"]["owner_resume_id"] == prior_resume +def test_explicit_owner_resume_advances_epoch_while_goal_is_already_active( + connected_registries: tuple[Path, Path], +) -> None: + source_registry, global_registry = connected_registries + first = set_goal_activation_state( + registry_path=global_registry, + goal_id="goal-one", + state="active", + actor_kind="owner", + owner_resume_action=True, + execute=True, + ) + first_resume = _goal(source_registry)["activation"]["owner_resume_id"] + assert first["ok"] is True + assert first["changed"] is False + assert first["written"] is True + assert first["owner_resume_advanced"] is True + assert _goal(global_registry)["activation"]["owner_resume_id"] == first_resume + + second = set_goal_activation_state( + registry_path=global_registry, + goal_id="goal-one", + state="active", + actor_kind="owner", + owner_resume_action=True, + execute=True, + ) + second_resume = _goal(source_registry)["activation"]["owner_resume_id"] + assert second["ok"] is True and second["readback"]["verified"] is True + assert second_resume != first_resume + assert _goal(global_registry)["activation"]["owner_resume_id"] == second_resume + + def test_activation_and_agent_registration_share_source_to_global_lock_order( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, diff --git a/tests/control_plane/test_heartbeat_receipt.py b/tests/control_plane/test_heartbeat_receipt.py index a127f1002e..5a7e6f04ba 100644 --- a/tests/control_plane/test_heartbeat_receipt.py +++ b/tests/control_plane/test_heartbeat_receipt.py @@ -6,9 +6,11 @@ import pytest from loopx.control_plane.quota.heartbeat_receipt import ( + bind_replan_successor_heartbeat_receipt, find_heartbeat_receipt, heartbeat_receipt_view, requalify_bound_heartbeat_receipt, + retain_pending_heartbeat_action_selection, upgrade_identityless_heartbeat_receipt, ) from loopx.rollout_event_log import ( @@ -99,6 +101,74 @@ def test_identityless_receipt_upgrade_rejects_conflicting_selected_todo( assert len(load_rollout_events(rollout_event_log_path(tmp_path, GOAL_ID))) == 2 +def test_replan_binding_rechecks_identity_inside_the_lock( + tmp_path: Path, +) -> None: + _append_receipt(tmp_path, todo_id=TODO_ID, effect_id=EFFECT_ID) + + with pytest.raises(ValueError): + bind_replan_successor_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + replan_obligation_id="replan-2222222222222222", + ) + + assert len(load_rollout_events(rollout_event_log_path(tmp_path, GOAL_ID))) == 1 + + +def test_replan_binding_preserves_concurrent_effective_details( + tmp_path: Path, +) -> None: + obligation_id = "replan-2222222222222222" + original = build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=TURN_ID, + status="autonomous_replan_required", + summary="identity-less autonomous replan receipt", + details={ + "interaction_mode": "autonomous_replan", + "ok": True, + "should_run": True, + "must_attempt_work": True, + "delivery_allowed": False, + "quiet_noop_allowed": False, + "semantic_replan_obligation_id": obligation_id, + }, + ) + log_path = rollout_event_log_path(tmp_path, GOAL_ID) + append_rollout_event(log_path, original) + retained, retained_appended = retain_pending_heartbeat_action_selection( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id="todo_concurrent_choice", + reason="owner_selected_candidate", + ) + assert retained_appended is True + + bound, appended = bind_replan_successor_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + replan_obligation_id=obligation_id, + ) + + assert appended is True + assert retained["details"]["pending_action_selection_todo_id"] == ( + "todo_concurrent_choice" + ) + assert bound["details"]["pending_action_selection_todo_id"] == ( + "todo_concurrent_choice" + ) + assert bound["details"]["replan_obligation_id"] == obligation_id + + def test_the_receipt_view_says_when_the_turn_still_owes_its_binding( tmp_path: Path, ) -> None: diff --git a/tests/control_plane/test_native_child_replan_guard_cli.py b/tests/control_plane/test_native_child_replan_guard_cli.py index bc7b5a4ccb..a4089d98b4 100644 --- a/tests/control_plane/test_native_child_replan_guard_cli.py +++ b/tests/control_plane/test_native_child_replan_guard_cli.py @@ -115,6 +115,123 @@ def _admitted_guard(call, todo_bound: bool) -> dict: return guard +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_visible_goal_begin_turn_binds_identityless_replan_when_successor_is_selected( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + call, runtime, _ = _fixture(tmp_path, monkeypatch, provider, True) + guard = call( + "quota", "should-run", "--runtime-profile", "codex_app_ssh_goal", + "--goal-id", GOAL, "--agent-id", AGENT, "--begin-turn", + ) + receipt = guard["heartbeat_receipt"] + assert receipt["settlement_binding_owed"] is True + assert "settlement_identity" not in receipt + assert guard["interaction_contract"]["cli_channel"]["selection_required"] is True + obligation = receipt["semantic_replan_obligation_id"] + turn = receipt["turn_instance_id"] + + from loopx.control_plane.quota.heartbeat_receipt import ( + bind_replan_successor_heartbeat_receipt, + find_heartbeat_receipt, + heartbeat_receipt_view, + ) + + with pytest.raises(ValueError, match="semantic replan guard conflicts"): + bind_replan_successor_heartbeat_receipt( + runtime, + goal_id=GOAL, + agent_id=AGENT, + turn_instance_id=turn, + replan_obligation_id="replan-0000000000000000", + ) + + successor = call( + "todo", "add", "--goal-id", GOAL, "--role", "agent", + "--claimed-by", AGENT, "--text", "Validate the selected replan route.", + "--task-class", "advancement_task", "--action-kind", "validate", + "--target-key", "selected-replan-route", "--operation-id", + "visible-goal-replan-successor", "--replan-obligation-id", obligation, + "--turn-instance-id", turn, + ) + assert successor["todo_id"].startswith("todo_") + + persisted = find_heartbeat_receipt( + runtime, goal_id=GOAL, agent_id=AGENT, turn_instance_id=turn, + ) + assert persisted is not None + upgraded = heartbeat_receipt_view( + persisted, turn_instance_id=turn, status="replayed", + ) + identity = upgraded["settlement_identity"] + assert identity["binding_kind"] == "autonomous_replan" + assert identity["replan_obligation_id"] == obligation + assert upgraded["semantic_replan_obligation_id"] == obligation + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_replan_successor_dry_run_does_not_bind_the_original_turn( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + call, runtime, _ = _fixture(tmp_path, monkeypatch, provider, True) + guard = call( + "quota", "should-run", "--runtime-profile", "codex_app_ssh_goal", + "--goal-id", GOAL, "--agent-id", AGENT, "--begin-turn", + ) + receipt = guard["heartbeat_receipt"] + obligation = receipt["semantic_replan_obligation_id"] + turn = receipt["turn_instance_id"] + log_path = rollout_event_log_path(runtime, GOAL) + before = load_rollout_events(log_path) + + preview = call( + "todo", "add", "--goal-id", GOAL, "--role", "agent", + "--claimed-by", AGENT, "--text", "Preview the selected replan route.", + "--task-class", "advancement_task", "--action-kind", "validate", + "--target-key", "selected-replan-route", "--operation-id", + "visible-goal-replan-preview", "--replan-obligation-id", obligation, + "--turn-instance-id", turn, "--dry-run", + ) + + assert preview["dry_run"] is True + assert preview["replan_transition"]["recorded"] is False + assert load_rollout_events(log_path) == before + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_replan_successor_validation_failure_does_not_bind_the_original_turn( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + call, runtime, _ = _fixture(tmp_path, monkeypatch, provider, True) + guard = call( + "quota", "should-run", "--runtime-profile", "codex_app_ssh_goal", + "--goal-id", GOAL, "--agent-id", AGENT, "--begin-turn", + ) + receipt = guard["heartbeat_receipt"] + obligation = receipt["semantic_replan_obligation_id"] + turn = receipt["turn_instance_id"] + log_path = rollout_event_log_path(runtime, GOAL) + before = load_rollout_events(log_path) + + call( + "todo", "add", "--goal-id", GOAL, "--role", "agent", + "--claimed-by", AGENT, "--text", "Invalid deferred successor.", + "--task-class", "advancement_task", "--action-kind", "validate", + "--target-key", "selected-replan-route", "--operation-id", + "visible-goal-replan-invalid", "--replan-obligation-id", obligation, + "--turn-instance-id", turn, "--status", "deferred", + expected_code=1, + ) + + assert load_rollout_events(log_path) == before + + @pytest.mark.parametrize("provider", ["file", "sqlite"]) @pytest.mark.parametrize("todo_bound", [True, False]) def test_legal_replan_reports_native_child_without_settling_parent( diff --git a/tests/test_chat_codex_goal.py b/tests/test_chat_codex_goal.py index 30bcebee65..8ee6d6dace 100644 --- a/tests/test_chat_codex_goal.py +++ b/tests/test_chat_codex_goal.py @@ -177,13 +177,17 @@ def test_resume_keeps_objective_and_accounting(tmp_path, monkeypatch): goal=native_goal("budgetLimited"), events=[begin("one"), complete, end("one")], ) + owner_resumes = [] host.driver.run( - parse_native_goal_command("/goal resume --tokens 2000"), lambda *a: None + parse_native_goal_command("/goal resume --tokens 2000"), + lambda *a: None, + on_resume_activated=lambda: owner_resumes.append("recorded"), ) activation = next(p for m, p in host.calls if m == "thread/goal/set") assert "objective" not in activation assert host.goal["objective"] == "Original objective" assert host.goal["tokensUsed"] == 500 and host.goal["createdAt"] == 123 + assert owner_resumes == ["recorded"] @pytest.mark.parametrize( @@ -386,6 +390,193 @@ def test_runtime_replay_and_native_state_use_existing_chat_turn(tmp_path, monkey controller.close() +def test_runtime_records_owner_resume_only_after_native_resume_activation( + tmp_path, monkeypatch +): + import loopx.agent_registry as agent_registry + import loopx.control_plane.goals.activation_service as activation_service + + host = Host( + tmp_path, + monkeypatch, + goal=native_goal("paused"), + events=[begin("one"), complete, end("one")], + ) + registry_path = tmp_path / "registry.json" + monkeypatch.setattr( + agent_registry, + "load_goal_from_registry", + lambda path, goal_id: {"id": goal_id}, + ) + activations = [] + + def record_activation(**kwargs): + activations.append(kwargs) + return {"ok": True} + + monkeypatch.setattr( + activation_service, "set_goal_activation_state", record_activation + ) + store = ChatSessionStore(tmp_path / "runtime" / "chat") + controller = ChatRuntimeController( + store=store, registry_path=registry_path, codex_bin="codex" + ) + session = store.create_session( + goal_id="fixture", + agent_id="codex", + adapter_kind="codex_app_server", + upstream_thread_id=host.session.thread_id, + upstream_mode="chat_native_goal", + channel_id="goal.fixture", + ) + sid = session["session_id"] + controller.adapters[sid] = CodexAppServerAdapter( + host.session, goal_driver=host.driver + ) + turn, created = controller.submit_turn( + session_id=sid, + client_turn_id="resume-one", + message="/goal resume --tokens 2000", + work_dir=tmp_path, + objective="Research", + ) + done = controller.wait_for_turn( + session_id=sid, turn_id=turn["turn_id"], timeout_sec=5 + ) + assert created and done["status"] == "completed", done + assert len(activations) == 1 + assert activations[0]["goal_id"] == "fixture" + assert activations[0]["state"] == "active" + assert activations[0]["actor_kind"] == "owner" + assert activations[0]["owner_resume_action"] is True + assert activations[0]["execute"] is True + controller.close() + + +def test_runtime_delegation_wake_does_not_advance_owner_resume( + tmp_path, monkeypatch +): + import loopx.agent_registry as agent_registry + import loopx.control_plane.goals.activation_service as activation_service + + host = Host( + tmp_path, + monkeypatch, + goal=native_goal("paused"), + events=[begin("one"), complete, end("one")], + ) + registry_path = tmp_path / "registry.json" + monkeypatch.setattr( + agent_registry, + "load_goal_from_registry", + lambda path, goal_id: {"id": goal_id}, + ) + activations = [] + monkeypatch.setattr( + activation_service, + "set_goal_activation_state", + lambda **kwargs: activations.append(kwargs) or {"ok": True}, + ) + store = ChatSessionStore(tmp_path / "runtime" / "chat") + controller = ChatRuntimeController( + store=store, registry_path=registry_path, codex_bin="codex" + ) + session = store.create_session( + goal_id="fixture", + agent_id="codex", + adapter_kind="codex_app_server", + upstream_thread_id=host.session.thread_id, + upstream_mode="chat_native_goal", + channel_id="goal.fixture", + ) + sid = session["session_id"] + original_load_turn = store.load_turn + + def load_wake_turn(session_id, turn_id): + turn = original_load_turn(session_id, turn_id) + if turn is not None and turn.get("client_turn_id") == "delegation-wake-one": + return {**turn, "loopx_request": {"operation": "wake"}} + return turn + + monkeypatch.setattr(store, "load_turn", load_wake_turn) + controller.adapters[sid] = CodexAppServerAdapter( + host.session, goal_driver=host.driver + ) + + turn, created = controller.submit_turn( + session_id=sid, + client_turn_id="delegation-wake-one", + message="/goal resume --tokens 2000", + work_dir=tmp_path, + objective="Research", + loopx_request={"operation": "wake"}, + ) + done = controller.wait_for_turn( + session_id=sid, turn_id=turn["turn_id"], timeout_sec=5 + ) + + assert created and done["status"] == "completed", done + assert activations == [] + controller.close() + + +def test_runtime_goal_resume_preserves_owner_stopped_state( + tmp_path, monkeypatch +): + import loopx.agent_registry as agent_registry + import loopx.control_plane.goals.activation_service as activation_service + + host = Host( + tmp_path, + monkeypatch, + goal=native_goal("paused"), + events=[begin("one"), complete, end("one")], + ) + registry_path = tmp_path / "registry.json" + monkeypatch.setattr( + agent_registry, + "load_goal_from_registry", + lambda path, goal_id: {"id": goal_id, "activation_state": "stopped"}, + ) + activations = [] + monkeypatch.setattr( + activation_service, + "set_goal_activation_state", + lambda **kwargs: activations.append(kwargs) or {"ok": True}, + ) + store = ChatSessionStore(tmp_path / "runtime" / "chat") + controller = ChatRuntimeController( + store=store, registry_path=registry_path, codex_bin="codex" + ) + session = store.create_session( + goal_id="fixture", + agent_id="codex", + adapter_kind="codex_app_server", + upstream_thread_id=host.session.thread_id, + upstream_mode="chat_native_goal", + channel_id="goal.fixture", + ) + sid = session["session_id"] + controller.adapters[sid] = CodexAppServerAdapter( + host.session, goal_driver=host.driver + ) + + turn, created = controller.submit_turn( + session_id=sid, + client_turn_id="stopped-resume-one", + message="/goal resume --tokens 2000", + work_dir=tmp_path, + objective="Research", + ) + done = controller.wait_for_turn( + session_id=sid, turn_id=turn["turn_id"], timeout_sec=5 + ) + + assert created and done["status"] == "completed", done + assert activations == [] + controller.close() + + def test_recovery_pauses_exact_thread_without_forking_or_resetting_goal( tmp_path, monkeypatch ):