diff --git a/docs/reference/required-work-context.md b/docs/reference/required-work-context.md index 7ccc94349b..a35e76e3a7 100644 --- a/docs/reference/required-work-context.md +++ b/docs/reference/required-work-context.md @@ -208,6 +208,14 @@ whole Goal/Todo narrative, source availability/revisions and read routes. Detail history and optional authoring recipes remain expandable from the same capture. Current narrative sources and their provenance precede other sources, including large scoped preferences; both retain their complete selected values. +During an unbound Todo choice, including during workspace repair, the initial +read keeps the candidate identities and selection command. It points to long +candidate write scopes in the original capture when those scopes matter to the +choice. The guard for the same Turn supplies the current scopes before delivery. +When a selected Todo needs an ordinary managed claim, the initial read keeps +the claim and continuation instructions. Read long requested scopes at +`/selected_todo/required_write_scopes` when needed for preparation. Use the +same-Turn guard's complete current scopes after the claim and before delivery. The preference source's complete `current` view also stays in the initial read: corrections, retirement/expiry and empty replacements retain their provenance, revision and advisory authority. This captured pre-work view does not replace the diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index acae4d618b..cb8657fbb6 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -2469,9 +2469,11 @@ function progressivePreparationScopes(payload: JsonObject): PreparationScopeDeta obligation.must_attempt_work === true && obligation.delivery_allowed === false; if (!repair && payload.effective_action !== EffectiveAction.NORMAL_RUN) return []; const selecting = hasUnboundActionSelection(cli); + const selected = jsonObject(payload.selected_todo); const claiming = cli.selection_required !== true && payload.normal_delivery_allowed === false && preparation?.schema_version === EXECUTION_PREPARATION_SCHEMA_VERSION && preparation.state === "claim_required" && - preparation.delivery_allowed === false && jsonObject(preparation.claim)?.host_execution_allowed === true; + preparation.delivery_allowed === false && typeof selected?.todo_id === "string" && + preparation.todo_id === selected.todo_id && jsonObject(preparation.claim)?.host_execution_allowed === true; if (!repair && !selecting && !claiming) return []; const boundary = jsonObject(payload.goal_boundary); // The recovery pointer and its guidance also cost bytes. Leave short lists inline. @@ -2483,18 +2485,26 @@ function progressivePreparationScopes(payload: JsonObject): PreparationScopeDeta marker_path: ["goal_boundary", "write_scope_pointer"], instruction: repair ? "If workspace repair needs the Goal's write scopes, select /goal_boundary/write_scope from the source below. " - : "If choosing work depends on write scope, select the pointer in goal_boundary.write_scope_pointer from the source below. " - + "Use the complete current scope from the ready decision before delivery. ", + : "If work preparation needs the Goal's write scopes, select the pointer in goal_boundary.write_scope_pointer from the source below. ", }); - const selected = jsonObject(payload.selected_todo); - if (repair && selected?.schema_version === "quota_selected_todo_v0" && + if (selected?.schema_version === "quota_selected_todo_v0" && typeof selected.todo_id === "string" && longScope(selected.required_write_scopes)) scopes.push({ path: ["selected_todo", "required_write_scopes"], - instruction: "If workspace repair needs the Todo's requested write scopes, select /selected_todo/required_write_scopes from the source below. ", + instruction: "If this preparation needs the Todo's requested write scopes, select /selected_todo/required_write_scopes from the source below. ", + }); + const suggestions = jsonObject(payload.action_portfolio)?.suggested_actions; + if (selecting && Array.isArray(suggestions)) suggestions.forEach((value, index) => { + const candidate = jsonObject(value); + if (typeof candidate?.todo_id !== "string" || !longScope(candidate.required_write_scopes)) return; + const path = ["action_portfolio", "suggested_actions", index, "required_write_scopes"]; + scopes.push({path, + instruction: `If choosing a candidate depends on its requested write scopes, select /${path.join("/")} from the source below. `, + }); }); const finalScope = scopes.at(-1); - if (repair && finalScope) finalScope.instruction += - "After relocating, rerun the guard for this Turn and use its complete current scopes before delivery. "; + if (finalScope) finalScope.instruction += repair + ? "After relocating, rerun the guard for this Turn and use its complete current scopes before delivery. " + : "Use the complete current scope from the ready decision before delivery. "; return scopes; } diff --git a/tests/control_plane/test_context_first_read.py b/tests/control_plane/test_context_first_read.py index 77c90bee54..3400b7188e 100644 --- a/tests/control_plane/test_context_first_read.py +++ b/tests/control_plane/test_context_first_read.py @@ -313,6 +313,158 @@ def test_initial_read_keeps_supporting_index_obligations_and_recovers_its_full_l assert json.loads(raw) == decision +@pytest.mark.parametrize("workspace_repair", [True, False], ids=["needs-worktree", "independent-worktree"]) +def test_unbound_candidate_scopes_are_only_expanded_on_request(tmp_path, monkeypatch, decision, workspace_repair): + from test_codex_context_lifecycle import setup + + setup(tmp_path, monkeypatch) + long_scopes = [f"src/area-{index:03d}/implementation/entrypoints/**" for index in range(355)] + short_scope = ["docs/reference/**"] + candidates = [ + {"todo_id": "todo_current", "text": "Repair the source entrypoint.", "required_write_scopes": long_scopes}, + {"todo_id": "todo_alternative", "text": "Verify the documentation.", "required_write_scopes": short_scope}, + ] + turn = "workspace-selection-fixture" + mode = "agent_workspace_repair" if workspace_repair else "normal_run" + obligation = "agent_workspace_guard" if workspace_repair else "work_lane_contract" + decision.update(should_run=True, effective_action=mode, + normal_delivery_allowed=not workspace_repair, recovery_delivery_allowed=False, + workspace_repair_allowed=workspace_repair, + agent_identity={"agent_id": "agent"}, + heartbeat_receipt={"turn_instance_id": turn, "settlement_binding_owed": True}, + execution_obligation={"kind": mode if workspace_repair else obligation, "contract": obligation, + "must_attempt_work": True, "delivery_allowed": False}) + decision["selected_todo"].update(schema_version="quota_selected_todo_v0", required_write_scopes=long_scopes) + contract = decision["interaction_contract"] + contract["mode"] = mode + contract["agent_channel"].update(delivery_allowed=False, must_attempt=True, + work_context={"instruction": "Relocate before delivering.", "sources": []}) + contract["cli_channel"] = { + "selection_required": True, "next_cli_actions": [], + "spend_allowed_now": False, "spend_after_validation": False, + "selection_policy_ref": "$.action_portfolio.selection_policy", + "selection_command": {"schema_version": "action_selection_cli_command_v1", + "route_prefix": "loopx --format json", + "command_args_template": f"quota should-run --todo-id '{{todo_id}}' --turn-instance-id {turn}", + "candidate_discovery_args": "todo list --goal-id fixture --status open"}, + } + policy = {"mode": "explicit_turn_binding", "decision_owner": "agent", "requires_explicit_turn_binding": True} + decision["action_portfolio"] = {"selection_policy": policy, "suggested_actions": candidates} + capture = tmp_path / "decision.json" + original = json.dumps(decision).encode() + capture.write_bytes(original) + capture.chmod(0o600) + registry = tmp_path / "absent-registry.json" + runtime = tmp_path / "unused-runtime" + args = [sys.executable, "-m", "loopx.entrypoint", "--registry", str(registry), + "--runtime-root", str(runtime), "--format", "json"] + run = subprocess.run([*args, "quota", "context-project", "--codex-app", + "--context-delivery", "on", "--goal-id", "fixture", "--agent-id", "agent", "--turn-instance-id", turn, + "--capture-file", str(capture), "--capture-sha256", hashlib.sha256(original).hexdigest(), + "--decision-output-root", str(tmp_path / "captures"), "--codex-context-dir", str(tmp_path)], + capture_output=True) + view = json.loads(run.stdout) + assert run.returncode == 0 and view["ok"], view + page, opening = read_selection(view["first_read_command"]) + assert opening["/goal_boundary/stop_condition"] == decision["goal_boundary"]["stop_condition"] + assert opening["/execution_obligation"] == decision["execution_obligation"] + assert opening["/interaction_contract/agent_channel/delivery_allowed"] is False + selection = opening["/interaction_contract/cli_channel/selection_command"] + original_selection = contract["cli_channel"]["selection_command"] + assert selection["candidate_discovery_args"] == original_selection["candidate_discovery_args"] + command_words = shlex.split(selection["command_args_template"]) + original_words = shlex.split(original_selection["command_args_template"]) + assert command_words[:len(original_words)] == original_words + assert opening["/interaction_contract/cli_channel/spend_allowed_now"] is False + assert opening["/action_portfolio/selection_policy"] == policy + projected = opening["/action_portfolio/suggested_actions"] + assert projected == [{key: value for key, value in candidates[0].items() if key != "required_write_scopes"}, + candidates[1]] + assert "required_write_scopes" not in opening["/selected_todo"] + pointer = "/action_portfolio/suggested_actions/0/required_write_scopes" + recommended_scope = "/selected_todo/required_write_scopes" + assert pointer in opening["/context_details/instruction"] + assert recommended_scope in opening["/context_details/instruction"] + assert page["total_bytes"] < len(json.dumps(long_scopes).encode()) + template = opening["/context_details/command_template"] + _, detail = read_selection(template.replace("", pointer) + f" --select {recommended_scope}") + assert detail[pointer] == detail[recommended_scope] == long_scopes + assert capture.read_bytes() == original + assert not registry.exists() and not runtime.exists() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_claim_preparation_keeps_requested_write_scopes_on_demand(tmp_path, monkeypatch, provider): + from test_quota_settlement_cli import ( + AGENT_ID, GOAL_ID, TODO_ID, _configure_repository_write_todo, _heartbeat_receipt_count, + _initialize_fixture_authority, _initialize_git_checkout, _run_cli, _spend_run_count, _write_fixture, + ) + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + + isolate_sqlite_runtime(tmp_path, monkeypatch) + monkeypatch.delenv("CODEX_THREAD_ID", raising=False) + project, runtime, registry = _write_fixture(tmp_path) + scopes = [f"src/area-{index:03d}/implementation/entrypoints/**" for index in range(355)] + state = _configure_repository_write_todo(project) + state.write_text(state.read_text().replace( + "required_capabilities=filesystem_write -->", + f"required_capabilities=filesystem_write required_write_scopes={','.join(scopes)} -->", + )) + config = json.loads(registry.read_text()) + config["goals"][0]["coordination"]["write_scope"] = ["src/**"] + registry.write_text(json.dumps(config)) + _initialize_git_checkout(project) + subprocess.run(["git", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", + "commit", "--quiet", "--allow-empty", "-m", "fixture"], cwd=project, check=True) + workspace = tmp_path / "work" + subprocess.run(["git", "worktree", "add", "--quiet", "--detach", str(workspace)], + cwd=project, check=True) + _initialize_fixture_authority(project, runtime, provider=provider, handoff_mode="hard_lease") + + def cli(*args): + code, result = _run_cli(registry, runtime, *args, cwd=workspace) + assert code == 0 and result["ok"], result + return result + + turn = "same-turn-claim" + binding = ("--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID) + guard = ("quota", "should-run", "--codex-app", *binding, "--turn-instance-id", turn, + "--available-capability", "filesystem_write", "--available-capability", "shell") + captures = tmp_path / "captures" + captures.mkdir(mode=0o700) + native = ("--context-delivery", "on", "--delta-delivery", "off", + "--decision-output-root", str(captures), "--codex-context-root", str(captures)) + raw = cli(*guard, "--context-delivery", "off") + channel = raw["interaction_contract"]["cli_channel"] + preparation = channel["execution_preparation"] + assert preparation["state"] == "claim_required" and preparation["delivery_allowed"] is False + assert preparation["claim"]["host_execution_allowed"] + assert raw["selected_todo"]["required_write_scopes"] == scopes + + view = cli(*guard, *native) + page, opening = read_selection(view["first_read_command"]) + state_pointer = "/interaction_contract/cli_channel/execution_preparation" + scope_pointer = "/selected_todo/required_write_scopes" + assert opening[state_pointer] == preparation + assert opening["/normal_delivery_allowed"] is False + assert opening["/interaction_contract/cli_channel/spend_after_validation"] is False + assert opening["/selected_todo"]["todo_id"] == TODO_ID + assert "required_write_scopes" not in opening["/selected_todo"], page["total_bytes"] + assert scope_pointer in opening["/context_details/instruction"] + _, detail = read_selection(opening["/context_details/command_template"].replace("", scope_pointer)) + assert detail[scope_pointer] == scopes + assert _heartbeat_receipt_count(runtime, turn) == 1 + + claim = cli(*preparation["claim"]["cli_args"]) + assert claim["execution_managed"] and claim["claim_operation_id"] + ready = cli(*guard, *native) + _, opening = read_selection(ready["first_read_command"]) + assert opening["/normal_delivery_allowed"] is True and opening[state_pointer]["state"] == "ready" + assert opening["/selected_todo"]["required_write_scopes"] == scopes + assert opening["/heartbeat_receipt"]["settlement_identity"] == raw["heartbeat_receipt"]["settlement_identity"] + assert _spend_run_count(runtime) == 0 + + @pytest.mark.parametrize("damage", [None, "foreign_plan", "changed_file"]) def test_native_preparation_reuses_only_its_current_digest_bound_navigation( tmp_path, monkeypatch, decision, damage,