diff --git a/loopx/control_plane/goals/activation_service.py b/loopx/control_plane/goals/activation_service.py index 368d3b2ea9..437a885beb 100644 --- a/loopx/control_plane/goals/activation_service.py +++ b/loopx/control_plane/goals/activation_service.py @@ -241,8 +241,9 @@ def _readback( goal_id: str, expected_state: GoalActivationState, expected_owner_resume_id: str | None, -) -> dict[str, Any]: - source_goal = _goal(load_registry(source_registry), goal_id) +) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: + source_payload = load_registry(source_registry) + source_goal = _goal(source_payload, goal_id) target_goal = _goal(load_registry(target_registry), goal_id) source_state = goal_activation_state(source_goal) target_state = goal_activation_state(target_goal) @@ -252,7 +253,7 @@ def _readback( and goal_owner_resume_id(source_goal) == expected_owner_resume_id and goal_owner_resume_id(target_goal) == expected_owner_resume_id ) - return { + summary = { "schema_version": GOAL_ACTIVATION_READBACK_SCHEMA_VERSION, "status": "verified" if verified else "mismatch", "verified": verified, @@ -261,6 +262,7 @@ def _readback( "source_state": source_state.value, "target_state": target_state.value, } + return summary, source_payload, source_goal def set_goal_activation_state( @@ -407,6 +409,7 @@ def set_goal_activation_state( return payload sync_payload: dict[str, Any] | None = None + closeout_source: dict[str, Any] | None = None with project_registry_transaction( source_registry, operation="set_goal_activation_state", @@ -473,7 +476,6 @@ def set_goal_activation_state( ) return payload locked_goal = _goal(source_payload, normalized_goal_id) - closeout_goal = dict(locked_goal) locked_state = goal_activation_state(locked_goal) if locked_state is not before_state: payload.update( @@ -516,21 +518,20 @@ def set_goal_activation_state( ) payload["global_sync"] = sync_payload - readback = ( - { + if sync_payload is not None and not sync_payload.get("ok"): + readback = { "schema_version": GOAL_ACTIVATION_READBACK_SCHEMA_VERSION, "status": "not_run", "verified": False, } - if sync_payload is not None and not sync_payload.get("ok") - else _readback( + else: + readback, closeout_source, closeout_goal = _readback( source_registry=source_registry, target_registry=target_registry, goal_id=normalized_goal_id, expected_state=target_state, expected_owner_resume_id=owner_resume_id, ) - ) payload["readback"] = readback sync_ok = sync_payload is None or bool(sync_payload.get("ok")) payload["ok"] = bool(sync_ok and readback.get("verified")) @@ -552,12 +553,13 @@ def set_goal_activation_state( and changed and payload.get("ok") and payload.get("written") - and closeout_goal is not None + and closeout_source is not None ): payload["closeout"] = _stop_closeout_payload( source_registry=source_registry, runtime_root_override=runtime_root_override, goal_id=normalized_goal_id, + closeout_source=closeout_source, closeout_goal=closeout_goal, ) return payload @@ -568,33 +570,45 @@ def _stop_closeout_payload( source_registry: Path, runtime_root_override: str | None, goal_id: str, + closeout_source: dict[str, Any], closeout_goal: Mapping[str, Any], ) -> dict[str, Any]: """Run the terminal hook after a committed stop transition.""" - from ...lifecycle.goal_closeout import run_goal_closeout + # The stop is already verified. Report any optional hook error separately. + try: + from ...lifecycle.goal_closeout import run_goal_closeout - closeout_runtime_root = resolve_runtime_root( - load_registry(source_registry), - runtime_root_override, - registry_path=source_registry, - ) - state_file = closeout_goal.get("state_file") - if not state_file: - state_file = ( - source_registry.parent - / "goals" - / goal_id - / "ACTIVE_GOAL_STATE.md" + closeout_runtime_root = resolve_runtime_root( + closeout_source, + runtime_root_override, + registry_path=source_registry, ) - return run_goal_closeout( - runtime_root=closeout_runtime_root, - goal_id=goal_id, - repo=str(closeout_goal.get("repo")) if closeout_goal.get("repo") else None, - state_file=str(state_file), - terminal_reason="stopped", - trigger="goal-lifecycle-stop", - ) + state_file = closeout_goal.get("state_file") + if not state_file: + state_file = ( + source_registry.parent + / "goals" + / goal_id + / "ACTIVE_GOAL_STATE.md" + ) + return run_goal_closeout( + runtime_root=closeout_runtime_root, + goal_id=goal_id, + repo=str(closeout_goal.get("repo")) if closeout_goal.get("repo") else None, + state_file=str(state_file), + terminal_reason="stopped", + trigger="goal-lifecycle-stop", + ) + except Exception as exc: + return { + "goal_id": goal_id, + "trigger": "goal-lifecycle-stop", + "terminal_reason": "stopped", + "status": "internal_error", + "error": "The closeout hook could not be prepared or run.", + "error_type": type(exc).__name__, + } def render_goal_activation_markdown(payload: dict[str, Any]) -> str: @@ -611,6 +625,9 @@ def render_goal_activation_markdown(payload: dict[str, Any]) -> str: readback = payload.get("readback") if isinstance(readback, dict): lines.append(f"- readback: `{readback.get('status')}`") + closeout = payload.get("closeout") + if isinstance(closeout, dict): + lines.append(f"- closeout: `{closeout.get('status')}`") if payload.get("error"): lines.extend(["", f"Error: {payload.get('error')}"]) return "\n".join(lines).rstrip() + "\n" diff --git a/tests/capabilities/test_goal_closeout_terminal_hooks.py b/tests/capabilities/test_goal_closeout_terminal_hooks.py index 85ea4891e8..7297e42999 100644 --- a/tests/capabilities/test_goal_closeout_terminal_hooks.py +++ b/tests/capabilities/test_goal_closeout_terminal_hooks.py @@ -4,6 +4,8 @@ import sys from pathlib import Path +import pytest + from loopx.capabilities.goal_closeout.machine_defaults import ( GOAL_CLOSEOUT_CONFIGURATION_SCHEMA, ) @@ -13,6 +15,7 @@ from loopx.capabilities.machine_configuration.store import ( configure_machine_configuration, ) +from loopx.control_plane.goals import activation_service from loopx.control_plane.goals.activation_service import set_goal_activation_state from loopx.global_registry import retire_global_registry_goals, sync_project_registry_to_global from loopx.lifecycle.goal_closeout import GOAL_CLOSEOUT_LEDGER_FILENAME @@ -135,7 +138,7 @@ def _ledger(root: Path, goal_id: str) -> list[dict[str, object]]: ] -def test_stop_runs_closeout_once_and_dry_run_does_not(tmp_path: Path) -> None: +def _registered_closeout_goal(tmp_path: Path) -> tuple[Path, Path, Path]: runtime_root = tmp_path / "runtime" project = tmp_path / "project" source_registry = project / ".loopx" / "registry.json" @@ -161,7 +164,12 @@ def test_stop_runs_closeout_once_and_dry_run_does_not(tmp_path: Path) -> None: dry_run=False, ) assert synced["ok"] is True - global_registry = runtime_root / "registry.global.json" + return source_registry, runtime_root / "registry.global.json", runtime_root + + +def test_stop_runs_closeout_once_and_dry_run_does_not(tmp_path: Path) -> None: + source_registry, global_registry, runtime_root = _registered_closeout_goal(tmp_path) + project = source_registry.parent.parent payload_path = tmp_path / "payloads.jsonl" _configure_closeout(runtime_root, payload_path) @@ -201,6 +209,66 @@ def test_stop_runs_closeout_once_and_dry_run_does_not(tmp_path: Path) -> None: assert len(_ledger(runtime_root, "goal-one")) == 1 +@pytest.mark.parametrize("failure", ["extra_registry_read", "hook_preparation", "no_hook_configured"]) +def test_stop_cli_preserves_verified_receipt_after_closeout_failure(tmp_path, monkeypatch, capsys, failure): + from loopx.cli import main + + source_registry, global_registry, runtime_root = _registered_closeout_goal(tmp_path) + payload_path = tmp_path / "hook-payloads.jsonl" + if failure != "no_hook_configured": + _configure_closeout(runtime_root, payload_path) + original_readback = activation_service._readback + original_load_registry = activation_service.load_registry + original_resolve_runtime_root = activation_service.resolve_runtime_root + readback_complete = False + + def finish_readback(**kwargs): + nonlocal readback_complete + result = original_readback(**kwargs) + readback_complete = True + return result + + def read_registry(path): + if readback_complete: + raise OSError("a late registry read must not be needed") + return original_load_registry(path) + + def resolve_runtime_root(*args, **kwargs): + if readback_complete: + raise OSError("sensitive runtime path from preparation failure") + return original_resolve_runtime_root(*args, **kwargs) + + monkeypatch.setattr(activation_service, "_readback", finish_readback) + if failure == "hook_preparation": + monkeypatch.setattr(activation_service, "resolve_runtime_root", resolve_runtime_root) + else: + monkeypatch.setattr(activation_service, "load_registry", read_registry) + exit_code = main(["--registry", str(global_registry), "--format", "json", "goal-lifecycle", + "--operation", "stop", "--goal-id", "goal-one", "--actor-kind", "owner", "--execute"]) + output = capsys.readouterr() + result = json.loads(output.out) + assert readback_complete is True + for registry in (source_registry, global_registry): + (goal,) = json.loads(registry.read_text(encoding="utf-8"))["goals"] + assert goal["activation"]["state"] == "stopped" + assert exit_code == 0 and result["ok"] and result["written"], result + assert result["readback"]["verified"] and not result["partial_write"] + if failure == "hook_preparation": + assert result["closeout"]["status"] == "internal_error" + assert result["closeout"]["error_type"] == "OSError" + assert "sensitive runtime path" not in output.out + assert not payload_path.exists() + elif failure == "no_hook_configured": + assert result["closeout"]["status"] == "not_configured" + assert not payload_path.exists() + else: + assert result["closeout"]["status"] == "success" + hook_payload = json.loads(payload_path.read_text(encoding="utf-8")) + assert hook_payload["repo"] == str(source_registry.parent.parent) + assert hook_payload["runtime_root"] == str(runtime_root) + assert len(_ledger(runtime_root, "goal-one")) == 1 + + def test_retire_runs_closeout_for_each_retired_goal(tmp_path: Path) -> None: runtime_root = tmp_path / "runtime" global_registry = runtime_root / "registry.global.json"