diff --git a/loopx/control_plane/work_items/interaction_contract.py b/loopx/control_plane/work_items/interaction_contract.py index 73070b5732..cc5b796103 100644 --- a/loopx/control_plane/work_items/interaction_contract.py +++ b/loopx/control_plane/work_items/interaction_contract.py @@ -13,6 +13,8 @@ import typing from collections.abc import Collection, Mapping +from ...install_contract import render_host_cli_command + from ..agents.agent_scope_frontier import AgentScopeFrontierAction, agent_scope_frontier_action as _agent_scope_frontier_action from ..agents.capability_gate import runtime_capabilities_for_cli_projection from ..agents.workspace_guard import delivery_workspace_refresh_hint @@ -633,7 +635,7 @@ def _selection_recovery_command( def _render_replan_successor_closeout_guard( *, settlement_plan: Mapping[str, Any] | None, - scheduler_args: str, typed_quota_guard: str, settlement_args: str, + scheduler_args: str, typed_quota_guard: str, ) -> str | None: """Render this host's guard for an existing TS-owned pure replan identity.""" if not scheduler_args or not settlement_plan: @@ -642,7 +644,11 @@ def _render_replan_successor_closeout_guard( if not isinstance(identity, Mapping) or identity.get("binding_kind") != "autonomous_replan": # Todo-bound replans retain their distinct closeout path. return None - return typed_quota_guard + settlement_args + # The receipt recovers the obligation; should-run accepts only its Turn. + return render_host_cli_command([ + *shlex.split(typed_quota_guard), + "--turn-instance-id", str(identity["turn_instance_id"]), + ]) def _deferred_resume_continuation( @@ -1019,7 +1025,7 @@ def _admitted_interaction_next_cli_actions( ), successor_closeout_guard=_render_replan_successor_closeout_guard( settlement_plan=settlement_plan, scheduler_args=scheduler_args, - typed_quota_guard=typed_quota_guard, settlement_args=settlement_args, + typed_quota_guard=typed_quota_guard, ), ) return _terminal_cli_actions( diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts index 748e4ca126..bd9985f80c 100644 --- a/loopx/control_plane/work_items/replan_semantics.ts +++ b/loopx/control_plane/work_items/replan_semantics.ts @@ -574,6 +574,19 @@ export function projectReplanSemantics(value: unknown): JsonObject { if (request.operation === "requirements") { const strideControl = strideControlContract(object(obligation.replan_context), obligation.obligation_id); const writeback = writebackProjection(required, externalReview, strideControl !== null); + if (required.includes("coverage_backed_no_followup")) { + writeback.writeback_contract = {...object(writeback.writeback_contract), + no_followup_requirements: { + cli_args: ["--progress-result-class", "no_followup", "--progress-coverage-scope-id", "", + "--progress-evidence-id", "", + "--agent-vision-json", ""], + vision_fields: {state: "no_followup", "path_delta.outcome": "stop"}, + preserve: ["vision_patch"], + rule: "Use verified scope coverage and the vision_authoring path_delta fields with evidence_refs. " + + "Retain the current complete vision_patch: changing durable fields requires outcome=replan and cannot be combined with stop. " + + "Write back and spend with the original settlement_plan identity, not a later obligation.", + }}; + } if (requiresStrideDecision(obligation)) { const contract = object(writeback.writeback_contract); writeback.cli_semantic_args = VISION_CLI_ARGS; diff --git a/tests/control_plane/test_replan_successor_guard_reentry.py b/tests/control_plane/test_replan_successor_guard_reentry.py index fd5586492a..48508cd15a 100644 --- a/tests/control_plane/test_replan_successor_guard_reentry.py +++ b/tests/control_plane/test_replan_successor_guard_reentry.py @@ -2,7 +2,9 @@ from __future__ import annotations import json +import os import shlex +import shutil import subprocess import sys from pathlib import Path @@ -107,6 +109,124 @@ def _add(call, obligation_id: str): "--operation-id", "periodic-source-successor", "--replan-obligation-id", obligation_id) +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_projected_successor_closeout_guard_executes_original_turn(tmp_path, monkeypatch, provider): + from loopx.command_invocation import loopx_cli_route + from loopx.control_plane.scheduler.execution_context import scheduler_execution_context_for_runtime_profile + from loopx.control_plane.work_items.interaction_contract import interaction_next_cli_actions + from loopx.control_plane.work_items.progress_observation import build_replan_action_packet + + call, _, _ = _fixture(tmp_path, monkeypatch, provider) + original = _guard(call) + identity = original["heartbeat_receipt"]["settlement_identity"] + # Exercise the existing bounded-research successor projection over a real guard. + original["replan_action_packet"] = build_replan_action_packet( + original["autonomous_replan_obligation"], goal_id=GOAL, agent_id=AGENT, + bounded_research_frontier={"selected_gap": { + "successor_summary": "Independently verify the source artifact", + "successor_binding": {"action_kind": "validate", "target_key": "independent-source-artifact"}, + }}, + ) + cli = Path(sys.executable).parent / ("loopx.exe" if os.name == "nt" else "loopx") + with loopx_cli_route(str(cli)): + actions = interaction_next_cli_actions( + original, mode="autonomous_replan", capability_reentry_resolved=True, + settlement_plan=original["interaction_contract"]["cli_channel"]["settlement_plan"], + scheduler_execution_context=scheduler_execution_context_for_runtime_profile("codex_app_heartbeat"), + runtime_root=original["runtime_root"], registry_path=str(tmp_path / "registry.json"), + turn_instance_id=TURN, + ) + command = actions[1] + tokens = shlex.split(command) + if os.name == "nt": + assert tokens.pop(0) == "&" + _add(call, identity["replan_obligation_id"]) + result = subprocess.run( + [*tokens, "--context-delivery", "off"], + capture_output=True, text=True, timeout=60, + ) + reread = json.loads(result.stdout) + assert result.returncode == 0, reread.get("error") or reread.get("reason") or reread + assert reread["heartbeat_receipt"]["settlement_identity"] == identity + assert reread["replan_action_packet"]["settlement_only"] is True + if os.name == "nt": + shell = shutil.which("pwsh") or shutil.which("powershell") + assert shell is not None + result = subprocess.run( + [shell, "-NoProfile", "-Command", command + "; exit $LASTEXITCODE"], + capture_output=True, text=True, timeout=60, + env={**os.environ, "PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"]}, + ) + native = read_cli_policy_payload(result.stdout, returncode=result.returncode) + assert result.returncode == 0, native + assert native["heartbeat_receipt"]["settlement_identity"] == identity + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_projected_terminal_replan_fields_execute_without_guessed_flags(tmp_path, monkeypatch, provider): + from copy import deepcopy + from loopx.install_contract import render_host_cli_command + + call, _, index = _fixture(tmp_path, monkeypatch, provider, future_monitor=False) + call("configure-goal", "--goal-id", GOAL, "--execution-stride-strategy", "off", "--execute") + # The complete delivery has no remaining Todo; retain its accepted mainline. + rows = [json.loads(row) for row in index.read_text().splitlines()] + vision = deepcopy(next(row["agent_vision"] for row in rows if "agent_vision" in row)) + original = _guard(call) + identity = original["heartbeat_receipt"]["settlement_identity"] + contract = original["replan_action_packet"]["writeback_contract"] + context = original["autonomous_replan_obligation"]["replan_context"] + assert context["evidence"] + for row in context["evidence"]: + read = row.get("read_action") or context["evidence_read_action_template"].replace("{evidence_ref}", row["evidence_ref"]) + detail = call(*shlex.split(read)[1:]) + assert detail["evidence"]["evidence_ref"] == row["evidence_ref"] + terminal = contract["no_followup_requirements"] + assert terminal["cli_args"] == ["--progress-result-class", "no_followup", + "--progress-coverage-scope-id", "", "--progress-evidence-id", "", + "--agent-vision-json", ""] + assert terminal["vision_fields"] == {"state": "no_followup", "path_delta.outcome": "stop"} + assert "vision_patch" in terminal["preserve"] + vision["state"] = terminal["vision_fields"]["state"] + vision["path_delta"] = { + "schema_version": "goal_path_delta_v0", "outcome": terminal["vision_fields"]["path_delta.outcome"], + "prior_assumption": "The bounded source scope could need more work.", + "observed_reality": "Independent validation covers the complete source scope.", + "stopped": ["Repeated source checks"], "evidence_refs": ["validation:complete-source"], + } + path = tmp_path / "author's terminal.json" + path.write_text(json.dumps(vision), encoding="utf-8") + command = next(action for action in original["interaction_contract"]["cli_channel"]["next_cli_actions"] + if "refresh-state" in action) + argv = shlex.split(command) + # Replace only the caller-authored values in the projected template. + argv[argv.index("--agent-vision-json") + 1] = str(path) + values = {"": str(path), "": "scope:complete-source", + "": "validation:complete-source"} + for flag, value in zip(terminal["cli_args"][::2], terminal["cli_args"][1::2], strict=True): + if flag in argv: + argv[argv.index(flag) + 1] = values.get(value, value) + else: + argv.extend([flag, values.get(value, value)]) + argv.extend(["--no-global-sync", "--suppress-external-sinks"]) + if os.name == "nt": + shell = shutil.which("pwsh") or shutil.which("powershell") + assert shell is not None + # Exercise the native shell, including a quoted executable and apostrophe. + argv[0] = str(Path(sys.executable).parent / "loopx.exe") + invocation = [shell, "-NoProfile", "-Command", render_host_cli_command(argv) + "; exit $LASTEXITCODE"] + else: + invocation = [sys.executable, "-m", "loopx.cli", *argv[1:]] + result = subprocess.run(invocation, capture_output=True, text=True, timeout=60) + written = json.loads(result.stdout) + assert result.returncode == 0, json.dumps(written, ensure_ascii=False) + assert written["settlement_identity"] == identity + assert written["autonomous_replan_ack"]["semantic_delta"]["satisfying_outcomes"] == ["coverage_backed_no_followup"] + spent = call(*shlex.split(written["settlement_owed"]["command"])[1:]) + assert spent["settlement_progress"]["state"] == "settled" + assert call(*shlex.split(written["settlement_owed"]["command"])[1:])["idempotent_replay"] is True + + @pytest.mark.parametrize("provider", ["file", "sqlite"]) @pytest.mark.parametrize("context_delivery", ["off", "on"]) def test_successor_cli_reads_policy_with_context_delivery( diff --git a/tests/control_plane/test_replan_writeback_projection.py b/tests/control_plane/test_replan_writeback_projection.py index 96258b7975..ecff0fda03 100644 --- a/tests/control_plane/test_replan_writeback_projection.py +++ b/tests/control_plane/test_replan_writeback_projection.py @@ -155,7 +155,7 @@ def test_declared_outcomes_not_trigger_name_determine_writeback_input() -> None: def test_guarded_successor_guidance_closes_original_turn_before_stopping(profile: str) -> None: payload = {"replan_action_packet": {"writeback_contract": {"successor_command": "loopx todo add"}}} binding = "--replan-obligation-id replan-1111111111111111 --turn-instance-id turn-original" - guard = f"loopx --format json quota should-run {profile} --goal-id example --agent-id agent-example {binding}" + guard = f"loopx --format json quota should-run {profile} --goal-id example --agent-id agent-example --turn-instance-id turn-original" actions = build_autonomous_replan_cli_actions( payload, goal_id="example", settlement_args=f" {binding}", scoped_cli_args=" --agent-id agent-example", quota_spend_action="spend-bound-turn", @@ -243,10 +243,11 @@ def test_successor_guard_entrypoint_retains_host_and_only_pure_replan_binding( tokens = shlex.split(actions[1]) assert tokens[tokens.index("--runtime-root") + 1] == "/tmp/public-safe-replan-runtime" assert tokens[tokens.index("--turn-instance-id") + 1] == "turn-original" - assert tokens[tokens.index("--replan-obligation-id") + 1] == identity["replan_obligation_id"] + assert "--replan-obligation-id" not in tokens assert tokens[tokens.index("--agent-id") + 1] == "agent-example" assert "--todo-id" not in tokens - assert render_scheduler_execution_args(scheduler_execution_context=context).strip() in actions[1] + for arg in shlex.split(render_scheduler_execution_args(scheduler_execution_context=context)): + assert arg in tokens assert "do not execute or select its successor" in actions[2] diff --git a/tests/control_plane_ts/replan_semantics.test.ts b/tests/control_plane_ts/replan_semantics.test.ts index 274fa81016..39fdd04bce 100644 --- a/tests/control_plane_ts/replan_semantics.test.ts +++ b/tests/control_plane_ts/replan_semantics.test.ts @@ -341,6 +341,21 @@ test("no-followup cannot hide an inconsistent vision behind another accepted out assert.equal(valid.accepted, true); }); +test("terminal input projection supplies coverage and vision without widening restricted exits", () => { + const result = projectReplanSemantics({operation: "requirements", obligation}); + const contract = result.writeback_contract as JsonObject; + const terminal = contract.no_followup_requirements as JsonObject; + assert.deepEqual(terminal.cli_args, ["--progress-result-class", "no_followup", + "--progress-coverage-scope-id", "", "--progress-evidence-id", "", + "--agent-vision-json", ""]); + assert.deepEqual(terminal.vision_fields, {state: "no_followup", "path_delta.outcome": "stop"}); + assert.deepEqual(terminal.preserve, ["vision_patch"]); + const restricted = projectReplanSemantics({operation: "requirements", obligation: { + ...obligation, satisfying_semantic_outcomes: ["new_concrete_blocker"], + }}); + assert.equal((restricted.writeback_contract as JsonObject).no_followup_requirements, undefined); +}); + test("external progress review: renamed identifiers discharge only behind new evidence; the plan may stand on evidence", () => { const review = {triggers: [{kind: "external_progress_review_drift", model_authority: "none"}]}; const projection = projectReplanSemantics({operation: "requirements", obligation: review});