diff --git a/loopx/control_plane/quota/live_decision.py b/loopx/control_plane/quota/live_decision.py index cfe569dcfe..b67fe68978 100644 --- a/loopx/control_plane/quota/live_decision.py +++ b/loopx/control_plane/quota/live_decision.py @@ -777,7 +777,10 @@ def build_live_quota_should_run_decision( ): from ..work_items.autonomous_replan_ack import load_receipt_replan_ack_candidates decision_status_payload["receipt_bound_replan_ack_candidates"] = load_receipt_replan_ack_candidates( - runtime_root, goal_id=goal_id, agent_id=agent_id, obligation_id=receipt_bound_replan_obligation_id) + runtime_root, goal_id=goal_id, agent_id=agent_id, + obligation_id=receipt_bound_replan_obligation_id, + guard_recorded_at=receipt_bound_guard_fields["receipt_bound_guard_recorded_at"], + guard_turn_instance_id=receipt_bound_guard_fields["receipt_bound_guard_turn_instance_id"]) fresh_operator_inbox_read = _fresh_operator_inbox_read_required( turn_start_hook_dispatch ) diff --git a/loopx/control_plane/work_items/autonomous_replan_ack.py b/loopx/control_plane/work_items/autonomous_replan_ack.py index c01f7e8738..a9a8ecb81f 100644 --- a/loopx/control_plane/work_items/autonomous_replan_ack.py +++ b/loopx/control_plane/work_items/autonomous_replan_ack.py @@ -267,8 +267,194 @@ def autonomous_replan_ack_candidates_for_obligation( return candidates +def _event_details(event: dict[str, Any]) -> dict[str, Any]: + details = event.get("details") + return details if isinstance(details, dict) else {} + + +def _admission_event_index( + events: list[dict[str, Any]], *, goal_id: str, agent_id: str, + turn_instance_id: str, recorded_at: str, +) -> int | None: + if not turn_instance_id or not recorded_at: + return None + found: int | None = None + for index, event in enumerate(events): + if ( + event.get("event_kind") == "quota_should_run" + and event.get("goal_id") == goal_id + and event.get("agent_id") == agent_id + and event.get("run_id") == turn_instance_id + and event.get("recorded_at") == recorded_at + ): + found = index + return found + + +def _binding_text(value: Any) -> str: + return str(value or "").strip() + + +def _source_run( + runs: list[dict[str, Any]] | None, *, turn_instance_id: str, obligation_id: str, +) -> dict[str, Any]: + for run in runs or []: + if _binding_text(run.get("turn_instance_id")) != turn_instance_id: + continue + ack = run.get("autonomous_replan_ack") + delta = ack.get("semantic_delta") if isinstance(ack, dict) else None + if isinstance(delta, dict) and _binding_text(delta.get("obligation_id")) == obligation_id: + return run + return {} + + +def _expected_todo_receipt( + run: dict[str, Any], events: list[dict[str, Any]], *, + goal_id: str, agent_id: str, turn_instance_id: str, +) -> tuple[str, str]: + """Todo settlement identity for this ACK, filled from its heartbeat receipt. + + A historical index can omit the Todo and effect. The turn's existing + quota receipt still has that exact identity. An empty side is not a match. + """ + + identity = run.get("settlement_identity") + identity = identity if isinstance(identity, dict) else {} + todo = _binding_text(run.get("todo_id") or identity.get("todo_id")) + effect = _binding_text(identity.get("effect_id")) + if todo and effect: + return todo, effect + for event in events: + if ( + event.get("event_kind") != "quota_should_run" + or event.get("goal_id") != goal_id + or event.get("agent_id") != agent_id + or _binding_text(event.get("run_id")) != turn_instance_id + ): + continue + details = _event_details(event) + todo = todo or _binding_text(event.get("todo_id") or details.get("todo_id")) + effect = effect or _binding_text(details.get("settlement_effect_id")) + return todo, effect + + +def _writeback_event_is_bound( + event: dict[str, Any], run: dict[str, Any], events: list[dict[str, Any]], *, + goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str, +) -> bool: + """Require one positive identity shared with the accepted ACK. + + The event obligation must equal the semantic delta, or its Todo and effect + must equal the ACK receipt. Missing fields do not count as agreement. + """ + + if ( + event.get("event_kind") != "refresh_state" + or event.get("goal_id") != goal_id + or event.get("agent_id") != agent_id + or _binding_text(event.get("run_id")) != turn_instance_id + ): + return False + details = _event_details(event) + if details.get("autonomous_replan_recorded") is not True: + return False + event_obligation = _binding_text(details.get("replan_obligation_id")) + if event_obligation: + return event_obligation == obligation_id + event_todo = _binding_text(event.get("todo_id")) + event_effect = _binding_text(details.get("settlement_effect_id")) + if not event_todo or not event_effect: + return False + expected_todo, expected_effect = _expected_todo_receipt( + run, events, goal_id=goal_id, agent_id=agent_id, turn_instance_id=turn_instance_id) + return bool( + expected_todo and expected_effect + and event_todo == expected_todo and event_effect == expected_effect + ) + + +def _original_writeback_event_index( + events: list[dict[str, Any]], runs: list[dict[str, Any]] | None, *, + goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str, +) -> int | None: + if not turn_instance_id or not obligation_id: + return None + run = _source_run(runs, turn_instance_id=turn_instance_id, obligation_id=obligation_id) + for index, event in enumerate(events): + if _writeback_event_is_bound( + event, run, events, goal_id=goal_id, agent_id=agent_id, + obligation_id=obligation_id, turn_instance_id=turn_instance_id, + ): + return index + return None + + +def attach_historical_ack_writeback_order( + candidates: list[dict[str, Any]], events: list[dict[str, Any]], *, + goal_id: str, agent_id: str, obligation_id: str, + guard_recorded_at: str | None, guard_turn_instance_id: str | None, + runs: list[dict[str, Any]] | None = None, +) -> None: + """Copy the original refresh event order onto matching ACK candidates. + + The compact run clock is whole seconds. The decision owner compares this + event with admission; this reader only selects the bound original event. + """ + + admission_index = _admission_event_index( + events, goal_id=goal_id, agent_id=agent_id, + turn_instance_id=str(guard_turn_instance_id or "").strip(), + recorded_at=str(guard_recorded_at or "").strip(), + ) + for candidate in candidates: + turn_instance_id = _binding_text(candidate.get("turn_instance_id")) + evidence_index = _original_writeback_event_index( + events, runs, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id, + turn_instance_id=turn_instance_id, + ) + if evidence_index is None: + continue + event = events[evidence_index] + candidate["writeback_recorded_at"] = event.get("recorded_at") + candidate["writeback_goal_id"] = event.get("goal_id") + candidate["writeback_agent_id"] = event.get("agent_id") + candidate["writeback_turn_instance_id"] = event.get("run_id") + candidate["writeback_obligation_id"] = obligation_id + candidate["writeback_follows_admission"] = ( + admission_index is not None and evidence_index > admission_index + ) + + +def historical_ack_candidates_with_writeback_order( + newest_first_runs: list[dict[str, Any]] | None, *, + goal_id: str, agent_id: str, obligation_id: str | None, + guard_scoped: bool = True, runtime_root: Path | str | None = None, + source_route: Any = None, + guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, +) -> list[dict[str, Any]]: + """Project obligation candidates and attach their original writeback order.""" + from ...rollout_event_log import load_rollout_events, rollout_event_log_path + + selected = _binding_text(obligation_id) if guard_scoped else "" + candidates = autonomous_replan_ack_candidates_for_obligation( + newest_first_runs, goal_id=goal_id, agent_id=agent_id, obligation_id=selected or None) + route = source_route if isinstance(source_route, dict) else {} + root_text = runtime_root or route.get("runtime_root") + root = Path(str(root_text)) if root_text else None + if root is None or not selected: + return candidates + attach_historical_ack_writeback_order( + candidates, load_rollout_events(rollout_event_log_path(root, goal_id)), + goal_id=goal_id, agent_id=agent_id, obligation_id=selected, + guard_recorded_at=guard_recorded_at, guard_turn_instance_id=guard_turn_instance_id, + runs=newest_first_runs, + ) + return candidates + + def load_receipt_replan_ack_candidates( runtime_root: Path, *, goal_id: str, agent_id: str, obligation_id: str, + guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, ) -> list[dict[str, Any]]: """Read exact recovery candidates without widening ordinary status history.""" from ...history import load_index @@ -277,8 +463,11 @@ def load_receipt_replan_ack_candidates( runs, _ = load_index(runtime_root / "goals" / goal_id / "runs" / "index.jsonl") newest_first = [run for _, run in sorted(enumerate(runs), key=lambda item: (*chronology_key(item[1].get("generated_at")), item[0]), reverse=True)] - return autonomous_replan_ack_candidates_for_obligation(newest_first, - goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id) + return historical_ack_candidates_with_writeback_order( + newest_first, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id, + runtime_root=runtime_root, guard_recorded_at=guard_recorded_at, + guard_turn_instance_id=guard_turn_instance_id, + ) def latest_blocked_successor_frontier_identity( diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts index 894d37ba9d..748e4ca126 100644 --- a/loopx/control_plane/work_items/replan_semantics.ts +++ b/loopx/control_plane/work_items/replan_semantics.ts @@ -111,11 +111,28 @@ function historicalAckDelta( const ackTurn = typeof ack.turn_instance_id === "string" ? ack.turn_instance_id.trim() : ""; const generated = typeof ack.generated_at === "string" ? parseTodoTimestampMicros(ack.generated_at) : null; + // A generated_at that is already strictly later proves order on its own. + // The compact run clock is whole seconds, so a stamp inside the admission + // second can be either side of a fractional guard_recorded_at. That + // candidate needs the original refresh_state event, bound to this Goal, + // Agent, obligation, and ACK Turn, with both its recorded time and its + // log position after admission. Missing or conflicting order stays pending. + const admissionSecond = admitted / 1_000_000n * 1_000_000n; + const preciseLater = generated !== null && generated > admitted; + const sameSecond = generated !== null && generated % 1_000_000n === 0n && + generated >= admissionSecond && !preciseLater; + const written = typeof ack.writeback_recorded_at === "string" + ? parseTodoTimestampMicros(ack.writeback_recorded_at) : null; + const writebackAfterAdmission = sameSecond && written !== null && written > admitted && + ack.writeback_follows_admission === true && ack.writeback_goal_id === goal && + ack.writeback_agent_id === agent && ack.writeback_turn_instance_id === ackTurn && + ack.writeback_obligation_id === selected; + const afterAdmission = preciseLater || writebackAfterAdmission; const outcomes = strings(delta.outcomes); const satisfying = strings(delta.satisfying_outcomes); return ack.schema_version === "autonomous_replan_ack_v0" && ack.recorded === true && ack.goal_id === goal && ack.agent_id === agent && ackTurn && ackTurn !== guardTurn && - generated !== null && generated > admitted && + generated !== null && afterAdmission && delta.schema_version === "replan_semantic_delta_v0" && delta.accepted === true && delta.obligation_id === selected && outcomes.length > 0 && satisfying.length > 0 && outcomes.every(outcome => KNOWN_OUTCOMES.has(outcome)) && diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index 494bb176ad..22eee62fda 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -24,7 +24,7 @@ ) from ..todos.succession_warning import todo_succession_gap_items from .autonomous_replan_ack import ( - autonomous_replan_ack_candidates_for_obligation, + historical_ack_candidates_with_writeback_order, latest_monitor_replan_frontier_identity, watch_lane_continuation_todo_ids, ) @@ -294,9 +294,13 @@ def qualify_replan_writeback( ] } } - status_payload["receipt_bound_replan_ack_candidates"] = autonomous_replan_ack_candidates_for_obligation( + status_payload["receipt_bound_replan_ack_candidates"] = historical_ack_candidates_with_writeback_order( newest_first_runs, goal_id=goal_id, agent_id=safe_agent_id, - obligation_id=guard_semantic_replan_obligation_id if guard_scoped else None) + 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, + ) if capability_evidence is not None: status_payload["bounded_research_frontier"] = capability_evidence.frontier context = build_goal_frontier_projection_context_from_status( diff --git a/tests/control_plane/test_autonomous_replan_ack.py b/tests/control_plane/test_autonomous_replan_ack.py index e3a0c2bebd..70b0594896 100644 --- a/tests/control_plane/test_autonomous_replan_ack.py +++ b/tests/control_plane/test_autonomous_replan_ack.py @@ -8,6 +8,7 @@ from loopx.control_plane.work_items.autonomous_replan_ack import ( AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW, AUTONOMOUS_REPLAN_ACK_RECOVERY_CANDIDATE_LIMIT, + attach_historical_ack_writeback_order, autonomous_replan_ack_candidates_for_obligation, compact_autonomous_replan_ack, latest_autonomous_replan_ack_for_projection, @@ -325,3 +326,78 @@ def test_long_chain_trigger_checkpoint_survives_ack_compaction() -> None: assert compact["semantic_delta"]["trigger_checkpoints"] == [ {"kind": "long_todo_chain", "frontier_revision": frontier_revision} ] + + +def test_same_second_candidate_keeps_the_todo_bound_writeback_order() -> None: + turn = "guided-start:later" + run = { + "goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": turn, + "todo_id": "todo-original", + "settlement_identity": {"todo_id": "todo-original", "effect_id": "effect-later"}, + "autonomous_replan_ack": {"semantic_delta": {"obligation_id": LONG_CHAIN_OBLIGATION_ID}}, + } + admission = {"event_kind": "quota_should_run", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": "guided-start:original", "recorded_at": "2026-08-01T00:00:01.500000Z"} + # A Todo-bound refresh leaves the obligation field empty. The semantic + # delta and the Todo receipt identify the writeback. + todo_event = {"event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": turn, "todo_id": "todo-original", "recorded_at": "2026-08-01T00:00:01.900000Z", + "details": {"autonomous_replan_recorded": True, "replan_obligation_id": None, + "settlement_effect_id": "effect-later"}} + other_obligation = {"event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": turn, "recorded_at": "2026-08-01T00:00:01.100000Z", "details": { + "autonomous_replan_recorded": True, "replan_obligation_id": "replan-ffffffffffffffff"}} + candidate = {"turn_instance_id": turn, "generated_at": "2026-08-01T00:00:01Z"} + attach_historical_ack_writeback_order( + [candidate], [other_obligation, admission, todo_event], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[run], + ) + assert candidate["writeback_recorded_at"] == "2026-08-01T00:00:01.900000Z" + assert candidate["writeback_follows_admission"] is True + assert candidate["writeback_obligation_id"] == LONG_CHAIN_OBLIGATION_ID + mismatched = {"turn_instance_id": turn} + mismatched_event = {**todo_event, "details": {**todo_event["details"], "settlement_effect_id": "effect-other"}} + attach_historical_ack_writeback_order( + [mismatched], [admission, mismatched_event], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[run], + ) + assert "writeback_recorded_at" not in mismatched + sparse_run = { + "goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": turn, + "autonomous_replan_ack": {"semantic_delta": {"obligation_id": LONG_CHAIN_OBLIGATION_ID}}, + } + later_receipt = {"event_kind": "quota_should_run", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": turn, "todo_id": "todo-original", "recorded_at": "2026-08-01T00:00:01.200000Z", + "details": {"settlement_effect_id": "effect-later", "todo_id": "todo-original"}} + filled = {"turn_instance_id": turn} + attach_historical_ack_writeback_order( + [filled], [admission, later_receipt, todo_event], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[sparse_run], + ) + assert filled["writeback_recorded_at"] == todo_event["recorded_at"] + foreign = {"turn_instance_id": turn} + foreign_event = {**todo_event, "todo_id": "todo-other", + "details": {**todo_event["details"], "settlement_effect_id": "effect-other"}} + attach_historical_ack_writeback_order( + [foreign], [admission, later_receipt, foreign_event], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[sparse_run], + ) + assert "writeback_recorded_at" not in foreign + blank = {"turn_instance_id": turn} + blank_event = {**todo_event, "todo_id": "", "details": { + "autonomous_replan_recorded": True, "replan_obligation_id": None, "settlement_effect_id": None}} + attach_historical_ack_writeback_order( + [blank], [admission, later_receipt, blank_event], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[sparse_run], + ) + assert "writeback_recorded_at" not in blank diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index e5a420ed67..6bb924e7c4 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -9057,3 +9057,120 @@ def test_exact_later_ack_executes_original_todo_settlement_commands( rc, todo = _run_cli(registry, runtime, "todo", "list", "--goal-id", GOAL_ID, "--todo-id", SELECTED_REPLAN_TODO_ID) assert rc == 0 and todo["todo"]["status"] == "open", todo + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("order", [ + "after", "before", "time_after_log_before", "time_before_log_after", + "receipt_fill", "foreign_todo", "blank_identity", +]) +def test_same_second_historical_ack_requires_writeback_after_admission( + tmp_path: Path, provider: str, order: str, +) -> None: + project, runtime, registry = _write_fixture(tmp_path) + _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _initialize_git_checkout(project) + _initialize_fixture_authority(project, runtime, provider=provider) + original_turn = "turn-historical-same-second" + admitted = _bind_selected_replan_guard(registry, runtime, project, original_turn) + obligation = admitted["replan_action_packet"]["obligation_id"] + recorded_at = admitted["heartbeat_receipt"]["recorded_at"] + recorded = datetime.fromisoformat(recorded_at.replace("Z", "+00:00")) + later_turn = "later-accepted-same-second" + later_admitted = _bind_selected_replan_guard(registry, runtime, project, later_turn) + assert later_admitted["replan_action_packet"]["obligation_id"] == obligation + vision = project / "vision.json" + vision.write_text(json.dumps({ + "schema_version": "goal_vision_replan_contract_v0", + "state": "vision_patch_proposed", + "vision_patch": {"acceptance_summary": "Verified fixture artifact; original work remains open."}, + "todo_delta": [f"retain:{SELECTED_REPLAN_TODO_ID}"], + "path_delta": { + "outcome": "replan", + "prior_assumption": "Fixture work needs a verified next route.", + "observed_reality": "A fixture check supports continuing the existing work.", + "retained": ["Original requirements and the existing Todo."], + "evidence_refs": ["evidence:fixture-check"], + }, + }), encoding="utf-8") + rc, refreshed = _run_cli( + registry, runtime, "refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--todo-id", SELECTED_REPLAN_TODO_ID, "--turn-instance-id", later_turn, + "--classification", "bounded_replan_progress", "--delivery-batch-scale", "single_surface", + "--delivery-outcome", "outcome_progress", "--delivery-workspace-path", str(project), + "--delivery-boundary", "semantic_closeout", "--agent-vision-json", str(vision), + "--autonomous-replan-recorded", "--repair-delta-kind", "goal_vision_patch", + "--no-global-sync", "--suppress-external-sinks", + ) + assert rc == 0 and refreshed["appended"] is True, refreshed + assert refreshed["autonomous_replan_ack"]["semantic_delta"]["obligation_id"] == obligation + same_second = recorded.replace(microsecond=0).astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + index_path = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl" + rows = [json.loads(line) for line in index_path.read_text(encoding="utf-8").splitlines() if line.strip()] + matched_runs = [row for row in rows if row.get("turn_instance_id") == later_turn] + assert matched_runs + sparse_index = order in {"receipt_fill", "foreign_todo", "blank_identity"} + for row in matched_runs: + row["generated_at"] = same_second + source = Path(row["json_path"]) + payload = json.loads(source.read_text(encoding="utf-8")) + payload["generated_at"] = same_second + if sparse_index: + for record in (row, payload): + record.pop("todo_id", None) + record.pop("settlement_identity", None) + source.write_text(json.dumps(payload), encoding="utf-8") + index_path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + time_after = order in { + "after", "time_after_log_before", "receipt_fill", "foreign_todo", "blank_identity", + } + written_at = (recorded + timedelta(microseconds=1 if time_after else -1)).astimezone( + timezone.utc).isoformat().replace("+00:00", "Z") + log_path = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl" + events = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip()] + event = next(item for item in events + if item.get("event_kind") == "refresh_state" and item.get("run_id") == later_turn) + assert not str((event.get("details") or {}).get("replan_obligation_id") or "").strip() + assert event["details"]["autonomous_replan_recorded"] is True + assert event.get("todo_id") == SELECTED_REPLAN_TODO_ID + events.remove(event) + event["recorded_at"] = written_at + if order == "foreign_todo": + event["todo_id"] = "todo_other_binding" + event["details"]["settlement_effect_id"] = "effect-other" + if order == "blank_identity": + event.pop("todo_id", None) + event["details"]["settlement_effect_id"] = None + event["details"]["replan_obligation_id"] = None + admission_index = next(index for index, item in enumerate(events) + if item.get("event_kind") == "quota_should_run" and item.get("run_id") == original_turn + and item.get("recorded_at") == recorded_at) + log_after = order in { + "after", "time_before_log_after", "receipt_fill", "foreign_todo", "blank_identity", + } + events.insert(len(events) if log_after else admission_index, event) + log_path.write_text("".join(json.dumps(item) + "\n" for item in events), encoding="utf-8") + guard_args = ("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, + "--agent-id", AGENT_ID, "--turn-instance-id", original_turn, + "--todo-id", SELECTED_REPLAN_TODO_ID) + rc, recovery = _run_cli(registry, runtime, *guard_args) + decision = (recovery.get("replan_action_packet") or {}).get("decision") + if order not in {"after", "receipt_fill"}: + assert decision != "historical_ack_recorded", { + "rc": rc, "decision": decision, "error": recovery.get("error"), + "error_code": recovery.get("error_code"), + } + assert _spend_run_count(runtime) == 0 + return + assert rc == 0, recovery + assert decision == "historical_ack_recorded", recovery.get("replan_action_packet") + actions = recovery["interaction_contract"]["cli_channel"]["next_cli_actions"] + writeback = next(command for command in actions if "refresh-state" in command) + spend = next(command for command in actions if "spend-slot" in command) + before = _spend_run_count(runtime) + rc, written_payload = _run_generated_cli(writeback, registry_path=registry) + assert rc == 0 and written_payload["ok"] is True and written_payload["appended"] is True, written_payload + assert _spend_run_count(runtime) == before + rc, spent = _run_generated_cli(spend, registry_path=registry) + assert rc == 0 and spent["ok"] is True, spent + assert _spend_run_count(runtime) == before + 1 diff --git a/tests/control_plane_ts/replan_semantics.test.ts b/tests/control_plane_ts/replan_semantics.test.ts index 73a0a76d37..274fa81016 100644 --- a/tests/control_plane_ts/replan_semantics.test.ts +++ b/tests/control_plane_ts/replan_semantics.test.ts @@ -649,17 +649,25 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", ( const request = {guard_scoped: true, selected_obligation_id: id, transition_candidates: [candidate], goal_id: goal, agent_id: agent, guard_recorded_at: "2026-08-01T00:00:01Z", guard_turn_instance_id: guardTurn}; - assert.deepEqual(projectReplanSemantics({operation: "turn_transition", ...request}).semantic_delta, delta); - const obligation = projectReplanSemantics({operation: "receipt_bound_obligation", ...request, - current_obligation: null, replay_phase: "open"}).obligation as JsonObject; - assert.equal(obligation.obligation_id, id); - assert.equal(obligation.resolution_mode, "receipt_bound_replan_settlement"); - const packet = obligation.settlement_action_packet as JsonObject; - assert.equal(packet.decision, "historical_ack_recorded"); - assert.equal(packet.settlement_only, true); - assert.equal(packet.required_outcome, "durable_writeback_receipt"); - assert.deepEqual(packet.semantic_delta, delta); - assert.equal((packet.writeback_contract as JsonObject).preferred_input, "exact_historical_ack"); + const settled = (current: typeof request) => { + assert.deepEqual(projectReplanSemantics({operation: "turn_transition", ...current}).semantic_delta, delta); + const obligation = projectReplanSemantics({operation: "receipt_bound_obligation", ...current, + current_obligation: null, replay_phase: "open"}).obligation as JsonObject; + assert.equal(obligation.obligation_id, id); + assert.equal(obligation.resolution_mode, "receipt_bound_replan_settlement"); + const packet = obligation.settlement_action_packet as JsonObject; + assert.equal(packet.decision, "historical_ack_recorded"); + assert.equal(packet.settlement_only, true); + assert.equal(packet.required_outcome, "durable_writeback_receipt"); + assert.deepEqual(packet.semantic_delta, delta); + assert.equal((packet.writeback_contract as JsonObject).preferred_input, "exact_historical_ack"); + }; + const rejected = (current: typeof request) => { + assert.equal(projectReplanSemantics({operation: "turn_transition", ...current}).semantic_delta, null); + assert.throws(() => projectReplanSemantics({operation: "receipt_bound_obligation", ...current, + current_obligation: null, replay_phase: "open"}), /identity conflicts/); + }; + settled(request); const pending = projectReplanSemantics({operation: "receipt_bound_obligation", ...request, current_obligation: null, replay_phase: "settlement_pending"}).obligation as JsonObject; @@ -670,10 +678,45 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", ( for (const missingGuard of [{guard_scoped: false}, {goal_id: null}, {agent_id: null}, {guard_recorded_at: null}, {guard_turn_instance_id: null}]) { - const unbound = {...request, ...missingGuard}; - assert.equal(projectReplanSemantics({operation: "turn_transition", ...unbound}).semantic_delta, null); - assert.throws(() => projectReplanSemantics({operation: "receipt_bound_obligation", ...unbound, - current_obligation: null, replay_phase: "open"}), /identity conflicts/); + rejected({...request, ...missingGuard}); + } + + // The whole-second run clock cannot order two writes inside the admission + // second. A bound refresh_state event whose recorded time and log position + // are both after admission can. The later Turn keeps its own turn id. + const boundWriteback = (generated_at: string, writeback_recorded_at: string, follows = true) => ({ + historical_ack: {...historicalAck, generated_at, writeback_recorded_at, + writeback_follows_admission: follows, writeback_goal_id: goal, writeback_agent_id: agent, + writeback_turn_instance_id: laterTurn, writeback_obligation_id: id}, + }); + for (const guard_recorded_at of [ + "2026-08-01T00:00:01Z", "2026-08-01T00:00:01.500Z", "2026-08-01T00:00:01.123456Z", + ]) { + for (const generated_at of ["2026-08-01T00:00:01Z", "2026-08-01T08:00:01+08:00"]) { + settled({...request, guard_recorded_at, transition_candidates: [ + boundWriteback(generated_at, "2026-08-01T00:00:01.900000Z")]}); + rejected({...request, guard_recorded_at, transition_candidates: [ + {historical_ack: {...historicalAck, generated_at}}]}); + } + } + const fractionalAdmission = {...request, guard_recorded_at: "2026-08-01T00:00:01.500Z"}; + const sameSecondAck = boundWriteback("2026-08-01T00:00:01Z", "2026-08-01T00:00:01.900000Z"); + rejected({...fractionalAdmission, transition_candidates: [ + boundWriteback("2026-08-01T00:00:01Z", "2026-08-01T00:00:01.100Z")]}); + rejected({...fractionalAdmission, transition_candidates: [ + boundWriteback("2026-08-01T00:00:01Z", "2026-08-01T00:00:01.900000Z", false)]}); + for (const broken of [ + {writeback_goal_id: "goal-b"}, {writeback_agent_id: "peer"}, + {writeback_turn_instance_id: guardTurn}, {writeback_obligation_id: "replan-2222222222222222"}, + ]) { + rejected({...fractionalAdmission, transition_candidates: [ + {historical_ack: {...sameSecondAck.historical_ack, ...broken}}]}); + } + // A fractional ACK earlier in the admission second, and a previous whole + // second, stay pending even when a later event is attached. + for (const generated_at of ["2026-08-01T00:00:01.100Z", "2026-08-01T00:00:00Z"]) { + rejected({...fractionalAdmission, transition_candidates: [ + boundWriteback(generated_at, "2026-08-01T00:00:01.900000Z")]}); } const invalid = [ @@ -683,7 +726,7 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", ( {historical_ack: {...historicalAck, agent_id: "peer"}}, {historical_ack: {...historicalAck, turn_instance_id: guardTurn}}, {historical_ack: {...historicalAck, turn_instance_id: null}}, - {historical_ack: {...historicalAck, generated_at: "2026-08-01T00:00:01Z"}}, + {historical_ack: {...historicalAck, generated_at: "2026-08-01T00:00:00Z"}}, {historical_ack: {...historicalAck, generated_at: "invalid"}}, {historical_ack: {...historicalAck, semantic_delta: {...delta, schema_version: "wrong"}}}, {historical_ack: {...historicalAck, semantic_delta: {...delta, accepted: false}}}, @@ -693,10 +736,7 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", ( {historical_ack: {...historicalAck, semantic_delta: {...delta, satisfying_outcomes: ["new_surface"]}}}, ]; for (const badCandidate of invalid) { - const changed = {...request, transition_candidates: [badCandidate]}; - assert.equal(projectReplanSemantics({operation: "turn_transition", ...changed}).semantic_delta, null); - assert.throws(() => projectReplanSemantics({operation: "receipt_bound_obligation", ...changed, - current_obligation: null, replay_phase: "open"}), /identity conflicts/); + rejected({...request, transition_candidates: [badCandidate]}); } });