From 56366ae6a7e94ee3cdb36d33f21048d470cb58a7 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:21:45 +0800 Subject: [PATCH] Resume a saved first Goal Turn after its checker recovers Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_commands/start_goal.py | 9 ++- loopx/cli_commands/start_goal_managed.py | 97 +++++++++++++++++------- packages/loopx-core/README.md | 5 ++ tests/test_core_distribution.py | 72 ++++++++++++++++++ 4 files changed, 154 insertions(+), 29 deletions(-) diff --git a/loopx/cli_commands/start_goal.py b/loopx/cli_commands/start_goal.py index 4736ca1a16..e75b4ebbc6 100644 --- a/loopx/cli_commands/start_goal.py +++ b/loopx/cli_commands/start_goal.py @@ -206,6 +206,11 @@ def register_start_goal_command(subparsers: argparse._SubParsersAction[argparse. action="store_true", help="Start one checked task in a fresh local project with an independent check.", ) + start_goal_parser.add_argument( + "--retry-failed-turn", + action="store_true", + help="With the original --execute request, resume its saved first Turn without rerunning the worker.", + ) start_goal_parser.add_argument( "--host", dest="execution_host", @@ -415,10 +420,10 @@ def handle_start_goal_command( return 0 if payload["ok"] else 1 print_payload(payload, args.format, lambda failure: _render_start_goal_markdown(failure, guided=False)) return 1 - if any(getattr(args, name, None) is not None for name in ( + if getattr(args, "retry_failed_turn", False) or any(getattr(args, name, None) is not None for name in ( "execution_host", "host_adapter_command_json", "validation_command_json", "write_dir", )): - print_payload({"ok": False, "error": "Host and check options require start-goal --execute."}, + print_payload({"ok": False, "error": "Host, check and retry options require start-goal --execute."}, args.format, _render_start_goal_markdown) return 2 if not bool(getattr(args, "guided", False)): diff --git a/loopx/cli_commands/start_goal_managed.py b/loopx/cli_commands/start_goal_managed.py index 0a7df9f1b7..2e5dfabc49 100644 --- a/loopx/cli_commands/start_goal_managed.py +++ b/loopx/cli_commands/start_goal_managed.py @@ -16,7 +16,11 @@ from ..control_plane.quota.turn_envelope import COMPLETE_TURN_HOST_REQUEST_SCHEMA from ..control_plane.todos.mutation_api import add_goal_todo, update_goal_todo from ..control_plane.turn_driver.command_validation import build_loopx_turn_command_validator, normalize_host_argv -from ..control_plane.turn_driver.journal_store import find_loopx_turn_key_by_instance +from ..control_plane.turn_driver.executor import inspect_loopx_turn_journal +from ..control_plane.turn_driver.journal_store import ( + find_loopx_turn_key_by_instance, + load_loopx_turn_plan_from_journal, +) from ..kunluncode_goal_mode.guards import native_controller_cli_write_block from ..paths import resolve_runtime_root from ..registry import find_registry_goal @@ -172,40 +176,75 @@ def execute_managed_start( **launch_identity, "validator": validator_argv, }) operation_id = "start-" + digest.removeprefix("sha256:")[:32] - _register_first_goal( - registry_path=registry_path, runtime_root=runtime_root, project=project, - goal_id=goal_id, agent_id=agent_id, objective=objective, - display_name=display_name, operation_id=operation_id, write_scope=write_scope, - ) - todo = add_goal_todo( - registry_path=registry_path, runtime_root_arg=str(runtime_root), - goal_id=goal_id, role="agent", text=objective, priority="P1", - claimed_by=agent_id, task_class="advancement_task", action_kind="advance", - operation_id=f"{operation_id}:first-task", required_write_scopes=write_scope or None, - ) - if not todo.get("ok") or not todo.get("todo_id"): - raise RuntimeError("The goal was registered. Retry the same start request to recover its first task.") - todo_id = str(todo["todo_id"]) - resume = find_loopx_turn_key_by_instance( - runtime_root, goal_id=goal_id, agent_id=agent_id, turn_instance_id=operation_id, - ) - if resume: + if getattr(args, "retry_failed_turn", False): + goal = find_registry_goal(registry, goal_id) + if goal is None or goal.get("creation_operation_id") != operation_id or goal.get("repo") != str(project): + raise ValueError("No matching first Turn. Use the original start-goal --execute request.") + resume = find_loopx_turn_key_by_instance( + runtime_root, goal_id=goal_id, agent_id=agent_id, turn_instance_id=operation_id, + ) + if resume is None: + raise ValueError("No saved first Turn. Use the original command without --retry-failed-turn.") + inspection = inspect_loopx_turn_journal( + runtime_root, goal_id=goal_id, agent_id=agent_id, turn_key=resume, retry_failed=True, + ) + recovery = inspection["recovery_decision"] + if not isinstance(recovery, dict) or recovery.get("action") not in {"continue", "return_existing"}: + reason = recovery.get("reason") if isinstance(recovery, dict) else "recovery_decision_unavailable" + raise ValueError(f"The saved first Turn could not be resumed ({reason}).") + if recovery.get("reinvoke_host") is not False: + raise ValueError("This recovery would rerun the worker. The saved-result retry does not permit that.") + plan = load_loopx_turn_plan_from_journal(runtime_root, goal_id=goal_id, agent_id=agent_id, turn_key=resume) + selected_todo = plan["route"].get("selected_todo") or {} + todo_id = selected_todo.get("todo_id") + if not todo_id: + raise ValueError("The saved first Turn has no selected task.") turn_args.resume_turn_key = resume + turn_args.retry_failed_turn = True else: - claimed = update_goal_todo( + _register_first_goal( + registry_path=registry_path, runtime_root=runtime_root, project=project, + goal_id=goal_id, agent_id=agent_id, objective=objective, + display_name=display_name, operation_id=operation_id, write_scope=write_scope, + ) + todo = add_goal_todo( registry_path=registry_path, runtime_root_arg=str(runtime_root), - goal_id=goal_id, todo_id=todo_id, claimed_by=agent_id, agent_id=agent_id, - claim_only=True, manage_execution=True, claim_operation_id=f"{operation_id}:first-claim", + goal_id=goal_id, role="agent", text=objective, priority="P1", + claimed_by=agent_id, task_class="advancement_task", action_kind="advance", + operation_id=f"{operation_id}:first-task", required_write_scopes=write_scope or None, ) - if not claimed.get("ok"): - raise RuntimeError(str(claimed.get("error") or "The first task could not be claimed")) - turn_args.todo_id = todo_id - turn_args.turn_instance_id = operation_id + if not todo.get("ok") or not todo.get("todo_id"): + raise RuntimeError("The goal was registered. Retry the same start request to recover its first task.") + todo_id = str(todo["todo_id"]) + resume = find_loopx_turn_key_by_instance( + runtime_root, goal_id=goal_id, agent_id=agent_id, turn_instance_id=operation_id, + ) + if resume: + turn_args.resume_turn_key = resume + else: + claimed = update_goal_todo( + registry_path=registry_path, runtime_root_arg=str(runtime_root), + goal_id=goal_id, todo_id=todo_id, claimed_by=agent_id, agent_id=agent_id, + claim_only=True, manage_execution=True, claim_operation_id=f"{operation_id}:first-claim", + ) + if not claimed.get("ok"): + raise RuntimeError(str(claimed.get("error") or "The first task could not be claimed")) + turn_args.todo_id = todo_id + turn_args.turn_instance_id = operation_id result: dict[str, Any] = {} handle_turn_command( turn_args, registry_path=registry_path, runtime_root_arg=str(runtime_root), output_format=lambda _args: "json", print_payload=lambda payload, *_: result.update(payload), ) + if ( + result.get("status") == "failed" + and result.get("validation_stage") == "task_postcondition" + and result.get("resume_turn_key") + ): + result["recommended_action"] = ( + "Once the independent checker is ready, repeat the original start-goal --execute command " + "with --retry-failed-turn to check the saved result without rerunning the worker." + ) return {**result, "goal_id": goal_id, "agent_id": agent_id, "todo_id": todo_id, "turn_instance_id": operation_id} @@ -213,7 +252,11 @@ def execute_managed_start( def render_managed_start_markdown(payload: dict[str, object]) -> str: kind = payload.get("result_kind") if payload.get("status") != "committed" or kind not in ("validated_completion", "validated_progress"): - return render_loopx_turn_execution_markdown(payload) + rendered = render_loopx_turn_execution_markdown(payload) + action, key = payload.get("recommended_action"), payload.get("resume_turn_key") + if isinstance(action, str) and isinstance(key, str): + return f"{rendered}\n\nTurn key: {key}\n{action}" + return rendered line = ( "Task completed and checked." if kind == "validated_completion" diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index 22abd88b24..2310620edf 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -55,6 +55,11 @@ adapter and check commands on Windows it checks absolute paths. Correct an unavailable program in the launch configuration and repeat the same goal. Repeat the original invocation after an interruption, including during registration. It continues the saved attempt or returns the checked result. +If the worker finished but the independent check did not pass, the command +retains the worker's result and reports the original Turn key. Once the checker +is ready, repeat the same command with `--retry-failed-turn`. This continues +checking and settling the original Turn without rerunning the worker or +registering new work. Repeating a completed retry returns the existing receipt. The `--guided` route remains available for an existing project or an interactive host. diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index 7303d16006..c4bf113a13 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -1017,6 +1017,78 @@ def _configure_first_goal_storage(core_python, project, runtime, provider): assert configured.returncode == 0, configured.stderr +@pytest.mark.skipif(os.name != "posix", reason="uses a stand-alone executable checker") +@pytest.mark.parametrize("provider", ["sqlite", "file"]) +def test_installed_core_retries_saved_first_turn(core_python, tmp_path, monkeypatch, provider): + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + + isolate_sqlite_runtime(tmp_path, monkeypatch) + project = tmp_path / "first-work" + project.mkdir() + runtime = project / ".loopx/runtime" + registry = project / ".loopx/registry.json" + check = tmp_path / "independent-check" + index = runtime / "goals/first-work-goal/runs/index.jsonl" + checker_source = VALIDATOR_SOURCE.replace("json.load(sys.stdin)", + "json.load(sys.stdin)\nwith pathlib.Path('checker-invocations').open('a') as f:f.write('checked\\n')") + check.write_text(f"#!{core_python}\n{checker_source}") + check.chmod(0o700) + parts = HOST_SOURCE.split("json.dump({", 1) + adapter = f"{parts[0]}pathlib.Path({str(check)!r}).unlink()\njson.dump({{{parts[1]}" + arguments = ["--format", "json", "start-goal", "--project", str(project), + "--goal-text", "Produce and independently check the first report.", "--execute", + "--host-adapter-command-json", json.dumps([core_python, "-I", "-c", adapter]), + "--validation-command-json", json.dumps([str(check)])] + retry = [*arguments, "--retry-failed-turn"] + + def run(argv, expected=0): + return json.loads(_run(core_python, argv, project, expected=expected).stdout) + + refused = run(retry, expected=1) + assert "No matching first Turn" in refused["error"] + assert not list(project.iterdir()) + if provider == "file": + _configure_first_goal_storage(core_python, project, runtime, provider) + first = run(arguments, expected=1) + key, todo_id = first["resume_turn_key"], first["todo_id"] + assert first["validation"]["status"] == "inconclusive" + assert first["effects"]["host_invoked"] and not first["effects"]["quota_spent"] + assert "--retry-failed-turn" in first["recommended_action"] + assert not (project / "checker-invocations").exists() + assert not index.exists() or "quota_slot_spent" not in index.read_text() + original_checker = f"#!{core_python}\n{checker_source}" + check.write_text(original_checker) + check.chmod(0o700) + markdown = _run(core_python, ["--format", "markdown", *arguments[2:]], project, expected=1).stdout + assert key in markdown and "with --retry-failed-turn" in markdown + plain = run(arguments, expected=1) + assert plain["replayed"] and not any(plain["effects"].values()) + assert not (project / "checker-invocations").exists() + + changed = list(retry) + changed[changed.index("--validation-command-json") + 1] = json.dumps([str(check), "different-command"]) + refused = run(changed, expected=1) + assert "No matching first Turn" in refused["error"] + assert not (project / "checker-invocations").exists() + before_registry = registry.read_bytes() + recovered = run(retry) + assert recovered["status"] == "committed" and recovered["validation"]["status"] == "passed" + assert recovered["resume_turn_key"] == key and recovered["todo_id"] == todo_id + assert recovered["turn_instance_id"] == first["turn_instance_id"] + assert recovered["effects"]["quota_spent"] and not recovered["effects"]["host_invoked"] + readback = run(["--registry", str(registry), "--format", "json", + "todo", "list", "--goal-id", first["goal_id"], "--todo-id", todo_id]) + assert readback["todo"]["status"] == "done" + assert readback["authority_read"]["source_authority"] == f"{provider}_v0" + replay = run(retry) + assert replay["replayed"] and not any(replay["effects"].values()) + assert replay["todo_id"] == todo_id and replay["resume_turn_key"] == key + assert registry.read_bytes() == before_registry + assert (project / "host-invocations").read_text().splitlines() == ["called"] + assert (project / "checker-invocations").read_text().splitlines() == ["checked"] + assert index.read_text().count("quota_slot_spent") == 1 + + @pytest.mark.skipif(os.name != "posix", reason="requires POSIX SIGKILL") @pytest.mark.parametrize("provider", ["sqlite", "file"]) @pytest.mark.parametrize("phase", ["registration", "initial-source"])