diff --git a/loopx/control_plane/agents/workspace_guard.py b/loopx/control_plane/agents/workspace_guard.py index ac113a122f..52a88eb38c 100644 --- a/loopx/control_plane/agents/workspace_guard.py +++ b/loopx/control_plane/agents/workspace_guard.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections.abc import Mapping from typing import Any, cast from hashlib import sha256 @@ -435,6 +436,18 @@ def observe_goal_local_workspace( return {"workspace": snapshot, **project_goal_write_scopes(str(root), scopes)} +def workspace_guard_missing_task_repository( + guard: Mapping[str, object] | None, +) -> bool: + """Return whether the workspace guard fired only on a Goal-repo fallback.""" + return ( + isinstance(guard, Mapping) + and guard.get("current_workspace") == "foreign_git_worktree" + and guard.get("repository_source") == "goal.repo" + and not guard.get("task_repository") + ) + + def build_agent_workspace_guard( goal: dict[str, Any], agent_identity: dict[str, Any] | None, @@ -521,6 +534,17 @@ def build_agent_workspace_guard( current_workspace = "canonical_checkout" if not current_workspace: return None + required_action = ( + "create or switch to an independent git worktree/branch for this peer lane, " + "then rerun quota should-run with the same --agent-id before editing files" + ) + if not task_repository and current_workspace == "foreign_git_worktree": + required_action = ( + "if this Todo intentionally targets the current repository, run loopx todo update " + "--task-repository ; otherwise create or switch " + "to an independent worktree of the Goal repository; then rerun quota " + "should-run with the same --agent-id before editing files" + ) payload = { "schema_version": AGENT_WORKSPACE_GUARD_SCHEMA_VERSION, "source": "quota.should-run", @@ -534,10 +558,7 @@ def build_agent_workspace_guard( "peer delivery with repository writes is not running from an independent " "worktree; normal delivery must move before repository edits" ), - "required_action": ( - "create or switch to an independent git worktree/branch for this peer lane, " - "then rerun quota should-run with the same --agent-id before editing files" - ), + "required_action": required_action, } if task_repository: payload["task_repository"] = task_repository diff --git a/loopx/control_plane/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index e8f0e76ad5..4a413dbe1f 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -991,9 +991,13 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly const deferredReentry = hasBoundDatedTodoReentry(context, interaction, plan); const turnBindingRequired = cli?.turn_binding_required === true; const admissionFields = ["next_cli_actions", "spend_allowed_now", "spend_after_validation", "spend_policy"]; - if (turnBindingRequired) + if (turnBindingRequired) { for (const field of ["turn_binding_required", ...admissionFields]) include("interaction_contract", "cli_channel", field); + } else if (context.effective_action === EffectiveAction.AGENT_WORKSPACE_REPAIR) { + for (const field of admissionFields) + include("interaction_contract", "cli_channel", field); + } const channel = object(interaction.agent_channel); // The matching inbox read is already required during explicit Todo selection. const selectingBeforeWork = context.ok === true && context.should_run === true && diff --git a/loopx/control_plane/quota/should_run_packet.py b/loopx/control_plane/quota/should_run_packet.py index 294d2fc2a4..78823987d1 100644 --- a/loopx/control_plane/quota/should_run_packet.py +++ b/loopx/control_plane/quota/should_run_packet.py @@ -271,6 +271,7 @@ def _execution_obligation( external_evidence_observation: dict[str, Any] | None = None, user_gate_owns_frontier: bool = False, blocked_retry_wait: dict[str, Any] | None = None, + workspace_guard: Mapping[str, Any] | None = None, ) -> dict[str, Any]: return build_execution_obligation( should_run=should_run, @@ -280,6 +281,7 @@ def _execution_obligation( external_evidence_observation=external_evidence_observation, user_gate_owns_frontier=user_gate_owns_frontier, blocked_retry_wait=blocked_retry_wait, + workspace_guard=workspace_guard, successor_replan_mode=AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED.value, ) @@ -1426,6 +1428,7 @@ def _build_active_quota_payload( prepared.user_todo_summary, prepared.agent_todo_summary, ), + workspace_guard=prepared.workspace_guard, ) # Single-field mirror so heartbeat prompts can stay thin: agents key work # obligation off this boolean instead of parsing notify semantics. diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index a3ffe17e47..f7d7ef4cc2 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -2343,12 +2343,14 @@ function admittedTurnRoute( const INITIAL_CONTEXT_DECISION_FIELDS = ["ok", "schema_version", "goal_id", "agent_id", "should_run", "effective_action", "normal_delivery_allowed", "recovery_delivery_allowed", "self_repair_allowed", "capability_repair_allowed", "workspace_repair_allowed", "safe_bypass_allowed", "safe_bypass_kind", "blocked_action_scope", "reason", - "execution_obligation", "goal_boundary", "heartbeat_receipt", "work_lane_contract", "selected_todo"]; + "execution_obligation", "workspace_guard", "goal_boundary", "heartbeat_receipt", "work_lane_contract", "selected_todo"]; /** The read-only plan needs the current decision and executable authoring * guidance. Evidence and diagnostics remain in its exact source capture. */ function turnPlanInspectionPaths(decision: JsonObject, route: "ready_for_host" | "replan_required"): string[][] { - const paths = INITIAL_CONTEXT_DECISION_FIELDS.filter(field => field !== "schema_version").map(field => [field]); + const paths = INITIAL_CONTEXT_DECISION_FIELDS + .filter(field => field !== "schema_version" && (field !== "workspace_guard" || Object.hasOwn(decision, "workspace_guard"))) + .map(field => [field]); for (const field of ["agent_identity", "decision", "recommended_action", "execution_preparation", "requires_user_action", "action_portfolio", "delivery_workspace_isolation", "replan_action_packet"]) paths.push([field]); diff --git a/loopx/control_plane/work_items/execution_obligation.py b/loopx/control_plane/work_items/execution_obligation.py index 1d8625c5d7..800b2582f0 100644 --- a/loopx/control_plane/work_items/execution_obligation.py +++ b/loopx/control_plane/work_items/execution_obligation.py @@ -1,8 +1,10 @@ from __future__ import annotations +from collections.abc import Mapping from typing import Any, cast from ..agents.agent_scope_frontier import AgentScopeFrontierAction +from ..agents.workspace_guard import workspace_guard_missing_task_repository from ..quota.effective_action import EffectiveAction @@ -19,6 +21,7 @@ def build_execution_obligation( user_gate_owns_frontier: bool = False, successor_replan_mode: str = SUCCESSOR_REPLAN_REQUIRED_MODE, blocked_retry_wait: dict[str, Any] | None = None, + workspace_guard: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Separate the worker execution contract from user-facing notification.""" @@ -30,6 +33,17 @@ def build_execution_obligation( else {} ) if should_run and recommended_mode == "repair_agent_workspace": + contract_obligation = ( + str(workspace_guard["required_action"]) + if workspace_guard_missing_task_repository(workspace_guard) + and isinstance(workspace_guard, Mapping) + and isinstance(workspace_guard.get("required_action"), str) + else ( + "do not edit repository files from a shared checkout; " + "create or switch to an independent worktree/branch, then rerun " + "quota should-run with the same agent id" + ) + ) return { "must_attempt_work": True, "kind": "agent_workspace_repair", @@ -37,11 +51,7 @@ def build_execution_obligation( "delivery_allowed": False, "notify_is_execution_gate": False, "contract": "agent_workspace_guard", - "contract_obligation": ( - "do not edit repository files from a shared checkout; " - "create or switch to an independent worktree/branch, then rerun " - "quota should-run with the same agent id" - ), + "contract_obligation": contract_obligation, "spend_policy": heartbeat_recommendation.get("spend_policy"), "reason": ( "peer delivery includes repository writes while the current workspace " diff --git a/loopx/control_plane/work_items/interaction_contract.py b/loopx/control_plane/work_items/interaction_contract.py index 7bc65511b2..dfa70c1206 100644 --- a/loopx/control_plane/work_items/interaction_contract.py +++ b/loopx/control_plane/work_items/interaction_contract.py @@ -17,7 +17,10 @@ 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 +from ..agents.workspace_guard import ( + delivery_workspace_refresh_hint, + workspace_guard_missing_task_repository, +) from ..goals.goal_frontier import AUTONOMOUS_REPLAN_REQUIRED_MODE from ..goals.goal_vision_wait import exact_blocked_successor_wait_state from ..quota.settlement import ( @@ -1006,6 +1009,30 @@ def _admitted_interaction_next_cli_actions( ), ] if mode == "agent_workspace_repair": + guard = payload.get("workspace_guard") + if workspace_guard_missing_task_repository( + guard if isinstance(guard, Mapping) else None + ): + selected_todo = payload.get("selected_todo") + selected_todo_id = ( + normalize_todo_id(selected_todo.get("todo_id")) + if isinstance(selected_todo, Mapping) + else None + ) + todo_arg = ( + f" --todo-id {shlex.quote(selected_todo_id)}" + if selected_todo_id + else "" + ) + return [ + ( + f"if this Todo targets the current repository: {command_prefix} todo update " + f"--goal-id {goal_id}{todo_arg}{lifecycle_actor_args} " + "--task-repository ; otherwise create or switch " + "to an independent worktree of the Goal repository" + ), + typed_quota_guard, + ] return [ "create or switch to an independent git worktree/branch", typed_quota_guard, diff --git a/loopx/control_plane/work_items/interaction_contract.ts b/loopx/control_plane/work_items/interaction_contract.ts index ef03a88d9b..31d19f4a2c 100644 --- a/loopx/control_plane/work_items/interaction_contract.ts +++ b/loopx/control_plane/work_items/interaction_contract.ts @@ -275,7 +275,10 @@ export function selectPrimaryActionInstruction(value: unknown, mode: string): st if (["user_gate", "user_todo_blocker_push", "user_action_required"].includes(mode)) return "wait for user/owner action after surfacing the blocker or gate"; if (mode === EffectiveAction.OUTCOME_FLOOR_RECOVERY) return "produce the required outcome-floor evidence artifact or write the concrete blocker"; if (mode === EffectiveAction.CAPABILITY_BRIDGE_REPAIR) return "execute interaction_contract.agent_channel.next_task_action.operation once with its real task-facing tool and exact target_ref when projected; preflight_allowed is false, and the instruction is context rather than CLI text; on success execute cli_channel.next_cli_actions[0] in the same turn and continue only when quota allows"; - if (mode === EffectiveAction.AGENT_WORKSPACE_REPAIR) return "create or switch to an independent worktree/branch, then rerun quota guard before file edits"; + if (mode === EffectiveAction.AGENT_WORKSPACE_REPAIR) { + return text(facts, "workspace_repair_action") + || "create or switch to an independent worktree/branch, then rerun quota guard before file edits"; + } if (mode === "automation_prompt_upgrade") return "update the installed automation once using the stable migration id, run its completion ack, then rerun quota guard"; if (mode === "control_plane_self_repair") return "repair the bounded control-plane/status projection fault exposed by quota"; if (mode === EffectiveAction.BOUNDARY_PROJECTION_REPAIR) return "repair goal_boundary.write_scope projection before attempting the selected write"; diff --git a/loopx/control_plane/work_items/primary_action.py b/loopx/control_plane/work_items/primary_action.py index 7e90e98dc3..c732beb134 100644 --- a/loopx/control_plane/work_items/primary_action.py +++ b/loopx/control_plane/work_items/primary_action.py @@ -4,6 +4,7 @@ from typing import Any from ...state_projection import next_action_resolution_trace +from ..agents.workspace_guard import workspace_guard_missing_task_repository from ..todos.contract import TODO_TASK_CLASS_ADVANCEMENT from ..todos.todo_semantics import todo_item_is_actionable_open, todo_item_task_class from .autonomous_replan_obligation import todo_lifecycle_settlement_obligation @@ -58,6 +59,7 @@ def address(item: dict[str, Any], *, limit: int = 80) -> dict[str, Any]: packet = obj(payload.get("replan_action_packet")) writeback = obj(packet.get("writeback_contract")) contract = obj(payload.get("task_orchestration_contract")) + guard = obj(payload.get("workspace_guard")) lifecycle = todo_lifecycle_settlement_obligation(payload) return { "goal_id": goal_id, @@ -106,6 +108,11 @@ def address(item: dict[str, Any], *, limit: int = 80) -> dict[str, Any]: if isinstance(contract.get("eligible_peer_lanes"), list) else 0}, "contract_obligation": str(obj(payload.get("execution_obligation"))["contract_obligation"]) if obj(payload.get("execution_obligation")).get("contract_obligation") else None, + "workspace_repair_action": ( + protocol_action_text(guard.get("required_action"), limit=320) + if workspace_guard_missing_task_repository(guard) + else None + ), } diff --git a/tests/control_plane/test_workspace_git_fact_reads.py b/tests/control_plane/test_workspace_git_fact_reads.py index 7da9345bc9..2302fae5f6 100644 --- a/tests/control_plane/test_workspace_git_fact_reads.py +++ b/tests/control_plane/test_workspace_git_fact_reads.py @@ -1,9 +1,20 @@ """Real Git layout reads stay fresh without repeating a root within a capture.""" +import json +import os +import shlex import subprocess +import sys +from pathlib import Path import pytest from loopx.control_plane.agents import workspace_guard as owner +from tests.control_plane.canonical_authority_fixture import ( + initialize_canonical_source_fixture, + isolate_sqlite_runtime, +) + +REPO_ROOT = Path(__file__).resolve().parents[2] def git(path, *args): @@ -123,3 +134,184 @@ def test_goal_repository_fallback_resolves_each_worktree_once(workspaces, monkey selected_todo={"required_write_scopes": ["src/**"]}, current_path=nested, ) is None assert sum(args == ("rev-parse", "--show-toplevel") for _, args in calls) == 2 + + +def test_foreign_worktree_explains_missing_cross_repository_binding(workspaces, tmp_path): + canonical, _, _ = workspaces + foreign = tmp_path / "foreign" + foreign.mkdir() + git(foreign, "init", "-q") + git(foreign, "remote", "add", "origin", "https://github.com/example/foreign.git") + identity = {"agent_id": "peer", "registered_agents": ["lead", "peer"]} + + guard = owner.build_agent_workspace_guard( + {"repo": str(canonical)}, identity, + selected_todo={"action_kind": "implement"}, current_path=foreign, + ) + + assert guard["current_workspace"] == "foreign_git_worktree" + assert guard["repository_source"] == "goal.repo" + assert "loopx todo update --task-repository " in guard["required_action"] + assert "Goal repository" in guard["required_action"] + + +def test_foreign_worktree_with_explicit_mismatched_task_repository_keeps_move_guidance(workspaces, tmp_path): + canonical, _, _ = workspaces + foreign = tmp_path / "foreign-bound" + foreign.mkdir() + git(foreign, "init", "-q") + git(foreign, "remote", "add", "origin", "https://github.com/example/foreign.git") + identity = {"agent_id": "peer", "registered_agents": ["lead", "peer"]} + + guard = owner.build_agent_workspace_guard( + {"repo": str(canonical)}, + identity, + selected_todo={ + "action_kind": "implement", + "task_repository": "git:github.com/example/other", + }, + current_path=foreign, + ) + + assert guard["current_workspace"] == "foreign_git_worktree" + assert guard["repository_source"] == "selected_todo.task_repository" + assert "--task-repository" not in guard["required_action"] + assert "create or switch to an independent git worktree/branch" in guard["required_action"] + + +@pytest.mark.parametrize("task_repository", [None, "git:github.com/example/other"]) +def test_foreign_worktree_progressive_initial_read_surfaces_missing_binding_guidance( + tmp_path, monkeypatch, task_repository, +): + isolate_sqlite_runtime(tmp_path, monkeypatch) + project = tmp_path / "goal-repo" + project.mkdir() + git(project, "init", "-q") + git(project, "config", "user.name", "Git fact fixture") + git(project, "config", "user.email", "fixture@example.test") + git(project, "remote", "add", "origin", "https://github.com/example/workspace.git") + git(project, "commit", "-q", "--allow-empty", "-m", "Initial goal commit") + + foreign = tmp_path / "foreign-repo" + foreign.mkdir() + git(foreign, "init", "-q") + git(foreign, "config", "user.name", "Git fact fixture") + git(foreign, "config", "user.email", "fixture@example.test") + git(foreign, "remote", "add", "origin", "https://github.com/example/foreign.git") + git(foreign, "commit", "-q", "--allow-empty", "-m", "Initial foreign commit") + + runtime = tmp_path / "runtime" + goal_id = "foreign-repo-hint-fixture" + agent_id = "peer" + todo_id = "todo_foreign_repo_hint" + state_rel = f".codex/goals/{goal_id}/ACTIVE_GOAL_STATE.md" + state_path = project / state_rel + state_path.parent.mkdir(parents=True, exist_ok=True) + repo_attr = f" task_repository={task_repository}" if task_repository else "" + state_path.write_text( + "---\n" + "status: active-read-only\n" + "owner_mode: goal\n" + 'objective: "Verify foreign worktree remediation guidance."\n' + "updated_at: 2026-01-01T00:00:00+00:00\n" + "---\n\n" + "# Foreign Worktree Guidance Fixture\n\n" + "## Agent Todo\n\n" + "- [ ] [P1] Update cross-repository target in independent worktree.\n" + f" \n", + encoding="utf-8", + ) + registry_path = project / ".loopx" / "registry.json" + registry_path.parent.mkdir(parents=True, exist_ok=True) + registry_path.write_text( + json.dumps( + { + "schema_version": "0.1", + "updated_at": "2026-01-01T00:00:00+00:00", + "common_runtime_root": str(runtime), + "goals": [ + { + "id": goal_id, + "domain": "workspace-guard-fixture", + "status": "active-read-only", + "repo": str(project), + "state_file": state_rel, + "adapter": { + "kind": "read_only_project_map_v0", + "status": "connected-read-only", + }, + "coordination": { + "registered_agents": ["lead", agent_id], + "agent_model": "peer_v1", + }, + "authority_sources": [], + "quota": {"compute": 1.0, "window_hours": 24, "allowed_slots": 4}, + } + ], + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + initialize_canonical_source_fixture( + runtime, + goal_id, + state_path=state_path, + provider="sqlite", + ) + + def run_entry(*args: str, cwd: Path) -> dict: + proc = subprocess.run( + [sys.executable, "-m", "loopx.entrypoint", *args], + cwd=cwd, + check=False, + capture_output=True, + text=True, + env={**os.environ, "PYTHONPATH": str(REPO_ROOT)}, + ) + assert proc.returncode == 0, proc.stderr or proc.stdout + return json.loads(proc.stdout) + + nav = run_entry( + "--registry", str(registry_path), + "--runtime-root", str(runtime), + "--format", "json", + "quota", "should-run", + "--codex-app", + "--goal-id", goal_id, + "--agent-id", agent_id, + "--turn-instance-id", "turn-foreign-initial-read", + "--context-delivery", "on", + cwd=foreign, + ) + first_tokens = shlex.split(nav["first_read_command"]) + quota_idx = first_tokens.index("quota") + page = run_entry("--format", "json", *first_tokens[quota_idx:], cwd=foreign) + selections = {row["pointer"]: row["value"] for row in json.loads(page["content"])["selections"]} + + assert selections["/effective_action"] == "agent_workspace_repair" + guard = selections["/workspace_guard"] + assert guard["current_workspace"] == "foreign_git_worktree" + obligation = selections["/execution_obligation"] + primary_action = selections["/interaction_contract/agent_channel/primary_action"] + cli_next = selections.get("/interaction_contract/cli_channel/next_cli_actions") or selections[ + "/interaction_contract/cli_channel" + ]["next_cli_actions"] + cli_actions = " ".join(cli_next) + + if task_repository is None: + assert guard["repository_source"] == "goal.repo" + assert "loopx todo update --task-repository " in guard["required_action"] + assert "--task-repository " in obligation["contract_obligation"] + assert "--task-repository " in primary_action + assert "todo update" in cli_actions + assert "--task-repository " in cli_actions + else: + assert guard["repository_source"] == "selected_todo.task_repository" + assert "--task-repository" not in guard["required_action"] + assert "--task-repository" not in obligation["contract_obligation"] + assert "independent worktree/branch" in primary_action + assert "--task-repository" not in cli_actions