diff --git a/docs/reference/protocols/peer-agent-runtime-v1.md b/docs/reference/protocols/peer-agent-runtime-v1.md index 8aa77ee8f2..5c7d42e17a 100644 --- a/docs/reference/protocols/peer-agent-runtime-v1.md +++ b/docs/reference/protocols/peer-agent-runtime-v1.md @@ -72,8 +72,17 @@ workspace isolation only: it is not an agent scope, write scope, permission grant, or replacement for claim/lease and goal-boundary checks. Without the field, the goal repository remains authoritative. -Accountable refresh applies Git isolation to Git delivery. A registered non-Git -Goal can instead record the existing path-free `local_goal_workspace` receipt +Accountable refresh applies Git isolation to Git delivery. For an ordinary +read-only verification, declare `--action-kind verify --required-capability +filesystem_read` and add `shell` when needed. With no repository or write +declaration, the Turn can record the verification workspace from the registered +Goal repository, including its main checkout. Completion and quota still bind +to that Turn and its evidence. An explicit isolation requirement, repository +binding or write declaration keeps its usual workspace checks. Tasks with +ambiguous legacy metadata keep their existing workspace requirements. + +A registered non-Git Goal can instead record the existing path-free +`local_goal_workspace` receipt for peer research or material work. Capture must occur inside that Goal root; an explicit Git task repository or owner isolation requirement cannot use this route. Completion validation remains independent, and in-flight writeback and diff --git a/loopx/control_plane/agents/workspace_guard.py b/loopx/control_plane/agents/workspace_guard.py index c0cd9452fc..6d2f73ebd6 100644 --- a/loopx/control_plane/agents/workspace_guard.py +++ b/loopx/control_plane/agents/workspace_guard.py @@ -244,7 +244,10 @@ def observe_goal_delivery_workspace_isolation( Goal into a Git task. Refresh still verifies the actual producing workspace. """ from ..quota.selected_todo_projection import resolve_selected_todo_write_contract - from ..quota.settlement_workspace_causality import build_delivery_workspace_causality + from ..quota.settlement_workspace_causality import ( + build_delivery_workspace_causality, + uses_registered_verification_workspace, + ) goal_project_asset = goal.get("project_asset") if isinstance(goal, Mapping) else None causality_todo = resolve_selected_todo_write_contract( @@ -267,15 +270,22 @@ def observe_goal_delivery_workspace_isolation( ) policy = goal.get("workspace_guard_policy") policy = policy if isinstance(policy, dict) else {} + explicit_requirement = policy.get("peer_independent_worktree_required") + task_repository = selected_todo.get("task_repository") + registered_verification = workspace is not None and uses_registered_verification_workspace( + causality, task_repository=task_repository, + explicit_peer_worktree_requirement=explicit_requirement, + ) workspace, required = qualify_delivery_workspace_isolation( workspace, multi_agent_goal=len(registered_agent_ids_for_goal(goal)) > 1, - explicit_peer_worktree_requirement=policy.get("peer_independent_worktree_required"), - task_repository=selected_todo.get("task_repository"), + explicit_peer_worktree_requirement=False if registered_verification else explicit_requirement, + task_repository=task_repository, ) # The preview needs policy and kind, not a second producing-workspace receipt. return { "identity_kind": (workspace or {}).get("identity_kind"), "peer_independent_worktree_required": required, + **({"registered_verification_workspace": True} if registered_verification else {}), } @@ -286,6 +296,11 @@ def delivery_workspace_refresh_hint(isolation: dict[str, Any]) -> str: "independent git worktree that produced the delivery; otherwise " "--delivery-workspace-path for that worktree" ) + if isolation.get("registered_verification_workspace") is True: + return ( + "registered Goal workspace used for verification; otherwise " + "--delivery-workspace-path for that workspace" + ) if isolation.get("identity_kind") == "local_goal": return ( "registered local Goal target; when caller cwd differs, refresh with " diff --git a/loopx/control_plane/quota/settlement_workspace_causality.py b/loopx/control_plane/quota/settlement_workspace_causality.py index 541dfe9d24..1cbaf03188 100644 --- a/loopx/control_plane/quota/settlement_workspace_causality.py +++ b/loopx/control_plane/quota/settlement_workspace_causality.py @@ -17,6 +17,7 @@ ) from ..todos.contract import ( normalize_required_write_scopes, + normalize_todo_action_kind, normalize_todo_continuation_policy, normalize_todo_id, normalize_todo_task_repository, @@ -128,9 +129,8 @@ def build_delivery_workspace_causality( if not todo_id: return None task_repository = normalize_todo_task_repository(todo.get("task_repository")) - required_write_scopes = normalize_required_write_scopes( - todo.get("required_write_scopes") or todo.get("required_write_scope") - ) + raw_write_scopes = todo.get("required_write_scopes") or todo.get("required_write_scope") + required_write_scopes = normalize_required_write_scopes(raw_write_scopes) capabilities = todo.get("required_capabilities") required_capabilities = sorted( { @@ -150,8 +150,10 @@ def build_delivery_workspace_causality( expected_todo_id=None, normalized_todo_contract={ "todo_id": todo_id, + "action_kind": normalize_todo_action_kind(todo.get("action_kind")), "task_repository": task_repository, "required_write_scopes": required_write_scopes, + "write_scope_declared": bool(raw_write_scopes), "required_capabilities": required_capabilities, "continuation_policy": continuation_policy, "source": source, @@ -160,6 +162,25 @@ def build_delivery_workspace_causality( ) +def uses_registered_verification_workspace( + causality: Mapping[str, object] | None, + *, + task_repository: str | None, + explicit_peer_worktree_requirement: object, +) -> bool: + """Apply the admitted read-only classification under current workspace policy.""" + return ( + causality is not None + and causality.get("requirement") == "required" + and causality.get("reason") == "declared_read_only_verification" + and not task_repository + and ( + explicit_peer_worktree_requirement is None + or explicit_peer_worktree_requirement is False + ) + ) + + def delivery_workspace_causality_event_fields( causality: Mapping[str, Any] | None, ) -> dict[str, str]: diff --git a/loopx/control_plane/quota/settlement_workspace_causality.ts b/loopx/control_plane/quota/settlement_workspace_causality.ts index 3270b1409d..5a442de7a4 100644 --- a/loopx/control_plane/quota/settlement_workspace_causality.ts +++ b/loopx/control_plane/quota/settlement_workspace_causality.ts @@ -216,8 +216,8 @@ function result(values: JsonObject): JsonObject { export function classifyDeliveryWorkspaceCausality( value: unknown, ): DeliveryWorkspaceCausality | null { - // Missing write metadata stays unknown. Only an explicit non-delivery - // contract with no repository-write evidence can omit workspace validation. + // Missing metadata is not a read-only declaration. Explicit verification + // still needs a workspace receipt, with checkout isolation chosen separately. const contract = requiredObject(value, "normalized_todo_contract"); const todoId = optionalString(contract.todo_id, "todo_id"); if (!todoId) return null; @@ -233,6 +233,7 @@ export function classifyDeliveryWorkspaceCausality( contract.required_capabilities, "required_capabilities", ); + const actionKind = optionalString(contract.action_kind, "action_kind"); const continuationPolicy = optionalString( contract.continuation_policy, "continuation_policy", @@ -250,6 +251,13 @@ export function classifyDeliveryWorkspaceCausality( } else if (continuationPolicy === "same_agent_non_delivery") { requirement = "not_required"; reason = "explicit_non_delivery_without_repository_writes"; + } else if ( + actionKind === "verify" && contract.write_scope_declared === false && + capabilities.includes("filesystem_read") && + capabilities.every((capability) => capability === "filesystem_read" || capability === "shell") + ) { + requirement = "required"; + reason = "declared_read_only_verification"; } else { requirement = "unknown"; reason = "todo_write_contract_not_explicit"; diff --git a/loopx/refresh_state/qualification.py b/loopx/refresh_state/qualification.py index ecdb206498..9e8d05deb6 100644 --- a/loopx/refresh_state/qualification.py +++ b/loopx/refresh_state/qualification.py @@ -21,6 +21,9 @@ ) from ..control_plane.quota.blocked_retry import require_blocked_retry_wait from ..control_plane.quota.settlement import QuotaSettlementReadback, SettlementIdentity +from ..control_plane.quota.settlement_workspace_causality import ( + uses_registered_verification_workspace, +) from ..control_plane.runtime.time import chronology_key, now_local_iso from ..control_plane.todos.active_state_todo_parser import parse_active_state_todos from ..control_plane.todos.completion_validation_accountability import ( @@ -504,14 +507,32 @@ def resolve_refresh_delivery_workspace( break raw_task_repo = selected_contract.get("task_repository") task_repository = str(raw_task_repo) if isinstance(raw_task_repo, str) else None - explicit_req = goal_context.explicit_peer_worktree_requirement + explicit_value = goal_context.explicit_peer_worktree_requirement + explicit_req = explicit_value if isinstance(explicit_value, bool) else None + registered_verification = uses_registered_verification_workspace( + settlement_workspace_requirement, task_repository=task_repository, + explicit_peer_worktree_requirement=explicit_value, + ) + if registered_verification and delivery_workspace is not None: + registered_project = goal_context.resolved_project + if registered_project is None: + raise ValueError("read-only verification requires a registered Goal workspace") + observed_path = delivery_workspace_path or Path.cwd() + if observed_path.resolve() != registered_project.resolve(): + registered = capture_delivery_workspace_fn( + current_path=registered_project, + local_goal_id=goal_id, + local_project_root=registered_project, + ) + if registered is None or ( + registered["workspace_identity"] != delivery_workspace["workspace_identity"] + ): + raise ValueError("read-only verification must use the registered Goal repository") delivery_workspace, peer_independent_worktree_required = ( qualify_delivery_workspace_isolation( delivery_workspace, multi_agent_goal=goal_context.multi_agent_goal, - explicit_peer_worktree_requirement=( - explicit_req if isinstance(explicit_req, bool) else None - ), + explicit_peer_worktree_requirement=False if registered_verification else explicit_req, task_repository=task_repository, ) ) diff --git a/tests/control_plane/test_delivery_workspace_causality.py b/tests/control_plane/test_delivery_workspace_causality.py index c5019d619b..aade0b625c 100644 --- a/tests/control_plane/test_delivery_workspace_causality.py +++ b/tests/control_plane/test_delivery_workspace_causality.py @@ -8,6 +8,7 @@ delivery_workspace_causality_from_event_details, missing_delivery_workspace_resolution, resolve_settlement_workspace_requirement, + uses_registered_verification_workspace, ) @@ -83,6 +84,57 @@ def test_non_delivery_policy_cannot_override_repository_write_contract( assert causality["reason"] == "declared_repository_or_write_contract" +def test_declared_read_only_verification_keeps_the_workspace_receipt() -> None: + causality = build_delivery_workspace_causality( + {"todo_id": "todo_verify", "action_kind": "verify", + "required_capabilities": ["filesystem_read", "shell"]} + ) + + assert causality is not None + assert causality["requirement"] == "required" + assert causality["reason"] == "declared_read_only_verification" + assert uses_registered_verification_workspace( + causality, task_repository=None, explicit_peer_worktree_requirement=None, + ) + assert not uses_registered_verification_workspace( + causality, task_repository=None, explicit_peer_worktree_requirement=True, + ) + assert not uses_registered_verification_workspace( + causality, task_repository=None, explicit_peer_worktree_requirement="true", + ) + assert not uses_registered_verification_workspace( + causality, task_repository="git:github.com/example/other", + explicit_peer_worktree_requirement=None, + ) + + +@pytest.mark.parametrize( + ("overrides", "expected"), + [ + ({"required_capabilities": ["shell"]}, "unknown"), + ({"action_kind": "repair"}, "unknown"), + ({"required_capabilities": ["filesystem_read", "network"]}, "unknown"), + ({"required_capabilities": ["filesystem_read", "filesystem_write"]}, "required"), + ({"required_write_scopes": ["docs/**"]}, "required"), + ({"required_write_scopes": ["../outside"]}, "unknown"), + ({"task_repository": "git:github.com/example/other"}, "required"), + ], +) +def test_verification_does_not_infer_a_read_only_workspace( + overrides: dict[str, object], expected: str, +) -> None: + causality = build_delivery_workspace_causality( + {"todo_id": "todo_verify", "action_kind": "verify", + "required_capabilities": ["filesystem_read", "shell"], **overrides} + ) + + assert causality is not None + assert causality["requirement"] == expected + assert not uses_registered_verification_workspace( + causality, task_repository=None, explicit_peer_worktree_requirement=None, + ) + + def test_underspecified_current_todo_keeps_workspace_guard_fail_closed() -> None: causality = build_delivery_workspace_causality( {"todo_id": "todo_legacy", "action_kind": "inspect"} diff --git a/tests/control_plane/test_delivery_workspace_causality_cli.py b/tests/control_plane/test_delivery_workspace_causality_cli.py new file mode 100644 index 0000000000..a84eaec8b7 --- /dev/null +++ b/tests/control_plane/test_delivery_workspace_causality_cli.py @@ -0,0 +1,283 @@ +"""Exercise workspace causality through the ordinary CLI and both local stores.""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +import pytest + +from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime +from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID, + GOAL_ID, + _classification_count, + _initialize_fixture_authority, + _initialize_git_checkout, + _run_cli, + _spend_run_count, + _write_fixture, +) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_read_only_verification_settles_in_registered_git_checkout( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry_path = _write_fixture(tmp_path) + _initialize_git_checkout(project) + subprocess.run( + [ + "git", + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.com", + "commit", + "--quiet", + "--allow-empty", + "-m", + "Verification fixture", + ], + cwd=project, + check=True, + capture_output=True, + ) + registry = json.loads(registry_path.read_text()) + registry["goals"][0]["coordination"]["registered_agents"].append("peer-agent") + registry_path.write_text(json.dumps(registry)) + _initialize_fixture_authority( + project, runtime, provider=provider, handoff_mode="hard_lease" + ) + + def cli(*args: str, cwd: Path = project) -> tuple[int, dict]: + return _run_cli(registry_path, runtime, *args, cwd=cwd) + + rc, created = cli( + "todo", + "add", + "--goal-id", + GOAL_ID, + "--role", + "agent", + "--claimed-by", + AGENT_ID, + "--text", + "Verify the immutable checkout revision and record the observation.", + "--action-kind", + "verify", + "--task-class", + "advancement_task", + "--required-capability", + "filesystem_read", + "--required-capability", + "shell", + ) + assert rc == 0 and created["added"], created + todo_id = created["todo_id"] + binding = ( + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--todo-id", + todo_id, + "--turn-instance-id", + f"turn-read-only-verification-{provider}", + ) + guard_args = ( + "quota", + "should-run", + "--codex-app", + *binding, + "--available-capability", + "filesystem_read", + "--available-capability", + "shell", + ) + rc, guard = cli(*guard_args) + assert rc == 0, guard + assert ( + guard["interaction_contract"]["cli_channel"]["execution_preparation"]["state"] + == "claim_required" + ) + rc, claim = cli( + "todo", + "claim", + "--goal-id", + GOAL_ID, + "--todo-id", + todo_id, + "--agent-id", + AGENT_ID, + "--claimed-by", + AGENT_ID, + ) + assert rc == 0, claim + rc, ready = cli(*guard_args) + assert rc == 0 and ready["normal_delivery_allowed"], ready + + head = subprocess.check_output( + ["git", "rev-parse", "--verify", "HEAD"], cwd=project, text=True + ).strip() + assert subprocess.check_output( + ["git", "log", "-1", "--format=%s", head], cwd=project, text=True + ).strip() == ("Verification fixture") + evidence = f"evidence:fixture-head-{head}" + rc, completed = cli( + "todo", + "complete", + *binding, + "--claim-operation-id", + claim["claim_operation_id"], + "--evidence", + evidence, + ) + assert rc == 0, completed + + classification = "registered_checkout_verification" + refresh = ( + "refresh-state", + *binding, + "--classification", + classification, + "--delivery-batch-scale", + "test_only", + "--delivery-outcome", + "outcome_progress", + "--delivery-boundary", + "semantic_closeout", + "--vision-state", + "vision_closed", + "--vision-summary", + "Verified the checkout revision through ordinary read commands.", + "--vision-acceptance", + "The verified revision is recorded in the Todo evidence.", + "--progress-result-class", + "advanced", + "--progress-evidence-id", + evidence, + "--no-global-sync", + "--suppress-external-sinks", + "--settle-turn", + "--settlement-receipt", + ) + rc, preview = cli(*refresh, "--dry-run") + assert rc == 0, preview.get("error") or preview + assert ( + ready["delivery_workspace_isolation"]["peer_independent_worktree_required"] + is False + ) + assert ( + "registered Goal workspace" + in ( + ready["interaction_contract"]["cli_channel"][ + "delivery_workspace_causality" + ]["refresh"] + ) + ) + assert preview["delivery_workspace"]["workspace_kind"] == "canonical_checkout" + assert ( + preview["delivery_workspace_causality"]["reason"] + == "declared_read_only_verification" + ) + assert not preview["delivery_workspace"]["peer_independent_worktree_required"] + + # A different canonical checkout cannot supply the registered Goal's receipt. + foreign = tmp_path / "foreign" + foreign.mkdir() + _initialize_git_checkout(foreign) + subprocess.run( + [ + "git", + "remote", + "set-url", + "origin", + "https://github.com/example/foreign.git", + ], + cwd=foreign, + check=True, + capture_output=True, + ) + rc, wrong = cli(*refresh, "--delivery-workspace-path", str(foreign), "--dry-run") + assert rc != 0 and "registered Goal repository" in wrong["error"], wrong + assert _spend_run_count(runtime) == 0 + + rc, written = cli(*refresh) + assert rc == 0 and written["settlement_result"]["ok"], written + assert written["delivery_workspace"]["workspace_kind"] == "canonical_checkout" + assert ( + written["settlement_identity"] + == ready["heartbeat_receipt"]["settlement_identity"] + ) + rc, replay = cli(*refresh) + assert rc == 0 and replay["idempotent_replay"], replay + assert _spend_run_count(runtime) == 1 + assert _classification_count(runtime, classification) == 1 + worktrees = subprocess.check_output( + ["git", "worktree", "list", "--porcelain"], cwd=project, text=True + ) + assert sum(line.startswith("worktree ") for line in worktrees.splitlines()) == 1 + + +def test_read_only_verification_respects_explicit_goal_workspace_isolation( + tmp_path: Path, +) -> None: + project, runtime, registry_path = _write_fixture(tmp_path) + _initialize_git_checkout(project) + registry = json.loads(registry_path.read_text()) + goal = registry["goals"][0] + goal["coordination"]["registered_agents"].append("peer-agent") + goal["workspace_guard_policy"] = {"peer_independent_worktree_required": True} + registry_path.write_text(json.dumps(registry)) + _initialize_fixture_authority(project, runtime) + rc, created = _run_cli( + registry_path, + runtime, + "todo", + "add", + "--goal-id", + GOAL_ID, + "--role", + "agent", + "--claimed-by", + AGENT_ID, + "--text", + "Verify a checkout under the Goal's explicit isolation policy.", + "--action-kind", + "verify", + "--task-class", + "advancement_task", + "--required-capability", + "filesystem_read", + cwd=project, + ) + assert rc == 0 and created["added"], created + rc, guard = _run_cli( + registry_path, + runtime, + "quota", + "should-run", + "--codex-app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--todo-id", + created["todo_id"], + "--available-capability", + "filesystem_read", + "--turn-instance-id", + "turn-explicit-verification-isolation", + cwd=project, + ) + assert rc == 0, guard + assert guard["effective_action"] == "agent_workspace_repair", guard + assert guard["normal_delivery_allowed"] is False + assert ( + guard["delivery_workspace_isolation"]["peer_independent_worktree_required"] + is True + ) diff --git a/tests/control_plane/test_delivery_workspace_causality_runtime.py b/tests/control_plane/test_delivery_workspace_causality_runtime.py index 50fa81bcc0..dc98f492f7 100644 --- a/tests/control_plane/test_delivery_workspace_causality_runtime.py +++ b/tests/control_plane/test_delivery_workspace_causality_runtime.py @@ -34,6 +34,7 @@ def call(method: str, params: dict[str, object]) -> dict[str, object]: assert causality.build_delivery_workspace_causality( { "todo_id": "TODO_WRITE", + "action_kind": "VERIFY", "task_repository": "https://github.com/example/project", "required_write_scope": "src/**", "required_capabilities": ["filesystem_write", "shell"], @@ -51,8 +52,10 @@ def call(method: str, params: dict[str, object]) -> dict[str, object]: assert params["operation"] == "classify" assert params["normalized_todo_contract"] == { "todo_id": "todo_write", + "action_kind": "verify", "task_repository": "git:github.com/example/project", "required_write_scopes": ["src/**"], + "write_scope_declared": True, "required_capabilities": ["filesystem_write", "shell"], "continuation_policy": None, "source": "selected_todo_contract",