diff --git a/examples/shared-goal-authority-e2e/mutants.py b/examples/shared-goal-authority-e2e/mutants.py index 783aeb4d11..0f2e6e7725 100644 --- a/examples/shared-goal-authority-e2e/mutants.py +++ b/examples/shared-goal-authority-e2e/mutants.py @@ -153,8 +153,8 @@ def remove_native_update_maintenance(source: str) -> str: " if False and normalized_next_action: # DELIBERATE MUTANT: bypass source recheck.")),), "tests/control_plane/test_next_action_writeback.py::test_final_commit_rechecks_relevant_source_facts[task]"), Case("public_refresh_writes_owned_paragraph", (("loopx/state_refresh.py", replacement( - "if not dry_run:\n runs_dir.mkdir(parents=True, exist_ok=True)\n json_path, markdown_path = reserve_unique_run_paths(runs_dir, generated_at)", - "if not dry_run:\n resolved_state_file.write_text(\n current_text + \"\\n- \" + normalized_next_action, encoding=\"utf-8\"\n )\n runs_dir.mkdir(parents=True, exist_ok=True)\n json_path, markdown_path = reserve_unique_run_paths(runs_dir, generated_at)")),), + "runs_dir.mkdir(parents=True, exist_ok=True)\n json_path, markdown_path = reserve_unique_run_paths(runs_dir, generated_at)", + "resolved_state_file.write_text(\n current_text + \"\\n- \" + normalized_next_action, encoding=\"utf-8\"\n )\n runs_dir.mkdir(parents=True, exist_ok=True)\n json_path, markdown_path = reserve_unique_run_paths(runs_dir, generated_at)")),), WRITER_TEST + "test_public_refresh_step_does_not_write_owned_paragraph"), Case("fence_unshared_state_lock", ((COORDINATION + "legacy_writer_fence.ts", replacement( "withFileMutationLock(statePath, () =>", diff --git a/loopx/cli_commands/quota_capture.py b/loopx/cli_commands/quota_capture.py index ef2c636b09..a33c355c74 100644 --- a/loopx/cli_commands/quota_capture.py +++ b/loopx/cli_commands/quota_capture.py @@ -22,11 +22,13 @@ context_index_fields as _context_index_fields, write_initial_context_read_reference, validate_handoff_socket, context_capture_read_command, - write_context_read_reference, private_capture_uid, open_regular_capture, + write_context_read_reference, + private_capture_uid as private_capture_uid, + open_regular_capture as open_regular_capture, ) from ..control_plane.turn_driver.native_context_profile import ( NATIVE_CONTEXT_FIRST_READ_FALLBACK_BYTES, NATIVE_CONTEXT_PAGE_BYTES, - native_context_page_budget, + native_context_page_budget as native_context_page_budget, ) from .quota_context_reader import ( budgeted_ready_opening, @@ -234,10 +236,60 @@ def quota_context_surface(payload: dict[str, Any]) -> str: return "turn_envelope" if version == TURN_ENVELOPE_SCHEMA_VERSION else "quota_packet" +def _saved_decision_reference( + directory: Path | None, *, expected_sha256: str | None = None, +) -> dict[str, str] | None: + """Verify the just-captured private decision file before staging replan views.""" + if directory is None: + return None + candidate = directory / "decision.json" + if not candidate.is_file(): + return None + import hashlib + import os + from ..control_plane.content_digest import BARE_SHA256_PATTERN + from ..control_plane.effect_runtime import MAX_REQUEST_BYTES + from ..control_plane.turn_driver.decision_capture import ( + open_regular_capture, + private_capture_supported, + private_capture_uid, + ) + + if not private_capture_supported(): + return None + if expected_sha256 is not None and BARE_SHA256_PATTERN.fullmatch(expected_sha256) is None: + return None + try: + uid = private_capture_uid() + resolved = candidate.expanduser().absolute() + resolved = resolved.parent.resolve(strict=True) / resolved.name + if resolved.is_symlink(): + return None + descriptor = open_regular_capture(resolved) + with os.fdopen(descriptor, "rb") as stream: + metadata = os.fstat(stream.fileno()) + if ( + metadata.st_uid != uid + or metadata.st_mode & 0o077 + or metadata.st_size > MAX_REQUEST_BYTES + ): + return None + raw = stream.read(metadata.st_size + 1) + except (OSError, ValueError): + return None + if len(raw) > MAX_REQUEST_BYTES: + return None + digest = hashlib.sha256(raw).hexdigest() + if expected_sha256 is not None and digest != expected_sha256: + return None + return {"path": str(resolved), "sha256": digest} + + def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespace, *, capture_directory: Path, capture_id: str, decision_identity: tuple[str, str], progressive_enabled: bool, reader_argv: list[str] | None) -> dict[str, Any]: """Prepare one already-decided native view; callers retain receipt failures.""" + from .quota_request import quota_detail_sections_from_args from ..control_plane.turn_driver.codex_context import ( NativeContextSessionUnavailable, codex_context_directory, prepare_codex_context, ) @@ -246,11 +298,19 @@ def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespa root=getattr(args, "codex_context_root", None), create=True) except NativeContextSessionUnavailable: directory = None # Current full input, no fabricated native journal. + decision_ref = ( + _saved_decision_reference(capture_directory, expected_sha256=capture_id) + if progressive_enabled + and (directory is not None or not bool(getattr(args, "begin_turn", False))) + and "vision" not in quota_detail_sections_from_args(args) + else None + ) prepared = prepare_codex_context(payload, directory=directory, capture_directory=capture_directory, goal_id=decision_identity[0], agent_id=decision_identity[1], surface=quota_context_surface(payload), capture_id=capture_id, continuity_generation=getattr(args, "_context_delivery_generation", None), - progressive_enabled=progressive_enabled) + progressive_enabled=progressive_enabled, + captured_decision=decision_ref) recovery = prepared.delivery.get("recovery") view = native_context_capture_view(prepared.delivery, capture_directory, context_directory=directory, progressive_enabled=progressive_enabled, initial_read_plan=prepared.initial_read_plan, @@ -410,14 +470,15 @@ def capture_decision(directory: Path | None, payload: dict[str, object], *, args: argparse.Namespace | None = None, native_context: bool = False, record_capture: Callable[[dict[str, object], str], None] | None = None) -> str | None: if directory is None: - return + return None from ..control_plane.turn_driver.decision_capture import write_decision_capture try: digest = write_decision_capture(directory / "decision.json", payload, publish=os.replace) if record_capture is not None: record_capture(payload, digest) - if isinstance(payload.get("detail_ref"), dict) and "full_decision" in payload["detail_ref"]: + detail_ref = payload.get("detail_ref") + if isinstance(detail_ref, dict) and "full_decision" in detail_ref: from ..command_invocation import current_loopx_cli_argv write_context_read_reference(directory / "decision.json", digest, diff --git a/loopx/cli_commands/quota_native_context.py b/loopx/cli_commands/quota_native_context.py index 6fc591b321..328c1ef710 100644 --- a/loopx/cli_commands/quota_native_context.py +++ b/loopx/cli_commands/quota_native_context.py @@ -280,6 +280,7 @@ def authority_refusal(error: Exception) -> dict[str, Any]: continuity_generation=getattr(args, "_context_delivery_generation", None), progressive_enabled=activation["progressive_enabled"], selection_command_args_template=transport, captured_decision=captured_decision if activation["progressive_enabled"] + and not args.select and not getattr(args, "list_fields", False) and (args.initial_read or "sha256" in captured_decision) else None, hook_session=hook_session, saved_capture=True, publication_guard=publication_guard) projected = prepared.delivery @@ -423,6 +424,8 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any] and event.get("hook_event_name") in CONTEXT_LIFECYCLE_HOOKS): directory = codex_context_directory(directory=args.codex_context_dir, root=getattr(args, "codex_context_root", None), session=event.get("session_id"), create=True) + if directory is None: + raise ValueError("context directory unavailable") scenario = activation["scenario"] progressive_enabled = activation["progressive_enabled"] payload = codex_context_hook(directory, event) @@ -485,9 +488,10 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any] preparation_context = str(error) except NativePreparationTurnUnavailable as error: preparation_context = str(error) - record_native_execution_preparation( - directory, event, source_sha256=request["source_sha256"], receipt=None, - ) + if request is not None: + record_native_execution_preparation( + directory, event, source_sha256=request["source_sha256"], receipt=None, + ) except (OSError, RuntimeError, subprocess.SubprocessError, ValueError, TypeError, RecursionError): # Reconcile only the attempted source. A concurrent guard # can replace recovery, so it must never be reserved here. diff --git a/loopx/control_plane/quota/unsettled_host_turn.py b/loopx/control_plane/quota/unsettled_host_turn.py index 60cff9bc65..b4efce2ac0 100644 --- a/loopx/control_plane/quota/unsettled_host_turn.py +++ b/loopx/control_plane/quota/unsettled_host_turn.py @@ -129,10 +129,10 @@ def restore_receipt_bound_todo_source( # owner still validates the original source identity and timestamps. from ..todos.list_readback import list_goal_todos - source = list_goal_todos( + goal_todos = list_goal_todos( registry_path=registry_path, runtime_root_arg=str(runtime_root), goal_id=goal_id, ) - todo_fields = {key: source[key] for key in ("user_todos", "agent_todos")} + todo_fields = {key: goal_todos[key] for key in ("user_todos", "agent_todos")} queue = payload.get("attention_queue") or {} return {**payload, "attention_queue": {**queue, "items": [ {**row, **todo_fields, @@ -598,6 +598,38 @@ def _apply_recovery_projection( ) if attention: payload["effective_action"] = EffectiveAction.BLOCKED_WAIT.value + recovery_lease_proof: dict[str, Any] | None = None + if not attention and recovery.get("repair") == "monitor_poll": + from .execution_preparation import project_selected_todo_execution_preparation + + agent_identity = payload.get("agent_identity") + agent_id = ( + agent_identity.get("agent_id") + if isinstance(agent_identity, Mapping) + else payload.get("agent_id") + ) + prior_todo_id = recovery.get("binding_id") + if ( + isinstance(prior_todo_id, str) + and prior_todo_id.strip() + and isinstance(payload.get("goal_id"), str) + and payload["goal_id"].strip() + and isinstance(agent_id, str) + and agent_id.strip() + ): + preparation = project_selected_todo_execution_preparation( + runtime_root=runtime_root, + goal_id=payload["goal_id"], + selected_todo={"todo_id": prior_todo_id}, + agent_id=agent_id, + ) + if ( + isinstance(preparation, Mapping) + and preparation.get("handoff_mode") == "hard_lease" + and preparation.get("state") == "ready" + and isinstance(preparation.get("lease_proof"), Mapping) + ): + recovery_lease_proof = dict(preparation["lease_proof"]) interaction_contract, arbitration = _build_interaction_contract_projection( payload, agent_scope_frontier_actions=[action.value for action in AgentScopeFrontierAction], @@ -606,6 +638,7 @@ def _apply_recovery_projection( turn_instance_id=current_turn_instance_id, runtime_root=str(runtime_root), registry_path=str(registry_path), + recovery_lease_proof=recovery_lease_proof, ) agent_channel = interaction_contract.get("agent_channel") if isinstance(agent_channel, dict): diff --git a/loopx/control_plane/turn_driver/codex_context.py b/loopx/control_plane/turn_driver/codex_context.py index c1b5a0ca99..ffabdca8f5 100644 --- a/loopx/control_plane/turn_driver/codex_context.py +++ b/loopx/control_plane/turn_driver/codex_context.py @@ -419,7 +419,7 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str previous = updated.get("host_execution_preparation") ready = previous.get("ready_capture") if isinstance(previous, dict) else None ready_digest = ready.get("sha256") if isinstance(ready, dict) else None - if isinstance(ready_digest, str) and not previous.get("retired_context_readback") and any( + if isinstance(previous, dict) and isinstance(ready_digest, str) and not previous.get("retired_context_readback") and any( page.get("ok") is True and ready_digest in (page.get("sha256"), page.get("source_sha256")) for page in pages @@ -741,7 +741,7 @@ def _native_context_request(state: dict[str, Any], scope: dict[str, Any], captur if isinstance(target, dict) and target.get("capture_id") == capture_id: # A retry may use # the original predecessor, but never this offer as its own baseline. - previous = previous.get("comparison_base") + previous = previous.get("comparison_base") if isinstance(previous, dict) else None if isinstance(previous, dict) and isinstance(previous.get("target"), dict): try: path, raw, payload = read_context_capture_file(previous["path"], previous["sha256"], private=True) @@ -903,7 +903,7 @@ def _record_native_delivery(root: Path, state: dict[str, Any], result: dict[str, if pinned is not None: reference, opening = pinned state["pending"]["observed_first_read"] = reference - if opening is not None: + if opening is not None and read_plan is not None: read_plan = {**read_plan, "observed_opening": opening} _save(root, state) if read_plan is None: @@ -941,7 +941,12 @@ def prepare_codex_context(payload: dict[str, Any], *, directory: str | None, cap from .decision_capture import capture_progressive_context return NativeContextPreparation(capture_progressive_context( - payload, directory=capture_directory, surface=surface)[0]) + payload, + directory=capture_directory, + surface=surface, + selection_command_args_template=selection_command_args_template, + captured_decision=captured_decision, + )[0]) try: with _locked(directory) as root: recovery_committed = False diff --git a/loopx/control_plane/work_items/interaction_contract.py b/loopx/control_plane/work_items/interaction_contract.py index 74ec33dba7..1af3bfea28 100644 --- a/loopx/control_plane/work_items/interaction_contract.py +++ b/loopx/control_plane/work_items/interaction_contract.py @@ -717,6 +717,7 @@ def interaction_next_cli_actions( turn_instance_id: str | None = None, runtime_root: str | None = None, registry_path: str | None = None, + recovery_lease_proof: Mapping[str, object] | None = None, ) -> list[str]: if unadmitted_action_selection(payload): return [_selection_recovery_command( @@ -730,6 +731,7 @@ def interaction_next_cli_actions( scheduler_execution_context=scheduler_execution_context, capability_reentry=capability_reentry, capability_reentry_resolved=capability_reentry_resolved, settlement_plan=settlement_plan, turn_instance_id=turn_instance_id, runtime_root=runtime_root, registry_path=registry_path, + recovery_lease_proof=recovery_lease_proof, ) @@ -840,6 +842,7 @@ def _admitted_interaction_next_cli_actions( turn_instance_id: str | None = None, runtime_root: str | None = None, registry_path: str | None = None, + recovery_lease_proof: Mapping[str, object] | None = None, ) -> list[str]: goal_id = str(payload.get("goal_id") or "") command_prefix = selection.render_cli_command_prefix(runtime_root=runtime_root, registry_path=registry_path) @@ -1072,6 +1075,7 @@ def _admitted_interaction_next_cli_actions( lifecycle_actor_args=lifecycle_actor_args, typed_quota_guard=typed_quota_guard, turn_instance_id=turn_instance_id, + lease_proof=recovery_lease_proof, ) if mode == "autonomous_replan": return build_autonomous_replan_cli_actions( @@ -1445,6 +1449,7 @@ def _build_interaction_cli_channel( turn_instance_id: str | None = None, runtime_root: str | None = None, registry_path: str | None = None, + recovery_lease_proof: Mapping[str, object] | None = None, ) -> dict[str, Any]: if selection_recovery_required: return selection.action_selection_recovery_cli_channel(_selection_recovery_command( @@ -1479,6 +1484,7 @@ def _build_interaction_cli_channel( turn_instance_id=turn_instance_id, runtime_root=runtime_root, registry_path=registry_path, + recovery_lease_proof=recovery_lease_proof, ), "spend_allowed_now": False, "spend_after_validation": spend_after_selection, @@ -1774,6 +1780,7 @@ def _build_interaction_contract_projection( turn_instance_id: str | None = None, runtime_root: str | None = None, registry_path: str | None = None, + recovery_lease_proof: Mapping[str, object] | None = None, ) -> tuple[InteractionContractPacket, SchedulerArbitration]: execution_obligation = payload.get("execution_obligation") if not isinstance(execution_obligation, dict): @@ -1875,6 +1882,7 @@ def _build_interaction_contract_projection( turn_instance_id=turn_instance_id, runtime_root=runtime_root, registry_path=registry_path, + recovery_lease_proof=recovery_lease_proof, ), } if turn_binding_required: diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index b6e3c72192..38ff46c6b3 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -14,6 +14,9 @@ from ..goals.goal_frontier import ( build_goal_frontier_projection_context_from_status, ) +from ..goals.goal_frontier.semantic_history import ( + latest_autonomous_replan_ack_from_status_payload, +) from ..status.autonomous_replan_projection import ( AUTONOMOUS_RUN_HISTORY_NEUTRAL_CLASSIFICATIONS, autonomous_replan_obligation_from_runs, @@ -212,6 +215,93 @@ def _obligation_was_created_by_current_completion( ) +def _build_writeback_projection_context( + *, + goal_id: str, + safe_agent_id: str, + owned_history: list[dict[str, Any]], + registry_goal: dict[str, Any] | None, + replan_source_route: Mapping[str, Any] | None, + guard_scoped: bool, + guard_semantic_replan_obligation_id: str | None, + receipt_bound_guard_recorded_at: str | None, + receipt_bound_guard_turn_instance_id: str | None, + goal_ref: Mapping[str, Any] | None, + admission_event_id: str | None, + capability_evidence: CapabilityReplanEvidence | None, + replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None, + run_obligation: Mapping[str, Any] | None, + agent_identity: Mapping[str, object] | None, + user_todos: dict[str, object] | None, + agent_todos: dict[str, object] | None, + agent_todo_source_items: list[dict[str, object]], +) -> tuple[dict[str, Any], dict[str, Any]]: + """Build status payload and goal-frontier context for replan writeback.""" + + status_payload: dict[str, Any] = { + **dict(replan_source_route or {}), + "run_history": { + "goals": [ + { + **(registry_goal or {}), + "id": goal_id, + "latest_runs": owned_history, + } + ] + }, + } + projected_ack = ( + latest_autonomous_replan_ack_from_status_payload( + status_payload, + goal_id=goal_id, + agent_id=safe_agent_id, + neutral_classifications=AUTONOMOUS_RUN_HISTORY_NEUTRAL_CLASSIFICATIONS, + ) + if guard_scoped and guard_semantic_replan_obligation_id + else None + ) + status_payload["receipt_bound_replan_ack_candidates"] = historical_ack_candidates_with_writeback_order( + owned_history, goal_id=goal_id, agent_id=safe_agent_id, + obligation_id=guard_semantic_replan_obligation_id, guard_scoped=guard_scoped, + source_route=replan_source_route, + guard_recorded_at=receipt_bound_guard_recorded_at, + guard_turn_instance_id=receipt_bound_guard_turn_instance_id, + goal_ref=goal_ref, admission_event_id=admission_event_id, + ) + if capability_evidence is not None: + status_payload["bounded_research_frontier"] = capability_evidence.frontier + context = build_goal_frontier_projection_context_from_status( + replan_explore_reader=replan_explore_reader, + goal_id=goal_id, + agent_id=safe_agent_id, + status_payload=status_payload, + item={ + **({"autonomous_replan_obligation": run_obligation} if run_obligation else {}), + **({"autonomous_replan_ack": projected_ack} if projected_ack is not None else {}), + }, + project_asset={"execution_profile": (registry_goal or {}).get("execution_profile")}, + user_todo_summary=user_todos, + agent_todo_summary=agent_todos, + agent_todo_source_items=agent_todo_source_items, + fallback_todo_source_items=agent_todo_source_items, + work_lane_contract=build_work_lane_context_contract( + {"progress_scope": "primary_goal"}, + agent_todo_summary=agent_todos, + ), + neutral_replan_ack_classifications=AUTONOMOUS_RUN_HISTORY_NEUTRAL_CLASSIFICATIONS, + registered_agent_ids=list(cast(dict[str, Any], agent_identity)["registered_agents"]), + goal_status=str((registry_goal or {}).get("status") or "active"), + receipt_bound_replan_obligation_id=(guard_semantic_replan_obligation_id if guard_scoped else None), + receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, + agent_profile=( + cast(dict[str, Any], cast(dict[str, Any], agent_identity).get("agent_profile")) + if isinstance(cast(dict[str, Any], agent_identity).get("agent_profile"), dict) + else None + ), + ) + return status_payload, context + + @effect_runtime_request_scope() def qualify_replan_writeback( *, @@ -288,61 +378,25 @@ def qualify_replan_writeback( external_progress_review=external_progress_review, effective_turn_cadence=effective_turn_cadence, ) - status_payload = { - **dict(replan_source_route or {}), - "run_history": { - "goals": [ - { - **(registry_goal or {}), - "id": goal_id, - "latest_runs": owned_history, - } - ] - } - } - status_payload["receipt_bound_replan_ack_candidates"] = historical_ack_candidates_with_writeback_order( - owned_history, goal_id=goal_id, agent_id=safe_agent_id, - obligation_id=guard_semantic_replan_obligation_id, guard_scoped=guard_scoped, - source_route=replan_source_route, - guard_recorded_at=receipt_bound_guard_recorded_at, - guard_turn_instance_id=receipt_bound_guard_turn_instance_id, - goal_ref=goal_ref, admission_event_id=admission_event_id, - ) - if capability_evidence is not None: - status_payload["bounded_research_frontier"] = capability_evidence.frontier - context = build_goal_frontier_projection_context_from_status( - replan_explore_reader=replan_explore_reader, + status_payload, context = _build_writeback_projection_context( goal_id=goal_id, - agent_id=safe_agent_id, - status_payload=status_payload, - item={ - **( - {"autonomous_replan_obligation": run_obligation} - if run_obligation - else {} - ) - }, - project_asset={"execution_profile": (registry_goal or {}).get("execution_profile")}, - user_todo_summary=user_todos, - agent_todo_summary=agent_todos, - agent_todo_source_items=agent_todo_source_items, - fallback_todo_source_items=agent_todo_source_items, - work_lane_contract=build_work_lane_context_contract( - {"progress_scope": "primary_goal"}, - agent_todo_summary=agent_todos, - ), - neutral_replan_ack_classifications=( - AUTONOMOUS_RUN_HISTORY_NEUTRAL_CLASSIFICATIONS - ), - registered_agent_ids=list(cast(dict[str, Any], agent_identity)["registered_agents"]), - goal_status=str((registry_goal or {}).get("status") or "active"), - receipt_bound_replan_obligation_id=(guard_semantic_replan_obligation_id if guard_scoped else None), + safe_agent_id=safe_agent_id, + owned_history=owned_history, + registry_goal=registry_goal, + replan_source_route=replan_source_route, + guard_scoped=guard_scoped, + guard_semantic_replan_obligation_id=guard_semantic_replan_obligation_id, receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, - agent_profile=( - cast(dict[str, Any], cast(dict[str, Any], agent_identity).get("agent_profile")) - if isinstance(cast(dict[str, Any], agent_identity).get("agent_profile"), dict) - else None - ), + receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, + goal_ref=goal_ref, + admission_event_id=admission_event_id, + capability_evidence=capability_evidence, + replan_explore_reader=replan_explore_reader, + run_obligation=run_obligation, + agent_identity=agent_identity, + user_todos=user_todos, + agent_todos=agent_todos, + agent_todo_source_items=agent_todo_source_items, ) obligation = context.get("replan_obligation") selected_capability = guard_capability if guard_scoped else (obligation or {}).get("capability_guard") diff --git a/loopx/control_plane/work_items/unsettled_host_turn_contract.py b/loopx/control_plane/work_items/unsettled_host_turn_contract.py index 1a9ef5238a..a57a024381 100644 --- a/loopx/control_plane/work_items/unsettled_host_turn_contract.py +++ b/loopx/control_plane/work_items/unsettled_host_turn_contract.py @@ -13,6 +13,7 @@ def recovery_cli_actions( lifecycle_actor_args: str, typed_quota_guard: str, turn_instance_id: str | None, + lease_proof: Mapping[str, Any] | None = None, ) -> list[str]: """Render the bounded typed closeout repair outside the main dispatcher.""" @@ -95,6 +96,17 @@ def recovery_cli_actions( ) cadence = str(recovery.get("binding_cadence") or "").strip() cadence_arg = f" --cadence {shlex.quote(cadence)}" if cadence else "" + lease_args = "" + if ( + isinstance(lease_proof, Mapping) + and isinstance(lease_proof.get("idempotency_key"), str) + and lease_proof["idempotency_key"].strip() + and isinstance(lease_proof.get("expected_version"), int) + ): + lease_args = ( + f" --task-lease-idempotency-key {shlex.quote(lease_proof['idempotency_key'].strip())}" + f" --task-lease-expected-version {lease_proof['expected_version']}" + ) return [ ( "If a verified observation was obtained under the original Turn, " @@ -106,8 +118,8 @@ def recovery_cli_actions( f"{command_prefix} quota monitor-poll --goal-id {goal_id}" f"{lifecycle_actor_args} --todo-id {shlex.quote(prior_todo_id)}" f"{target_arg} --result-hash ''" - f"{cadence_arg} --turn-instance-id {shlex.quote(prior_turn_id)} " - "--execute" + f"{cadence_arg} --turn-instance-id {shlex.quote(prior_turn_id)}" + f"{lease_args} --execute" ), ( "If observation is unavailable, instead close only the original " @@ -120,6 +132,7 @@ def recovery_cli_actions( f"{command_prefix} refresh-state --goal-id {goal_id}{lifecycle_actor_args}" f" --todo-id {shlex.quote(prior_todo_id)}" f" --turn-instance-id {shlex.quote(prior_turn_id)}" + f"{lease_args}" " --classification monitor_observation_unavailable" " --delivery-batch-scale single_surface --delivery-outcome outcome_gap" " --progress-result-class blocked --progress-blocker-id ''" diff --git a/loopx/quota.py b/loopx/quota.py index e3477dc065..46af12acd9 100644 --- a/loopx/quota.py +++ b/loopx/quota.py @@ -1029,7 +1029,7 @@ def _attach_auxiliary_monitor_settlement_resume( goal_id=identity.goal_id, agent_id=identity.agent_id, todo_id=identity.todo_id, turn_instance_id=identity.turn_instance_id, replan_obligation_id=identity.replan_obligation_id, command_prefix=prefix, scoped_cli_args=scoped_args, lifecycle_actor_args="", - quota_spend_source=str(progress["quota_spend_source"]), goal_ref=goal_ref, + quota_spend_source=str(progress["quota_spend_source"]), goal_ref=goal_ref, composed_settlement=True, ) ordered_steps = _dict_items(plan.as_dict().get("ordered_steps")) result["settlement_resume"] = { diff --git a/tests/control_plane/replan_packet_fixture.py b/tests/control_plane/replan_packet_fixture.py index 2f2f5bbdf9..23d9aec6bd 100644 --- a/tests/control_plane/replan_packet_fixture.py +++ b/tests/control_plane/replan_packet_fixture.py @@ -24,7 +24,17 @@ def populated_replan_source(root, *, acceptance=False, explore_context=None): def scoped(value): if isinstance(value, dict): - return {key: scoped(item) for key, item in value.items()} + mapped = {key: scoped(item) for key, item in value.items()} + if ( + mapped.get("schema_version") == "quota_settlement_identity_v0" + and mapped.get("todo_id") + and mapped.get("turn_instance_id") + ): + mapped["effect_id"] = ( + f"{mapped['goal_id']}:{mapped['agent_id']}:" + f"{mapped['todo_id']}:{mapped['turn_instance_id']}" + ) + return mapped if isinstance(value, list): return [scoped(item) for item in value] if value == "evidence-goal": @@ -60,6 +70,10 @@ def scoped(value): row["generated_at"] = (start + timedelta(minutes=index)).isoformat() row["turn_instance_id"] = f"turn-synthetic-{index}" row["settlement_identity"]["turn_instance_id"] = row["turn_instance_id"] + row["settlement_identity"]["effect_id"] = ( + f"{row['settlement_identity']['goal_id']}:{row['settlement_identity']['agent_id']}:" + f"{row['settlement_identity']['todo_id']}:{row['turn_instance_id']}" + ) rows.append(row) contract = None if acceptance: diff --git a/tests/control_plane/test_capability_monitor_repair_tool_behavior.py b/tests/control_plane/test_capability_monitor_repair_tool_behavior.py index 9d7110336b..ee21888e65 100644 --- a/tests/control_plane/test_capability_monitor_repair_tool_behavior.py +++ b/tests/control_plane/test_capability_monitor_repair_tool_behavior.py @@ -138,9 +138,19 @@ def transport(**kwargs: Any) -> Mapping[str, Any]: assert CAPABILITY_REPAIR_TARGET_CAPABILITY in quota_result[ "capability_gate" ]["repair_missing"] - assert quota_result["agent_todo_summary"]["monitor_schedule_gap_items"][0][ - "todo_id" - ] == CAPABILITY_REPAIR_MONITOR_TODO_ID + from loopx.control_plane.todos.todo_semantics import ( + todo_summary_monitor_schedule_gap_items, + ) + + summary = quota_result["agent_todo_summary"] + gap_items = summary.get("monitor_schedule_gap_items") + if gap_items is None: + assert ( + summary["monitor_schedule_gap_items_ref"] + == "$.agent_todo_summary.monitor_open_items" + ) + gap_items = todo_summary_monitor_schedule_gap_items(summary) + assert gap_items[0]["todo_id"] == CAPABILITY_REPAIR_MONITOR_TODO_ID def test_actor_rejects_capability_repair_before_quota(tmp_path: Path) -> None: diff --git a/tests/control_plane/test_effective_turn_replan.py b/tests/control_plane/test_effective_turn_replan.py index 03fba2571b..4422758afc 100644 --- a/tests/control_plane/test_effective_turn_replan.py +++ b/tests/control_plane/test_effective_turn_replan.py @@ -339,8 +339,9 @@ def periodic(): ) assert rc == 0, envelope assert envelope["replan_action_packet"]["planning_guidance"] == selected["replan_action_packet"]["planning_guidance"] - assert envelope["replan_action_packet"]["writeback_contract"]["vision_authoring"] == authoring - assert envelope["writeback"]["settlement_plan"] == plan + env_contract = envelope["replan_action_packet"]["writeback_contract"] + assert env_contract["vision_authoring_ref"] == contract["vision_authoring_ref"] + assert envelope["interaction_contract"]["cli_channel"]["settlement_plan"] == plan vision_path = tmp_path / "periodic-vision.json" vision = json.loads(json.dumps(authoring["minimal_example"])) vision["vision_patch"] = {"acceptance_summary": "Original acceptance remains open."} diff --git a/tests/control_plane/test_frontier_deadline.py b/tests/control_plane/test_frontier_deadline.py index b7caca89ce..1703f01fd2 100644 --- a/tests/control_plane/test_frontier_deadline.py +++ b/tests/control_plane/test_frontier_deadline.py @@ -1,3 +1,4 @@ +import copy import json import subprocess import sys @@ -200,7 +201,10 @@ def test_installed_cli_keeps_full_source_deadline_after_compaction(tmp_path, mon assert summary["frontier_deadline"]["identity"] == "todo_monitor_23" assert summary["frontier_deadline"]["next_due_at"] == "2099-01-01T00:01:00+00:00" if role == "agent": - assert "monitor_open_items" not in summary # CLI omits this diagnostic lane entirely. + from loopx.control_plane.quota.cli_projection import compact_quota_should_run_cli_payload + assert len(summary["monitor_open_items"]) >= 1 + displayed = compact_quota_should_run_cli_payload(copy.deepcopy(packet))["agent_todo_summary"] + assert "monitor_open_items" not in displayed # CLI display omits this diagnostic lane. else: assert all(row["todo_id"] != "todo_monitor_23" for row in summary["gate_open_items"]) assert packet["scheduler_hint"]["cold_path_detail"]["frontier_recheck"][ diff --git a/tests/control_plane/test_heartbeat_receipt.py b/tests/control_plane/test_heartbeat_receipt.py index 5a7e6f04ba..ecb8312e8c 100644 --- a/tests/control_plane/test_heartbeat_receipt.py +++ b/tests/control_plane/test_heartbeat_receipt.py @@ -374,22 +374,22 @@ def rows(): # Both routes still owe the same result, writeback and exactly one debit. (project / "validated-result.txt").write_text("Synthetic result validated before closeout.\n") plan = reentry["interaction_contract"]["cli_channel"]["settlement_plan"] + assert plan["schema_version"] == "quota_settlement_plan_v2" command = next(s["command_template"] for s in plan["ordered_steps"] if s["kind"] == "durable_writeback") command = command.replace("", "admission_timer_validated").replace( "", "single_surface").replace("", "outcome_progress") command += (" --delivery-boundary in_flight_continuation --progress-result-class advanced" f" --progress-work-item-id {work} --progress-evidence-id evidence:synthetic-result" " --no-global-sync --suppress-external-sinks") - rc, written = _run_generated_cli(command, registry_path=registry, cwd=project) - assert rc == 0, written - spend = written["settlement_owed"]["command"] for attempt in range(2): - rc, settled = _run_generated_cli(spend, registry_path=registry, cwd=project) - assert rc == 0, settled - assert settled["settlement_result"]["ok"] is True - if attempt: - assert settled["idempotent_replay"] is True - assert settled["appended"] is False + rc, written = _run_generated_cli(command, registry_path=registry, cwd=project) + assert rc == 0, written + assert written["settlement_result"]["ok"] is True + assert written["settlement_progress"]["state"] == "settled" + assert [row["step_kind"] for row in written["settlement_result"]["receipts"]] == [ + "validation", "durable_writeback", "quota_spend", + ] + assert written.get("idempotent_replay", False) is bool(attempt) assert _spend_run_count(runtime) == 1 rc, replay = _run_cli(registry, runtime, *guard) assert rc == 0, replay diff --git a/tests/control_plane/test_heartbeat_registry_route.py b/tests/control_plane/test_heartbeat_registry_route.py index ecec55ac74..9207731093 100644 --- a/tests/control_plane/test_heartbeat_registry_route.py +++ b/tests/control_plane/test_heartbeat_registry_route.py @@ -240,6 +240,7 @@ def test_cli_generated_guard_selection_and_settlement_ignore_conflicting_cwd_reg _route(step["command_template"], registry, runtime) assert cli._spend_run_count(runtime) == 0 + assert plan["schema_version"] == "quota_settlement_plan_v2" refresh = next(c for c in channel["next_cli_actions"] if "refresh-state" in c) replacements = { "": "validated_progress", "": "implementation", @@ -247,19 +248,20 @@ def test_cli_generated_guard_selection_and_settlement_ignore_conflicting_cwd_reg } for placeholder, value in replacements.items(): refresh = refresh.replace(placeholder, value) - code, refreshed = _execute(shlex.split(refresh)[1:] + [ + refresh_args = shlex.split(refresh)[1:] + [ "--vision-state", "vision_on_track", "--vision-summary", "Keep validating the selected work.", "--vision-acceptance", "The same Turn settles once against the selected authority.", "--no-global-sync", "--suppress-external-sinks", - ], project) - assert code == 0 and refreshed["settlement_result"]["ok"], refreshed - spend = next(c for c in channel["next_cli_actions"] if "spend-slot" in c) + ] for replay in (False, True): - code, spent = _execute(shlex.split(spend)[1:], project) - assert code == 0 and spent["settlement_result"]["ok"], spent - if replay: - assert spent["idempotent_replay"] and not spent["appended"] + code, refreshed = _execute(refresh_args, project) + assert code == 0 and refreshed["settlement_result"]["ok"], refreshed + assert refreshed["settlement_progress"]["state"] == "settled" + assert [row["step_kind"] for row in refreshed["settlement_result"]["receipts"]] == [ + "validation", "durable_writeback", "quota_spend", + ] + assert refreshed.get("idempotent_replay", False) is replay assert cli._spend_run_count(runtime) == 1 code, settled = _execute(guard_argv, project) assert code == 0 and settled["effective_action"] == "heartbeat_settled_skip", settled diff --git a/tests/control_plane/test_lifecycle_guard_reentry.py b/tests/control_plane/test_lifecycle_guard_reentry.py index 14659dfe5e..aa9a5f7d0d 100644 --- a/tests/control_plane/test_lifecycle_guard_reentry.py +++ b/tests/control_plane/test_lifecycle_guard_reentry.py @@ -82,7 +82,28 @@ def add_work(): *(["--replan-obligation-id", obligation["obligation_id"]] if new_work == "bound_before_closeout" else [])) later = None - if new_work != "after_closeout": + if new_work == "bound_before_closeout": + later = add_work() + assert later["replan_transition"]["recorded"] is True + assert later["replan_transition"]["outcome"] == "new_runnable_successor" + pending = _guard(call, turn) + assert pending["heartbeat_receipt"]["settlement_identity"] == identity + assert pending.get("selected_todo") is None + assert pending["autonomous_replan_obligation"]["resolution_mode"] == "receipt_bound_replan_settlement" + assert pending["replan_action_packet"]["decision"] == "successor_transition_recorded" + assert pending["replan_action_packet"]["successor_todo_id"] == later["todo_id"] + denied = call("quota", "spend-slot", "--goal-id", GOAL, "--agent-id", AGENT, + "--codex-app", "--turn-instance-id", turn, "--replan-obligation-id", + obligation["obligation_id"], "--source", "heartbeat", "--execute", expected_code=1) + assert denied.get("appended") is not True + actions = pending["interaction_contract"]["cli_channel"]["next_cli_actions"] + refreshed = call(*shlex.split(actions[0])[1:], "--no-global-sync", "--suppress-external-sinks") + assert refreshed["settlement_progress"]["state"] == "spend_required" + assert call(*shlex.split(actions[1])[1:])["settlement_progress"]["state"] == "settled" + assert call(*shlex.split(actions[1])[1:])["appended"] is False + assert call("todo", "list", "--goal-id", GOAL, "--todo-id", later["todo_id"])["todo"]["status"] == "open" + return + if new_work == "before_closeout": later = add_work() for _ in range(2): pending = _guard(call, turn) @@ -177,14 +198,22 @@ def test_native_cli_context_exposes_the_same_bound_lifecycle_reentry( entry = call("quota", "should-run", "--runtime-profile", "generic_cli", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", turn, "--context-delivery", delivery, "--decision-output-dir", str(tmp_path / "capture")) + from loopx.control_plane.quota.turn_envelope import build_turn_envelope + if delivery == "auto": assert entry["schema_version"] == "context_capture_navigation_v1" selected = call("quota", "context-read", "--reference-file", entry["recovery"]["reference_file"], - "--select", "/replan_action_packet/writeback", "--page-bytes", "8000") + "--select", "/interaction_contract/cli_channel/next_cli_actions", "--page-bytes", "8000") assert selected["eof"] is True - writer_command = json.loads(selected["content"])["selections"][0]["value"] + selected_actions = json.loads(selected["content"])["selections"][0]["value"] + full_page = call("quota", "context-read", "--reference-file", entry["recovery"]["reference_file"], + "--page-bytes", "64000", "--max-page-output-bytes", "64000") + assert full_page["eof"] is True + projected = json.loads(full_page["content"]) + assert projected["interaction_contract"]["cli_channel"]["next_cli_actions"] == selected_actions else: - writer_command = entry["replan_action_packet"]["writeback"] + projected = entry + writer_command = build_turn_envelope(projected)["replan_action_packet"]["writeback"] result = subprocess.run(shlex.split(writer_command), capture_output=True, text=True, check=True) writer = json.loads(result.stdout) actions = writer["writeback"]["next_cli_actions"] diff --git a/tests/control_plane/test_monitor_observation_admission.py b/tests/control_plane/test_monitor_observation_admission.py index 1c088d8f40..eeea31d36e 100644 --- a/tests/control_plane/test_monitor_observation_admission.py +++ b/tests/control_plane/test_monitor_observation_admission.py @@ -310,9 +310,10 @@ def test_completed_advancement_retains_auxiliary_monitor_admission( AGENT_ID, "--claimed-by", AGENT_ID, + "--turn-instance-id", + turn, "--evidence", "read-only fixture delivery validated", - "--no-follow-up", "--task-lease-idempotency-key", "primary-execution", "--task-lease-expected-version", @@ -333,6 +334,10 @@ def test_completed_advancement_retains_auxiliary_monitor_admission( *binding, "--todo-id", TODO_ID, + "--task-lease-idempotency-key", + "primary-execution", + "--task-lease-expected-version", + "3", "--classification", "fixture_delivery_validated", "--delivery-batch-scale", @@ -449,26 +454,35 @@ def parsed_closeout(step): }.get(token, token) for token in _projected_cli_args(writeback_command, turn_instance_id=turn) ) - rc, refresh = _run_cli( - registry_path, - runtime, - *args, - "--delivery-workspace-path", - str(project), - "--no-global-sync", - "--suppress-external-sinks", - ) - assert rc == 0, refresh - spend_command = refresh["settlement_owed"]["command"] + for replay_refresh in (False, True): + rc, refresh = _run_cli( + registry_path, + runtime, + *args, + "--delivery-workspace-path", + str(project), + "--no-global-sync", + "--suppress-external-sinks", + ) + assert rc == 0, refresh + assert "settlement_owed" not in refresh + assert refresh["settlement_progress"]["state"] == "settled" + assert [row["step_kind"] for row in refresh["settlement_result"]["receipts"]] == [ + "validation", + "durable_writeback", + "quota_spend", + ] + assert refresh.get("idempotent_replay", False) is replay_refresh + assert _spend_run_count(runtime) == 1 else: assert resume["next_step"]["kind"] == "quota_spend" spend_command = poll["settlement_owed"]["command"] - spend_args = _projected_cli_args(spend_command, turn_instance_id=turn) - for _ in range(2): - rc, spend = _run_cli(registry_path, runtime, *spend_args) - assert rc == 0, spend - assert spend["settlement_identity"]["todo_id"] == TODO_ID - assert _spend_run_count(runtime) == 1 + spend_args = _projected_cli_args(spend_command, turn_instance_id=turn) + for _ in range(2): + rc, spend = _run_cli(registry_path, runtime, *spend_args) + assert rc == 0, spend + assert spend["settlement_identity"]["todo_id"] == TODO_ID + assert _spend_run_count(runtime) == 1 rc, replay = _run_cli(registry_path, runtime, *poll_args) assert rc == 0, replay assert replay["replayed"] is True diff --git a/tests/control_plane/test_progress_observation.py b/tests/control_plane/test_progress_observation.py index f1833a5d8e..44dbdce333 100644 --- a/tests/control_plane/test_progress_observation.py +++ b/tests/control_plane/test_progress_observation.py @@ -314,7 +314,14 @@ def test_host_projects_evidence_context_and_minimal_action_packet() -> None: isinstance(instruction, str) and instruction for instruction in packet["planning_guidance"] ) - assert packet["writeback_contract"] == {} + no_followup = packet["writeback_contract"]["no_followup_requirements"] + assert set(packet["writeback_contract"]) == {"no_followup_requirements"} + assert "--progress-result-class" in no_followup["cli_args"] + assert no_followup["vision_fields"] == { + "state": "no_followup", + "path_delta.outcome": "stop", + } + assert no_followup["preserve"] == ["vision_patch"] assert packet["allowed_terminal"] == [ "exploration_exhausted", "blocked", diff --git a/tests/control_plane/test_replan_authoring_owner.py b/tests/control_plane/test_replan_authoring_owner.py index 748453b4b2..2a6dc9613a 100644 --- a/tests/control_plane/test_replan_authoring_owner.py +++ b/tests/control_plane/test_replan_authoring_owner.py @@ -201,11 +201,18 @@ def test_real_capture_authoring_read_does_not_repeat_work_or_spend(tmp_path, mon "--decision-output-dir", str(capture), cwd=project) assert code == 0, result source = json.loads((capture / "decision.json").read_text()) - authoring = deepcopy(source["replan_action_packet"]["writeback_contract"]["vision_authoring"]) + assert source["replan_action_packet"]["writeback_contract"]["vision_authoring_ref"] == ( + "$.interaction_contract.cli_channel.settlement_plan.ordered_steps[1].vision_authoring" + ) + authoring = deepcopy(source["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"][1]["vision_authoring"]) authoring.pop("minimal_example", None) shared = shared_packet(source) before = state.read_bytes() - run = cli_writer(project, shared, source_digest(shared)) + run = cli_writer( + project, + shared, + build_turn_envelope(shared)["action_signature"]["source_decision_hash"], + ) assert run.returncode == 0, run.stdout + run.stderr assert json.loads(run.stdout)["writeback_contract"]["vision_authoring"] == authoring assert state.read_bytes() == before diff --git a/tests/control_plane/test_replan_progress_native_cli.py b/tests/control_plane/test_replan_progress_native_cli.py index 9ea2edb670..f7d0cdc046 100644 --- a/tests/control_plane/test_replan_progress_native_cli.py +++ b/tests/control_plane/test_replan_progress_native_cli.py @@ -208,13 +208,39 @@ def test_captured_replan_preserves_scoped_memory_without_trusting_reader_locatio source = json.loads(captured) assert source["replan_action_packet"]["decision"] == "replan_required" assert source["reward_memory_recall"]["status"] == "applied" and memory.calls == 1 + from loopx.capabilities.turn_context import attach_turn_context + from loopx.control_plane.turn_driver.driver import build_loopx_turn_plan + projected = project_turn_context(source) assert projected["reward_memory_recall"]["context"]["guidance"] - relocated = {**source, "replan_read_path": str(tmp_path / "other-location.json")} - assert project_turn_context(relocated) == projected + # Signed complete captures reject direct top-level edits, while Host plan + # carrier detail_ref relocation preserves exact capability binding. + assert project_turn_context({**source, "replan_read_path": str(tmp_path / "other-location.json")}) == {} + plan = build_loopx_turn_plan(source, host="codex-cli", execution_mode="isolated-headless") + attach_turn_context( + plan, + registry_path=registry, + goal_id=GOAL, + agent_id=AGENT, + decision=source, + turn_instance_id=TURN, + ) + plan_projected = project_turn_context(plan) + assert plan_projected["reward_memory_recall"]["context"]["guidance"] + relocated = deepcopy(plan) + relocated["detail_ref"] = { + "captured_decision": { + "path": str(tmp_path / "other-location.json"), + "turn_key": plan["transaction"]["turn_key"], + "goal_id": GOAL, + "agent_id": AGENT, + "source_hash_ref": "$.source_decision_hash", + } + } + assert project_turn_context(relocated) == plan_projected changed = deepcopy(relocated) - plan = changed["interaction_contract"]["cli_channel"]["settlement_plan"] - plan["ordered_steps"][1]["command_template"] += " --evidence substituted" + settlement = changed["work_contract"]["interaction_contract"]["cli_channel"]["settlement_plan"] + settlement["ordered_steps"][1]["command_template"] += " --evidence substituted" assert project_turn_context(changed) == {} finally: restart_effect_runtime(wait_for_exit=True) diff --git a/tests/control_plane/test_replan_saved_context.py b/tests/control_plane/test_replan_saved_context.py index 7b73e58e57..00f68afaa3 100644 --- a/tests/control_plane/test_replan_saved_context.py +++ b/tests/control_plane/test_replan_saved_context.py @@ -73,12 +73,17 @@ def test_saved_replan_reads_keep_original_authority(tmp_path, monkeypatch, provi "source": "goal_acceptance", "content": {"status": "loaded", "goal_acceptance_contract": distinct}, }) source["precision_fixture"] = {"exact_integer": 2**53 + 1, "exact_float": 1.0} + source.pop("schema_version", None) + source.pop("contract_binding", None) capture = tmp_path / "precision-source.json" reader_path = capture write_decision_capture(capture, source) if entry == "staged": capture = tmp_path / "already-staged.json" - write_decision_capture(capture, _turn_envelope_result("replan_cli_view", payload=source)) + staged_view = _turn_envelope_result("replan_cli_view", payload=source) + staged_view.pop("schema_version", None) + staged_view.pop("contract_binding", None) + write_decision_capture(capture, staged_view) selected_raw = capture.read_bytes() def snapshot(): @@ -105,7 +110,7 @@ def snapshot(): from loopx.entrypoint import main original = turn_envelope._turn_envelope_result def fail(operation, **kwargs): - if operation == 'context_delivery' and (kwargs.get('native_projection') or {}).get('captured_decision_path'): + if operation == 'context_delivery' and (kwargs.get('native_projection') or {}).get('captured_decision'): marker.write_text('context_delivery') raise EffectRuntimeStartupError('synthetic presentation outage', diagnostic_code='synthetic_fixture') return original(operation, **kwargs) diff --git a/tests/control_plane/test_replan_staged_read.py b/tests/control_plane/test_replan_staged_read.py index 27e18eb74d..1a2851ef01 100644 --- a/tests/control_plane/test_replan_staged_read.py +++ b/tests/control_plane/test_replan_staged_read.py @@ -123,8 +123,10 @@ def test_pure_replan_does_not_advertise_unavailable_explore_attachment(tmp_path, source = json.loads((capture / "decision.json").read_bytes()) original = explore_source(source)["content"]["graph"] graph = explore_source(entry)["content"]["graph"] + raw_graph = call("explore", "turn-context", "--goal-id", goal, "--agent-id", agent)["graph"] assert entry["heartbeat_receipt"]["settlement_identity"]["binding_kind"] == "autonomous_replan" assert not entry.get("selected_todo") + assert graph == original assert "result_attachment_template" not in graph and "result_writeback_read" not in graph assert "unavailable for this pure replan" in graph["result_writeback_guidance"] assert "Read measurement_feedback before repeating a measured route" in graph["result_writeback_guidance"] @@ -132,16 +134,17 @@ def test_pure_replan_does_not_advertise_unavailable_explore_attachment(tmp_path, assert "Capture is optional, not a settlement obligation." in graph["result_writeback_guidance"] for key in ("writeback_results", "measurement_feedback", "result_page", "recent_findings", "record_node_template", "record_finding_template", "guidance"): - assert graph.get(key) == original.get(key) - assert json_bytes(original) - json_bytes(graph) > 2000 - writer_run = subprocess.run(shlex.split(entry["replan_action_packet"]["writeback"]), + assert graph.get(key) == raw_graph.get(key) + assert json_bytes(raw_graph) - json_bytes(graph) > 2000 + writer_run = subprocess.run( + shlex.split(_turn_envelope_result("replan_cli_view", payload=entry)["replan_action_packet"]["writeback"]), capture_output=True, text=True, check=True) writer = json.loads(writer_run.stdout) assert all(not row.get("optional_attachments") for row in writer["writeback"]["settlement_plan"]["ordered_steps"]) # Prove the real attachment owner rejects this binding; projection must # not suggest a new way around it or change its primary commit behavior. - attachment = {**original["result_attachment_template"], "question": "Is the source valid?", + attachment = {**raw_graph["result_attachment_template"], "question": "Is the source valid?", "applicability": "Synthetic source", "input_revision": "source-v1", "observation": "Reviewed", "interpretation": "Unresolved", "status": "tentative", "evidence_refs": ["evidence:source-review"]} with pytest.raises(ValueError, match="requires agent, Todo and Turn identity"): @@ -151,6 +154,7 @@ def test_pure_replan_does_not_advertise_unavailable_explore_attachment(tmp_path, # identity keep the old payload rather than guessing applicability. for mutation in ("capture", "custom", "identity", "attachment"): changed = copy.deepcopy(source) + explore_source(changed)["content"]["graph"] = copy.deepcopy(raw_graph) expected = explore_source(changed)["content"] if mutation == "capture": changed.pop("replan_read_path") @@ -188,9 +192,23 @@ def assert_explore_entry_and_writer(source, entry, writer): assert graph.get(key) == original.get(key) step = next(row for row in writer["writeback"]["settlement_plan"]["ordered_steps"] if row["kind"] == "durable_writeback") attachment = next(row for row in step["optional_attachments"] if row["capability_id"] == "explore") - assert attachment["guidance"] == original["result_writeback_guidance"] + original_guidance = original.get("result_writeback_guidance") + if original_guidance is None and isinstance(original.get("result_writeback_guidance_ref"), str): + node = source + for part in original["result_writeback_guidance_ref"].removeprefix("$.").split("."): + if "[" in part and part.endswith("]"): + key, index = part[:-1].split("[", 1) + node = node[key][int(index)] + else: + node = node[part] + original_guidance = node + assert attachment["guidance"] == original_guidance assert attachment["attachment_template"] == original["result_attachment_template"] - assert json_bytes(original) - json_bytes(graph) > 2000 + resolved_original = dict(original) + if original_guidance is not None and "result_writeback_guidance" not in resolved_original: + resolved_original.pop("result_writeback_guidance_ref", None) + resolved_original["result_writeback_guidance"] = original_guidance + assert json_bytes(resolved_original) - json_bytes(graph) > 2000 @pytest.mark.parametrize("provider", ["file", "sqlite"]) @@ -307,8 +325,9 @@ def observe(command, **kwargs): assert "replan_action_packet" not in view return assert source["autonomous_replan_obligation"]["replan_context"]["context_id"] - assert "replan_context" not in view["autonomous_replan_obligation"] - packet = view["replan_action_packet"] + staged_view = view if context_delivery else _turn_envelope_result("replan_cli_view", payload=view) + assert "replan_context" not in staged_view["autonomous_replan_obligation"] + packet = staged_view["replan_action_packet"] assert "planning_guidance" not in packet capture = Path(source["replan_read_path"]) assert capture.read_bytes() == source_path.read_bytes() @@ -320,7 +339,7 @@ def observe(command, **kwargs): assert read["obligation_id"] == selector["obligation_id"] assert read["stage"] == stage if stage == "writeback": - assert_explore_entry_and_writer(source, view, read) + assert_explore_entry_and_writer(source, staged_view, read) assert {key: fixture[key].read_bytes() for key in before} == before assert capture.read_bytes() == source_path.read_bytes() assert len(commands) == 1 # Reads did not re-enter checkpoint preflight. @@ -357,7 +376,9 @@ def invoke(argv): "--context-delivery", mode, "--delta-delivery", "auto" if mode == "on" else "off", "--decision-output-root", str(captures), "--codex-context-dir", str(native), *(["--defer-context-presentation"] if mode == "on" else [])) - review_argv = shlex.split(entry["replan_action_packet"]["review"]) + assert entry["interaction_contract"]["cli_channel"]["selection_required"] is True + assert not entry["interaction_contract"]["cli_channel"].get("settlement_plan") + review_argv = shlex.split(build_turn_envelope(entry)["replan_action_packet"]["review"]) review = json.loads(invoke(review_argv).stdout) assert review["next"]["selection_required"] is True and "writeback" not in review["next"] selection = entry @@ -444,6 +465,9 @@ def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, m step = next(row for row in changed["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"] if row["kind"] == "durable_writeback") attachment = next(row for row in step["optional_attachments"] if row["capability_id"] == "explore") + if "result_writeback_guidance_ref" in graph and mutation != "capture": + graph.pop("result_writeback_guidance_ref") + graph["result_writeback_guidance"] = attachment["guidance"] if mutation == "custom": graph["result_writeback_guidance"] += " Stop before a new operation." attachment["guidance"] = graph["result_writeback_guidance"] @@ -457,7 +481,7 @@ def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, m changed.pop("replan_read_path") projected = _turn_envelope_result("replan_cli_view", payload=changed) assert explore_source(projected)["content"]["graph"] == graph - entry_writeback = guard["writeback"] if envelope else guard["interaction_contract"]["cli_channel"] + entry_writeback = guard["interaction_contract"]["cli_channel"] assert "settlement_plan" not in entry_writeback and "next_cli_actions" not in entry_writeback assert entry_writeback["settlement_identity"] == source["heartbeat_receipt"]["settlement_identity"] original_files = {key: fixture[key].read_bytes() for key in ("registry", "state", "index")} @@ -477,12 +501,7 @@ def read(stage, expected_code=0): assert result.returncode == expected_code, (result.stdout, result.stderr) return json.loads(result.stdout) review, writer = read("review"), read("writeback") - if not envelope: - assert_explore_entry_and_writer(source, guard, writer) - else: - assert_explore_entry_and_writer(source, { - "interaction_contract": {"agent_channel": {"work_context": guard["work_context"]}}, - "replan_action_packet": packet}, writer) + assert_explore_entry_and_writer(source, guard, writer) assert writer["writeback"]["settlement_plan"] == source["interaction_contract"]["cli_channel"]["settlement_plan"] assert writer["settlement_command"].endswith(" --settle-turn") # Real CLI/default-off and native readers both deliver the original @@ -495,7 +514,7 @@ def read(stage, expected_code=0): assert guard.get("action_portfolio") == source.get("action_portfolio") assert review["context_id"] == writer["context_id"] assert review["obligation_id"] == source["replan_action_packet"]["obligation_id"] - assert {k: v for k, v in writer["writeback_contract"].items() if k not in {"successor_binding_args", "successor_settlement"}} == without_example(source["replan_action_packet"]["writeback_contract"]) + assert writer["writeback_contract"] == without_example(source["replan_action_packet"]["writeback_contract"]) assert (capture / "decision.json").read_bytes() == saved assert {key: fixture[key].read_bytes() for key in original_files} == original_files assert not reader_fixture["registry"].exists() @@ -514,7 +533,7 @@ def read(stage, expected_code=0): target[field] = value (capture / "decision.json").write_text(json.dumps(source)) rejected = read("review", expected_code=1) - assert "source hash" in rejected["reason"] + assert rejected["reason"] == "capture digest mismatch; restore the original capture, do not rerun admission" (capture / "decision.json").write_bytes(saved) # A valid next operation still reaches the existing writer and semantic gate. result = call_progress_cli(fixture, *fixture["refresh"]) diff --git a/tests/control_plane/test_replan_successor_guard_reentry.py b/tests/control_plane/test_replan_successor_guard_reentry.py index 48508cd15a..6922bccd5f 100644 --- a/tests/control_plane/test_replan_successor_guard_reentry.py +++ b/tests/control_plane/test_replan_successor_guard_reentry.py @@ -438,8 +438,9 @@ def test_successor_guard_returns_original_settlement_not_repeated_planning( envelope = call("quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", TURN, "--turn-envelope") assert envelope["replan_action_packet"]["settlement_only"] is True - assert envelope["writeback"]["next_cli_actions"] == actions - assert envelope["action_signature"]["matches"] is True + assert envelope["interaction_contract"]["cli_channel"]["next_cli_actions"] == actions + assert envelope["contract_binding"]["source_decision_hash"] + assert envelope["contract_binding"]["content_hash"] premature_spend = call(*shlex.split(actions[1])[1:], expected_code=1) assert premature_spend.get("appended") is not True assert not any(json.loads(line).get("classification") == "quota_slot_spent" @@ -464,9 +465,10 @@ def test_successor_guard_returns_original_settlement_not_repeated_planning( assert pending_plan["ordered_steps"] == [cli["settlement_plan"]["ordered_steps"][-1]] pending_envelope = call("quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", TURN, "--turn-envelope") - assert pending_envelope["writeback"]["next_cli_actions"] == spend_actions - assert pending_envelope["writeback"]["settlement_plan"] == pending_plan - assert pending_envelope["action_signature"]["matches"] is True + assert pending_envelope["interaction_contract"]["cli_channel"]["next_cli_actions"] == spend_actions + assert pending_envelope["interaction_contract"]["cli_channel"]["settlement_plan"] == pending_plan + assert pending_envelope["contract_binding"]["source_decision_hash"] + assert pending_envelope["contract_binding"]["content_hash"] spent = call(*shlex.split(spend_actions[0])[1:]) assert spent["settlement_progress"]["state"] == "settled" assert spent["appended"] is True diff --git a/tests/control_plane/test_scheduler_interaction_arbitration.py b/tests/control_plane/test_scheduler_interaction_arbitration.py index 0f2e944eb3..2151cc04a5 100644 --- a/tests/control_plane/test_scheduler_interaction_arbitration.py +++ b/tests/control_plane/test_scheduler_interaction_arbitration.py @@ -659,6 +659,7 @@ def test_primary_instruction_adapter_preserves_pinned_python_views(): if name in {f"precedence-{i}" for i in range(8)} else [{"goal_id": "other", "label": "Unscoped backlog"}] if name == "candidate-edge-9" else [] ) + expected.setdefault("workspace_repair_action", None) assert primary_action_instruction_facts(case["payload"]) == expected, name diff --git a/tests/control_plane/test_todo_list_thin.py b/tests/control_plane/test_todo_list_thin.py index 22e04616f6..1a99bce1e2 100644 --- a/tests/control_plane/test_todo_list_thin.py +++ b/tests/control_plane/test_todo_list_thin.py @@ -588,4 +588,4 @@ def test_cli_rejects_thin_outside_todo_list(tmp_path: Path) -> None: assert result.returncode == 1, result.stdout payload = json.loads(result.stdout) - assert payload["error"] == "--thin is supported only by todo list" + assert payload["error"] == "--thin is supported only by todo list, todo receipt, todo claim" diff --git a/tests/control_plane/test_vision_budget_cli.py b/tests/control_plane/test_vision_budget_cli.py index c203b018a5..62af1b9f47 100644 --- a/tests/control_plane/test_vision_budget_cli.py +++ b/tests/control_plane/test_vision_budget_cli.py @@ -312,7 +312,7 @@ def test_authoring_example_material_closeout_has_no_missing_path_replan(tmp_path registry, runtime, vision_path=path, check=True, dry_run=False, autonomous_replan_recorded=False, )) - assert result["vision_checkpoint"]["satisfied"] is True + assert result["vision_checkpoint"]["satisfied"] is (omitted != "wait") quota = fixture.run_quota(registry, runtime) gaps = quota["goal_frontier_projection"]["acceptance_gaps"] outcome_gaps = [g for g in gaps if g["kind"] == "vision_outcome_checkpoint_required"]