diff --git a/docs/reference/protocols/turn-envelope-v0.md b/docs/reference/protocols/turn-envelope-v0.md index a325346986..f64b42a9bf 100644 --- a/docs/reference/protocols/turn-envelope-v0.md +++ b/docs/reference/protocols/turn-envelope-v0.md @@ -482,10 +482,17 @@ and are published atomically with owner-only file permissions without replacing an existing observation. They can contain private Goal context and must not be included in public logs or artifacts. -Host retry validates and reuses the original journal's capture even if current -source text changes. Reading detail does not invoke quota or spend a slot. -Current source admission, cancellation, workspace/lease and mutation checks -retain their existing owners; the observation grants no fresh authority. +Host retry validates and reuses the original journal's capture. Before native +Codex or an external stdio Host launches with a verified selected Todo, the +current complete contract must still match the original task body, required write scopes and +required capabilities. Progress notes do not invalidate that work. A mismatch +returns `current_turn_work_changed` before dispatching the model. For stdio, +the shared process supervisor holds the launch guard through spawn. The +journal records the refused attempt and its original capture remains readable. +Use a fresh eligible Turn for the changed task. Keep original captures and receipts for +readback. Reading detail does not invoke quota or spend a slot. Current source +admission, cancellation, workspace/lease and mutation checks retain their +existing owners; the observation grants no fresh authority. Missing, corrupt, wrong-identity or source-hash-mismatched captures refuse Host reinvocation. Restore the original evidence rather than reconstructing it from a new guard. A capture published before a journal write failure is retained; @@ -507,6 +514,11 @@ blocks resume. Journal inspection can report the invalid work contract without performing recovery or a debit. Retain the historical reader until the last supported journal and its recovery window are reconciled. +原生 Codex 和外部 stdio Host 启动前会用当前完整契约复核所选 Todo 的已验证正文、 +所需写入范围和能力。只改进度备注可以继续。改变工作声明会在模型调用前返回 +`current_turn_work_changed`。stdio 进程由共用的进程管理器在准入锁内启动。 +journal 记录已拒绝的尝试。变更后的工作使用新的合格 Turn,原捕获与回执仍可读回。 + 恢复预览和 journal 解释共用同一个 typed plan reader。受支持的历史记录保留原版本和 字节。显式声明不支持的 plan、envelope 或动作签名版本及覆盖范围时,恢复会停止。 检查入口仍可报告契约无效,不执行恢复或扣额。保留历史读取器,直到最后一份受支持的 diff --git a/loopx/cli_commands/turn_decision.py b/loopx/cli_commands/turn_decision.py index 1c36db7f4f..edc067f02b 100644 --- a/loopx/cli_commands/turn_decision.py +++ b/loopx/cli_commands/turn_decision.py @@ -358,6 +358,7 @@ def current_turn_host_launch_decision( args: argparse.Namespace, *, registry_path: Path, runtime_root: Path, identity: SettlementIdentity, planned_effective_action: object, + planned_selected_work_basis: str | None, scheduler_execution_context: Mapping[str, Any], operator_inbox_urgency_projector: Callable[..., dict[str, Any]], turn_start_hook_dispatch: Mapping[str, Any] | None = None, @@ -416,7 +417,7 @@ def current_turn_host_launch_decision( plan = build_loopx_turn_plan( current_contract, host=args.host, execution_mode=args.execution_mode, scheduler_owner=args.scheduler_owner, turn_instance_id=identity.turn_instance_id, - goal_ref=goal_ref, + goal_ref=goal_ref, include_selected_work_basis=planned_selected_work_basis is not None, ) route = plan["route"] if route.get("would_invoke_host") is not True: @@ -425,6 +426,8 @@ def current_turn_host_launch_decision( raise FirstPartyHostRuntimeRejected("current_turn_selection_changed") if (identity.replan_obligation_id or identity.request_subject is not None) and plan["transaction"]["settlement_plan"]["identity"] != identity.as_dict(): raise FirstPartyHostRuntimeRejected("current_turn_selection_changed") + if planned_selected_work_basis is not None and plan.get("_selected_work_basis") != planned_selected_work_basis: + raise FirstPartyHostRuntimeRejected("current_turn_work_changed") return launch diff --git a/loopx/cli_commands/turn_run_once.py b/loopx/cli_commands/turn_run_once.py index 9cbf8136d9..fa28ea033e 100644 --- a/loopx/cli_commands/turn_run_once.py +++ b/loopx/cli_commands/turn_run_once.py @@ -1,6 +1,7 @@ from __future__ import annotations import argparse +from functools import partial import sys as _sys from collections.abc import Callable, Mapping from pathlib import Path @@ -767,18 +768,24 @@ def scheduler(_spend_payload: dict[str, object]) -> dict[str, object]: host_runner: Callable[[Mapping[str, Any]], dict[str, Any]] | None = None session_binding_resolver = None - if args.host == "codex-app-server": - def native_launch_decision(current_registry: Path) -> Mapping[str, Any]: - return current_turn_host_launch_decision(args, registry_path=current_registry, - runtime_root=runtime_root, identity=settlement_identity, - planned_effective_action=execution_context["effective_action"], - scheduler_execution_context=payload.get("scheduler_execution_context") or {}, - operator_inbox_urgency_projector=operator_inbox_urgency_projector, - turn_start_hook_dispatch=turn_start_hook_dispatch, goal_ref=goal_ref) + def current_launch_decision(current_registry: Path) -> Mapping[str, Any]: + # Native and stdio transports recheck the original work at launch. + # A global route checks its source even if the mirror is unchanged. + return current_turn_host_launch_decision( + args, registry_path=current_registry, runtime_root=runtime_root, + identity=settlement_identity, + planned_effective_action=execution_context["effective_action"], + planned_selected_work_basis=execution_context.get("selected_work_basis"), + scheduler_execution_context=payload.get("scheduler_execution_context") or {}, + operator_inbox_urgency_projector=operator_inbox_urgency_projector, + turn_start_hook_dispatch=turn_start_hook_dispatch, goal_ref=goal_ref, + ) + + if args.host == "codex-app-server": native_admission = (goal_admission or FirstPartyHostGoalAdmission.for_plan( registry_path=registry_path, goal_id=args.goal_id, planned_goal_ref=goal_ref, - )).with_launch_decision(native_launch_decision) + )).with_launch_decision(current_launch_decision) def run_native_host(request: Mapping[str, Any]) -> dict[str, Any]: return native_host_runner(request, lambda: native_admission.launch_lifetime( @@ -787,22 +794,6 @@ def run_native_host(request: Mapping[str, Any]) -> dict[str, Any]: host_runner = run_native_host session_binding_resolver = native_session_binding_resolver elif args.host == "codex-cli": - - def current_launch_decision(current_registry: Path) -> Mapping[str, Any]: - # Revalidate the already admitted identity through the same - # owner. In a global route the source is checked first, even - # when its mirror still advertises old quota or health. - return current_turn_host_launch_decision( - args, registry_path=current_registry, runtime_root=runtime_root, - identity=settlement_identity, - planned_effective_action=execution_context["effective_action"], - scheduler_execution_context=payload.get("scheduler_execution_context") or {}, - operator_inbox_urgency_projector=operator_inbox_urgency_projector, - # Keep this Turn's already dispatched required reads at launch. - turn_start_hook_dispatch=turn_start_hook_dispatch, - goal_ref=goal_ref, - ) - host_runner = build_codex_cli_host_runner( args, runtime_root=runtime_root, project=project, registry_path=registry_path, goal_ref=goal_ref, @@ -924,6 +915,10 @@ def on_managed_start_admitted() -> None: admit_start=managed_cadence.admit if args.execute else None, confirm_start=managed_cadence.confirm if args.execute else None, goal_admission=goal_admission, + host_launch_guard=(partial( + goal_admission.with_launch_decision(current_launch_decision).launch_lifetime, + operation="turn_external_host_launch", + ) if raw_argv is not None and goal_admission is not None else None), ) if args.execute: result.update(drain_committed_turn_post_writeback_hooks( diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 71b56c8eab..7d5bdc2f3a 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -1957,6 +1957,7 @@ export function completePlanningFacts(request: JsonObject): JsonObject { return {...lineage, work, source_decision_hash: decisionSourceHash(decision), action_source_hash: canonicalHash(turnEnvelopeActionSignatureDocument(work)), scoped_settlement_identity: scopedIdentity, scoped_identity_error: identityError, + ...(request.include_selected_work_basis === true ? {selected_work_basis: selectedWorkLaunchBasis(decision)} : {}), ...(request.inspect_plan === true && (lineage.route === "ready_for_host" || lineage.route === "replan_required") ? {inspection_paths: turnPlanInspectionPaths(decision, lineage.route)} : {})}; @@ -2010,6 +2011,19 @@ function completeTaskTextSha256(decision: JsonObject, todoId: unknown): string | return capturedTodoTextSha256(declared, context, decision.recommended_action, todoId); } +/** Launch rechecks the admitted task, not the provider revision or the bounded + * action signature. Progress, diagnostics and receipt changes are not edits to + * the work. Losing the verified body on a fresh read is not a match. */ +function selectedWorkLaunchBasis(decision: JsonObject, verifiedTextSha256?: string | null): string | null { + const todoId = selectedWorkTodoId(decision); + const selected = object(decision.selected_todo); + if (!todoId || todoId !== selected.todo_id) return null; + const textSha256 = verifiedTextSha256 === undefined ? completeTaskTextSha256(decision, todoId) : verifiedTextSha256; + return textSha256 === null ? null : canonicalHash({todo_id: todoId, text_sha256: textSha256, + required_write_scopes: selected.required_write_scopes ?? [], + required_capabilities: selected.required_capabilities ?? []}); +} + export function composeCompleteTurnDecision(value: unknown): JsonObject { const request = requireJsonObject(value, "complete Turn decision request"); const payload = requireJsonObject(request.payload, "complete Turn decision source"); @@ -2655,8 +2669,9 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject { const {decision, projection} = completeHostSource(request); const work = {selected_todo: object(projection.action).selected_todo, task_orchestration_contract: projection.task_orchestration_contract}; - return {selected_todo: selectedWorkTodo(work), - sha256: completeTaskTextSha256(decision, selectedWorkTodoId(work) ?? ""), + const sha256 = completeTaskTextSha256(decision, selectedWorkTodoId(work) ?? ""); + return {selected_todo: selectedWorkTodo(work), sha256, + selected_work_basis: selectedWorkLaunchBasis(decision, sha256), effective_action: decision.effective_action ?? null, writeback: object(projection.writeback), task_lease_proof: object(object(decision.execution_preparation).lease_proof), diff --git a/loopx/control_plane/turn_driver/driver.py b/loopx/control_plane/turn_driver/driver.py index 375a73ccff..5594207935 100644 --- a/loopx/control_plane/turn_driver/driver.py +++ b/loopx/control_plane/turn_driver/driver.py @@ -418,6 +418,21 @@ def _bind_host_child_operations( return bound +def _complete_plan_source_fields( + work_contract: object, projection: Mapping[str, Any], original_envelope: Mapping[str, Any] | None, +) -> dict[str, Any]: + fields = {"work_contract": work_contract, "source_decision_hash": projection["source_decision_hash"]} + for key in ("inspection_paths", "selected_work_basis"): + if key in projection: + fields[f"_{key}"] = projection[key] + if original_envelope is not None: + # Carry the reader of the original capture from a transitional pair. + header = captured_turn_host_input({"turn_envelope": original_envelope}) + if "detail_ref" in header: + fields["detail_ref"] = header["detail_ref"] + return fields + + def build_loopx_turn_plan( turn_envelope: Mapping[str, Any], *, @@ -431,6 +446,7 @@ def build_loopx_turn_plan( goal_ref: Mapping[str, object] | None = None, work_contract: object = _ABSENT_WORK_CONTRACT, inspect_plan: bool = False, + include_selected_work_basis: bool = False, ) -> dict[str, Any]: """Plan from one complete source; retain the recorded v0 input codec. @@ -483,6 +499,7 @@ def build_loopx_turn_plan( projection = _turn_envelope_result("planning_facts", payload=work_contract, turn_instance_id=turn_instance_id, **({"inspect_plan": True} if inspect_plan else {}), + **({"include_selected_work_basis": True} if include_selected_work_basis else {}), **({} if source_only_input else {"envelope": supplied})) envelope = _mapping(projection["work"]) else: @@ -609,16 +626,9 @@ def build_loopx_turn_plan( ), } if current: - payload["work_contract"] = work_contract - payload["source_decision_hash"] = projection["source_decision_hash"] - if "inspection_paths" in projection: - payload["_inspection_paths"] = projection["inspection_paths"] - if not source_only_input: - # Older callers may already carry an original quota capture. Keep - # its exact header without retaining that caller's second source. - header = captured_turn_host_input({"turn_envelope": supplied}) - if "detail_ref" in header: - payload["detail_ref"] = header["detail_ref"] + payload.update(_complete_plan_source_fields( + work_contract, projection, None if source_only_input else supplied, + )) else: payload["turn_envelope"] = envelope if child_operations: diff --git a/loopx/control_plane/turn_driver/executor.py b/loopx/control_plane/turn_driver/executor.py index 27ba70f20b..73675259e1 100644 --- a/loopx/control_plane/turn_driver/executor.py +++ b/loopx/control_plane/turn_driver/executor.py @@ -877,6 +877,7 @@ def _run_host( argv: Sequence[str], project: Path, timeout_seconds: float | None, + launch_guard: Callable[[], AbstractContextManager[None]] | None = None, ) -> dict[str, Any]: # Dispatch has checked the source and its internal effect adapter before # journal/cadence admission. External stdin gets the same single complete @@ -900,7 +901,10 @@ def count_stderr(text: str) -> None: stdout_limit_bytes=HOST_RESULT_MAX_BYTES, on_stdout=stdout.append, on_stderr=count_stderr, + launch_guard=launch_guard, ) + except FirstPartyHostRuntimeRejected: + raise except (OSError, RuntimeError, ValueError) as exc: return {"ok": False, "reason": type(exc).__name__, "returncode": None} if observed["outcome"] == "output_limit": @@ -1011,6 +1015,7 @@ def _host_result_stage( confirm_start: Callable[[], None] | None = None, usage_runtime_root: Path | None = None, usage_goal_id: str = "", + host_launch_guard: Callable[[], AbstractContextManager[None]] | None = None, ) -> tuple[dict[str, Any] | None, list[str], dict[str, Any] | None]: completed_phases = list(journal.get("completed_phases") or []) from_journal = "typed_result" in completed_phases @@ -1033,22 +1038,32 @@ def _host_result_stage( confirm_start() from ...usage_goal import observe_goal_execution - with observe_goal_execution( - usage_runtime_root or project, - usage_goal_id, - host=str((plan.get("host") or {}).get("kind") or "unknown"), - ): - host_observation = ( - _run_host_runner(request, runner=host_runner) - if host_runner is not None - else _run_host( - request, - argv=argv or [], - project=project, - timeout_seconds=timeout_seconds, + rejected_launch = None + try: + with observe_goal_execution( + usage_runtime_root or project, + usage_goal_id, + host=str((plan.get("host") or {}).get("kind") or "unknown"), + ): + host_observation = ( + _run_host_runner(request, runner=host_runner) + if host_runner is not None + else _run_host( + request, + argv=argv or [], + project=project, + timeout_seconds=timeout_seconds, + launch_guard=host_launch_guard, + ) ) - ) - effects["host_invoked"] = True + except FirstPartyHostRuntimeRejected as exc: + # Stdio checks the Goal only before spawn. A native Host can reject + # after dispatch too, so retain reconciliation for other failures. + if host_runner is not None and exc.code != "current_turn_work_changed": + raise + rejected_launch = exc.code + host_observation = {"ok": False, "reason": str(exc), "failure_kind": "contract_rejected"} + effects["host_invoked"] = rejected_launch is None if not host_observation.get("ok"): failure = _host_failure( plan, @@ -1074,17 +1089,10 @@ def _host_result_stage( else: journal.pop("host_recovery", None) persist_journal(journal) - return ( - None, - [], - execution_payload( - plan, - journal, - execute=True, - replayed=False, - effects=effects, - ), - ) + terminal = execution_payload(plan, journal, execute=True, replayed=False, effects=effects) + if rejected_launch is not None: + terminal["error_code"] = rejected_launch + return None, [], terminal result = dict(host_observation["value"]) completed_phases = list(TRANSACTION_PHASES[:2]) @@ -1575,6 +1583,7 @@ def run_loopx_turn_once( admit_start: Callable[[Mapping[str, Any]], dict[str, Any]] | None = None, confirm_start: Callable[[], None] | None = None, goal_admission: FirstPartyHostGoalAdmission | None = None, + host_launch_guard: Callable[[], AbstractContextManager[None]] | None = None, ) -> dict[str, Any]: argv, host_projection = _prepare_host_invocation(plan, host_argv=host_argv, host_runner=host_runner) transaction_plan = ( @@ -1846,6 +1855,7 @@ def finish_recovery(payload: dict[str, Any]) -> dict[str, Any]: persist_journal=persist_journal, effects=effects, confirm_start=confirm_start if reserved_start else None, + host_launch_guard=host_launch_guard, ) if terminal is not None: return finish_recovery(terminal) diff --git a/tests/control_plane/test_host_current_admission.py b/tests/control_plane/test_host_current_admission.py index 3fb995e6d1..f3819ec0e2 100644 --- a/tests/control_plane/test_host_current_admission.py +++ b/tests/control_plane/test_host_current_admission.py @@ -3,6 +3,7 @@ import json from pathlib import Path +import sys import pytest @@ -94,3 +95,128 @@ def lose_state_before_start(**kwargs): assert not state.exists() index = runtime / "goals/loopx-turn-fixture/runs/index.jsonl" assert not index.exists() or "quota_slot_spent" not in index.read_text() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("change", ["task_text", "write_scope", "progress_note"]) +@pytest.mark.parametrize("host", ["exec", "operation"]) +def test_native_launch_rechecks_same_todo_after_planning( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, change: str, host: str, +) -> None: + runtime, registry, native, model, arguments = _fixture(tmp_path, monkeypatch, provider) + project = registry.parent.parent + if host == "exec": + executable, model = _fake_codex(tmp_path) + executable.write_text(executable.read_text().replace( + "args = sys.argv[1:]", f"pathlib.Path({str(native)!r}).write_text('native')\nargs = sys.argv[1:]", 1, + )) + monkeypatch.setenv("FAKE_CODEX_LOG", str(model)) + arguments.remove("--codex-operation-tools") + arguments[arguments.index("--codex-bin") + 1] = str(executable) + old = _quota(registry, runtime, project) + assert old["should_run"] is True, old + todo_id = old["selected_todo"]["todo_id"] + mutation = { + "task_text": ["--text", "[P0] Verify the replacement fixture before any work."], + "write_scope": ["--required-write-scope", "docs/evidence/**"], + "progress_note": ["--note", "Independent observation received."], + }[change] + host_module = codex_cli if host == "exec" else codex_operation_host + original_input = host_module.prepare_codex_cli_input + readbacks = [] + + def edit_after_planning(request): + code, result = _cli([ + "--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", + "todo", "update", "--goal-id", "loopx-turn-fixture", "--agent-id", "codex-fixture", + "--todo-id", todo_id, *mutation, + ]) + assert code == 0 and result["ok"], result + current = _quota(registry, runtime, project) + assert current["should_run"] is True and current["effective_action"] == old["effective_action"], current + assert current["selected_todo"]["todo_id"] == todo_id + readbacks.append((result, _bindings(runtime))) + return original_input(request) + + monkeypatch.setattr(host_module, "prepare_codex_cli_input", edit_after_planning) + code, payload = _cli([*arguments, "--execute"]) + assert len(readbacks) == 1 + if change == "progress_note": + assert native.exists() and model.exists(), payload + else: + # Operation mode already started app-server; it must not start a + # model Turn or publish its Session binding on the stale request. + assert native.exists() is (host == "operation") and not model.exists(), payload + assert code == 1 and "current_turn_work_changed" in json.dumps(payload), payload + assert _bindings(runtime) == readbacks[0][1] + index = runtime / "goals/loopx-turn-fixture/runs/index.jsonl" + assert not index.exists() or "quota_slot_spent" not in index.read_text() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("edit_task", [False, True]) +def test_stdio_retry_checks_original_task_before_launch(tmp_path, monkeypatch, provider, edit_task): + from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection + from loopx.control_plane.todos.active_state_todo_parser import parse_active_state_todos + from tests.control_plane.canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + from tests.control_plane.test_turn_host_decision_capture import _fixture_module + + isolate_sqlite_runtime(tmp_path, monkeypatch) + fixture = _fixture_module() + project, runtime, workspace, registry = fixture._write_fixture(tmp_path, turn_count=2) + state = project / ".codex/goals" / fixture.GOAL_ID / "ACTIVE_GOAL_STATE.md" + todos = parse_active_state_todos(state.read_text(), state_path=state, item_limit=None) + initialize_canonical_authority(runtime, fixture.GOAL_ID, + build_todo_runtime_shadow_projection(goal_id=fixture.GOAL_ID, handoff_mode="soft_claim", + todos=todos["agent_todos"]["items"]), state_path=state, provider=provider) + marker = workspace / "process-count" + runner = tmp_path / "runner.py" + runner.write_text(f'''import json +from pathlib import Path + +def run_dsh_turn(**options): + workspace = Path(options["workspace"]) + marker = workspace / "process-count" + first = not marker.exists() + marker.write_text("1" if first else "2") + if first: + raise TimeoutError("Fixture failed before producing a result") + (workspace / {fixture.MARKER_NAME!r}).write_text({fixture._marker_value(1)!r}) + return json.dumps({{"result_kind": "validated_progress", "classification": "checked_work", + "summary": "The original work passed independent validation.", "next_action": "Continue.", + "work_evidence": ["artifact:marker"], "validation_evidence": ["fixture:validate-marker"]}}) +''', encoding="utf-8") + prefix = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + subject = ["--goal-id", fixture.GOAL_ID, "--agent-id", fixture.AGENT_ID] + adapter = [sys.executable, "-m", "loopx.dsh_goal_mode", "--workspace", str(workspace), + "--dsh-runner", str(runner), "--dsh-home", str(tmp_path / "dsh-home")] + validator = [sys.executable, "-c", "from pathlib import Path; import json,sys; json.load(sys.stdin); " + f"assert Path({fixture.MARKER_NAME!r}).read_text() == {fixture._marker_value(1)!r}"] + argv = [*prefix, "turn", "run-once", *subject, "--host", "generic-cli", "--project", str(workspace), + "--execution-mode", "isolated-headless", "--no-global-sync", "--timeout-seconds", "20", + "--host-adapter-request-schema", "loopx_turn_host_request_v1", + "--host-adapter-command-json", json.dumps(adapter), + "--validation-command-json", json.dumps(validator), "--execute"] + code, first = fixture._run_cli([*argv, "--turn-instance-id", "bound-stdio-retry"]) + assert code == 1 and first["status"] == "failed", first + assert marker.read_text() == "1" and fixture._quota_spend_count(runtime) == 0 + if edit_task: + binding = [*subject, "--todo-id", fixture.TODO_ID] + code, before = fixture._run_cli([*prefix, "todo", "list", *binding]) + assert code == 0 + code, changed = fixture._run_cli([*prefix, "todo", "update", *binding, "--execute", + "--text", before["todo"]["text"] + " Follow the replacement requirement.", + "--update-operation-id", "change-captured-work", + "--update-expected-provider-revision", before["authority_read"]["provider_revision"]]) + assert code == 0 and changed["changed"], changed + recovery = [*argv, "--resume-turn-key", first["resume_turn_key"]] + code, result = fixture._run_cli([*recovery, "--retry-failed-turn"]) + if edit_task: + assert code == 1 and result["error_code"] == "current_turn_work_changed", result + assert not any(result["effects"].values()) + else: + assert code == 0 and result["status"] == "committed", result + _, replay = fixture._run_cli(recovery) + assert replay["replayed"] and not any(replay["effects"].values()) + assert marker.read_text() == ("1" if edit_task else "2") + assert fixture._quota_spend_count(runtime) == (0 if edit_task else 1) diff --git a/tests/test_native_steward_turn_host.py b/tests/test_native_steward_turn_host.py index 4d0deb96d6..3c11caab85 100644 --- a/tests/test_native_steward_turn_host.py +++ b/tests/test_native_steward_turn_host.py @@ -940,6 +940,41 @@ def test_native_turn_uses_original_app_server_and_kernel_without_a_new_session(s assert capture.read_bytes() == calls +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_managed_task_edit_after_planning_does_not_start_native_turn(steward, tmp_path, monkeypatch, provider): + from loopx.cli_commands import turn_run_once + + service, session, actor, todo_id, _, capture = managed_fixture(steward, tmp_path, monkeypatch, provider) + store, runtime, *_ = steward + original_request = turn_run_once.prepare_turn_host_request + revised = "[P1] Check the corrected readiness condition before continuing." + edits = [] + + def edit_after_planning(*args, **kwargs): + prepared = original_request(*args, **kwargs) + assert args[0].host == "codex-app-server" + edits.append(cli(runtime, "todo", "update", "--goal-id", actor["goal_id"], + "--todo-id", todo_id, "--agent-id", actor["agent_id"], "--text", revised)) + return prepared + + monkeypatch.setattr(turn_run_once, "prepare_turn_host_request", edit_after_planning) + before = capture.read_bytes() + accepted, created = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="changed-task-before-native-launch", todo_id=todo_id) + assert created + completed = runtime.wait_for_turn(session_id=accepted["session_id"], turn_id=accepted["turn_id"], timeout_sec=90) + result = completed["response"]["native_loopx"] + assert len(edits) == 1 and edits[0]["ok"] + assert not result["ok"] and "current_turn_work_changed" in json.dumps(result), result + calls = [json.loads(line) for line in capture.read_bytes()[len(before):].splitlines()] + assert all(row["method"] != "turn/start" for row in calls) + assert store.load_session(session["session_id"])["upstream_thread_id"] == session["upstream_thread_id"] + current = cli(runtime, "todo", "list", "--goal-id", actor["goal_id"], "--todo-id", todo_id)["todo"] + assert current["text"] == revised and not current["done"] + index = Path(runtime.coordination_runtime_root) / "goals" / actor["goal_id"] / "runs/index.jsonl" + assert not index.exists() or "quota_slot_spent" not in index.read_text() + + def test_unselected_or_unavailable_work_does_not_invoke_the_model(steward, tmp_path, monkeypatch): sid, actor, _ = prepare(steward, "sqlite", tmp_path, monkeypatch) store, runtime, _, _, binding, capture, _ = steward