diff --git a/docs/reference/canonical-todo-completion-update.md b/docs/reference/canonical-todo-completion-update.md index 291ece5652..9de8a4a3b9 100644 --- a/docs/reference/canonical-todo-completion-update.md +++ b/docs/reference/canonical-todo-completion-update.md @@ -214,6 +214,28 @@ Python 只复用 OS I/O;准入、声明、期限、源/租约见证和完成 ## Linked User completion effects +### Monitor observations and User gates + +A Monitor observation and a User gate completion have different identities and +different owners. An observation is evidence: a file appearing, a changed hash or +a successful external job never completes or approves a User gate, and the +Monitor contract projects no gate completion command. When a due Monitor is +admitted while the agent has open User gates, its actions carry a read-only +notice instead. + +Two attempts stay rejected by their existing owners: completing the gate with +the Monitor Turn (`settlement binding does not match the original quota +guard`), and attaching evidence through a plain `todo update` +(`handoff_mode_requires_lease`). The agent records the observation with +`quota monitor-poll` and yields. An observation is not tied to any gate, so it is +not reported as one. The gate owner completes a gate through the User lifecycle +with their own decision; a linked target then resumes for a fresh guarded Turn. + +Work that may continue on an observed change without an owner decision does not +belong behind a User gate. Emit it from the observation itself with +`quota monitor-poll --material-change --next-agent-todo ...`: the successor is an +independent runnable Agent Todo, admitted by its own fresh guard. + An admitted `todo complete --decision-outcome approve|reject|cancel` now commits its exact linked Agent Todo effects in the **same** provider transaction as the User completion and receipt. Ordinary User actions completed through update or diff --git a/loopx/control_plane/work_items/interaction_contract.py b/loopx/control_plane/work_items/interaction_contract.py index 73070b5732..5bcaf1e388 100644 --- a/loopx/control_plane/work_items/interaction_contract.py +++ b/loopx/control_plane/work_items/interaction_contract.py @@ -47,7 +47,7 @@ normalize_todo_replan_obligation_id, ) from ..todos.todo_semantics import todo_item_task_class -from ..todos.user_gate import has_only_open_user_actions, open_todo_count +from ..todos.user_gate import has_only_open_user_actions, open_todo_count, open_user_gate_todo_items from ..todos.write_hint import build_capability_resolution_writeback_actions from .autonomous_replan_obligation import ( build_autonomous_replan_cli_actions, @@ -463,6 +463,17 @@ def _due_monitor_cli_actions( ] +# Observation is evidence, never an owner decision: no completion command is projected. +# Keep the text free of quote characters; consumers shlex-split every action. +MONITOR_USER_GATE_NOTICE = ( + "A Monitor observation never completes or approves a User gate. Do not pass the id or claim proof " + "of this Turn to a gate completion, and do not attach evidence to a gate through todo update. " + "Record the observation with the poll below and yield. Work that may continue on an observed change " + "without an owner decision belongs in the successor of that poll (--material-change with " + "--next-agent-todo), not behind a User gate." +) + + def _turn_scoped_cli_settlement_context( payload: dict[str, Any], *, @@ -1436,6 +1447,10 @@ def _build_interaction_cli_channel( work_lane = payload.get("work_lane_contract") if not isinstance(work_lane, Mapping): work_lane = {} + if primary_monitor is not None and turn_instance_id and open_user_gate_todo_items(payload.get("user_todo_summary")): + # Keep the Monitor instruction first; the notice precedes the poll it qualifies. + actions = channel["next_cli_actions"] + channel["next_cli_actions"] = [*actions[:1], MONITOR_USER_GATE_NOTICE, *actions[1:]] auxiliary_monitor = work_lane.get("auxiliary_monitor_poll") if not isinstance(auxiliary_monitor, Mapping): auxiliary_monitor = None diff --git a/tests/control_plane/test_monitor_gate_handoff.py b/tests/control_plane/test_monitor_gate_handoff.py new file mode 100644 index 0000000000..541c21620e --- /dev/null +++ b/tests/control_plane/test_monitor_gate_handoff.py @@ -0,0 +1,104 @@ +"""A due Monitor is told that its observation cannot complete a User gate.""" +from __future__ import annotations + +import json + +import pytest +from canonical_authority_fixture import isolate_sqlite_runtime + +from loopx.control_plane.testing.canary_harness import run_json_cli, run_json_cli_result +from loopx.control_plane.work_items.interaction_contract import MONITOR_USER_GATE_NOTICE +from tests.control_plane.test_monitor_followthrough_contract import ( + AGENT_ID, + GOAL_ID, + _write_fixture, +) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_monitor_observation_never_projects_gate_completion(tmp_path, tmp_path_factory, monkeypatch, provider): + isolate_sqlite_runtime(tmp_path, monkeypatch) + registry, runtime, state = _write_fixture(tmp_path_factory.mktemp("g") / "a b", provider=provider, + handoff_mode="hard_lease") + + def cli(*args): + return run_json_cli(*args, registry_path=registry, runtime_root=runtime) + + def rejected(*args): + rc, result = run_json_cli_result(*args, registry_path=registry, runtime_root=runtime) + assert rc == 1 and result["ok"] is False, result + return result + + def actions(guard): + return guard["interaction_contract"]["cli_channel"]["next_cli_actions"] + + actor = ("--goal-id", GOAL_ID, "--agent-id", AGENT_ID) + scope = (*actor, "--runtime-profile", "generic_cli") + monitor_args = ("todo", "add", "--goal-id", GOAL_ID, "--role", "agent", "--task-class", "continuous_monitor", + "--claimed-by", AGENT_ID, "--target-key", "prices-input", "--cadence", "1m", + "--expires-at", "2099-01-01T00:00:00Z", "--next-due-at", "2000-01-01T00:00:00Z", + "--text", "Observe inputs/prices.json once when due.") + monitor = cli(*monitor_args)["todo_id"] + claim = cli("todo", "claim", *actor, "--todo-id", monitor, "--claimed-by", AGENT_ID) + # Without an open User gate the projection is unchanged. + plain = cli("quota", "should-run", *scope, "--turn-instance-id", "no-gate") + assert plain["selected_todo"]["todo_id"] == monitor + assert MONITOR_USER_GATE_NOTICE not in actions(plain) + + work = cli("todo", "add", "--goal-id", GOAL_ID, "--role", "agent", "--task-class", "advancement_task", + "--claimed-by", AGENT_ID, "--status", "blocked", + "--text", "Compute value from the supplied prices.")["todo_id"] + gate = cli("todo", "add", *actor, "--role", "user", "--task-class", "user_gate", + "--unblocks-todo-id", work, "--text", "Provide inputs/prices.json.")["todo_id"] + # An unrelated owner decision for the same agent must never receive an approval recipe either. + release = cli("todo", "add", *actor, "--role", "user", "--task-class", "user_gate", + "--decision-scope", "production:goal:release", "--text", "Approve the release.")["todo_id"] + + guard = cli("quota", "should-run", *scope, "--turn-instance-id", "no-gate") + assert guard["selected_todo"]["todo_id"] == monitor + projected = actions(guard) + assert "condition unmet" in projected[0] + assert projected[1] == MONITOR_USER_GATE_NOTICE + # The notice never points an observation at a gate, linked or unrelated. + assert "pending user action" not in MONITOR_USER_GATE_NOTICE and "report" not in MONITOR_USER_GATE_NOTICE + commands = [action for action in projected if action.startswith("loopx ")] + assert len(commands) == 1 and " quota monitor-poll " in commands[0], projected + assert not any("todo complete" in action or "--decision-outcome" in action for action in projected) + assert gate not in " ".join(projected) and release not in " ".join(projected) + + price_file = state.parents[3] / "inputs" / "prices.json" + price_file.parent.mkdir() + price_file.write_text('{"A":199}', encoding="utf-8") + poll = cli("quota", "monitor-poll", *scope, "--turn-instance-id", "no-gate", "--todo-id", monitor, + "--target-key", "prices-input", "--result-hash", "prices-present", "--material-change", + "--use-current-task-lease", "--execute") + assert poll["material_change"] is True + assert poll["turn_continuation"]["current_turn_settled"] is True + # The two attempts the notice rules out stay rejected by their existing owners. + denied = rejected("todo", "complete", *actor, "--role", "user", "--todo-id", gate, + "--turn-instance-id", "no-gate", "--decision-outcome", "approve", "--evidence", "Actual input observed") + assert "settlement binding does not match the original quota guard" in denied["error"] + denied = rejected("todo", "update", *actor, "--todo-id", gate, "--evidence", "Actual input observed") + assert denied["error_code"] == "handoff_mode_requires_lease" + rows = {row["todo_id"]: row for row in cli("todo", "list", "--goal-id", GOAL_ID)["todos"]} + assert rows[gate]["status"] == "open" and rows[release]["status"] == "open" + assert rows[work]["status"] == "blocked" + + # A later unchanged check still carries the notice and still offers no completion. + cli("todo", "update", *actor, "--todo-id", monitor, "--claim-operation-id", claim["claim_operation_id"], + "--next-due-at", "2000-01-01T00:00:00Z") + unchanged = cli("quota", "should-run", *scope, "--turn-instance-id", "unchanged-monitor") + assert unchanged["selected_todo"]["todo_id"] == monitor + assert MONITOR_USER_GATE_NOTICE in actions(unchanged) + assert not any("todo complete" in action for action in actions(unchanged)) + + # The owner's own decision remains the only route, and resumes the linked work for a fresh Turn. + completed = cli("todo", "complete", *actor, "--role", "user", "--todo-id", gate, + "--decision-outcome", "approve", "--evidence", "Owner confirmed the supplied prices") + assert completed["unblock_resume"]["state"] == "resumed" + rows = {row["todo_id"]: row for row in cli("todo", "list", "--goal-id", GOAL_ID)["todos"]} + assert rows[work]["status"] == "open" and rows[release]["status"] == "open" + index = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl" + events = [json.loads(line) for line in index.read_text(encoding="utf-8").splitlines()] + assert sum(row["classification"] == "quota_monitor_poll" for row in events) == 1 + assert not any(row["classification"] == "quota_slot_spent" for row in events)