diff --git a/loopx/control_plane/quota/heartbeat_receipt_identity.ts b/loopx/control_plane/quota/heartbeat_receipt_identity.ts index a7da9f7bb1..3ac6fa63f7 100644 --- a/loopx/control_plane/quota/heartbeat_receipt_identity.ts +++ b/loopx/control_plane/quota/heartbeat_receipt_identity.ts @@ -196,6 +196,34 @@ export function selectEffectiveHeartbeatReceipt( : entries.at(-1)!.value; } +/** + * The first bound receipt for one Turn, used only as the admission clock. + * + * `selectEffectiveHeartbeatReceipt` still returns the latest bound receipt so + * review and work content stay current. A later same-Turn upgrade must not + * move the historical-ACK admission time or log position. Callers pass the + * GoalRef-filtered receipt list; this reduction does not widen that scope. + * Conflicting bindings fail closed, the same way the effective reduction does. + */ +export function selectAdmissionHeartbeatReceipt( + goalId: string, + agentId: string, + entries: readonly { fact: HeartbeatReceiptFact; value: Value }[], +): Value | null { + const identities = new Map(); + for (const entry of entries) { + const binding = heartbeatReceiptBinding(goalId, agentId, entry.fact); + if (!binding || identities.has(binding.identity_key)) continue; + identities.set(binding.identity_key, entry.value); + } + if (identities.size > 1) { + throw receiptIdentityConflict( + "heartbeat receipt has conflicting settlement identities for the same goal, agent, and turn", + ); + } + return identities.size === 1 ? [...identities.values()][0]! : null; +} + /** Reentry can qualify work on the original binding, never replace its authority. * The caller commits this append-only projection under the receipt-log lock. */ export function heartbeatWorkRequalification( diff --git a/loopx/control_plane/quota/live_decision.py b/loopx/control_plane/quota/live_decision.py index fde3e9c491..f38e888c22 100644 --- a/loopx/control_plane/quota/live_decision.py +++ b/loopx/control_plane/quota/live_decision.py @@ -67,12 +67,16 @@ def _receipt_bound_guard_fields( obligation_id and isinstance(guard, Mapping) and guard.get("scope") == "turn_guard" and guard.get("selected_obligation_id") == obligation_id ) + # The effective receipt stays the latest content. The admission clock is the + # first bound receipt already selected by the GoalRef-filtered readback. + admission_recorded_at = getattr(readback, "admission_recorded_at", None) return { "receipt_bound_replan_guard_scoped": guard_scoped, "receipt_bound_replan_execution_pending": bool( guard_scoped and readback and readback.replan_execution_pending ), - "receipt_bound_guard_recorded_at": receipt.get("recorded_at"), + "receipt_bound_guard_recorded_at": admission_recorded_at or receipt.get("recorded_at"), + "receipt_bound_admission_event_id": getattr(readback, "admission_event_id", None), "receipt_bound_guard_turn_instance_id": identity.turn_instance_id if identity is not None else None, "receipt_bound_replan_review": guard.get("selected_review_source") if isinstance(guard, Mapping) else None, "receipt_bound_successor_replan": bool(getattr(readback, "successor_replan_pending", False)), @@ -786,6 +790,7 @@ def build_live_quota_should_run_decision( receipt_bound_guard_fields = _receipt_bound_guard_fields( settlement_readback, receipt_bound_replan_obligation_id, ) + admission_event_id = receipt_bound_guard_fields.pop("receipt_bound_admission_event_id") if ( receipt_bound_guard_fields["receipt_bound_replan_guard_scoped"] and receipt_bound_replay_phase is ReceiptBoundReplayPhase.OPEN @@ -797,7 +802,8 @@ def build_live_quota_should_run_decision( 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"]) + guard_turn_instance_id=receipt_bound_guard_fields["receipt_bound_guard_turn_instance_id"], + admission_event_id=admission_event_id) fresh_operator_inbox_read = _fresh_operator_inbox_read_required( turn_start_hook_dispatch ) diff --git a/loopx/control_plane/quota/settlement.py b/loopx/control_plane/quota/settlement.py index c5d282fd63..dd79812c63 100644 --- a/loopx/control_plane/quota/settlement.py +++ b/loopx/control_plane/quota/settlement.py @@ -181,6 +181,8 @@ class QuotaSettlementReadback: heartbeat_reentry_qualification: dict[str, Any] | None = None successor_replan_pending: bool = False replan_execution_pending: bool = False + admission_recorded_at: str | None = None + admission_event_id: str | None = None def render_owed_host_command(argv: list[str]) -> str: @@ -315,6 +317,14 @@ def _optional_readback_record(value: Any) -> dict[str, Any] | None: return dict(value) +def _optional_readback_text(value: Any) -> str | None: + if value is None: + return None + if not isinstance(value, str) or not value.strip(): + raise RuntimeError("TypeScript quota settlement readback result shape mismatch") + return value + + def _semantic_replan_guard(value: Any) -> dict[str, Any] | None: guard = _optional_readback_record(value) if guard is None: @@ -564,4 +574,6 @@ def read_heartbeat_settlement( if replay_phase is not None else None ), + admission_recorded_at=_optional_readback_text(payload.get("admission_recorded_at")), + admission_event_id=_optional_readback_text(payload.get("admission_event_id")), ) diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index f3064dbf36..d4ae51bc68 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -61,6 +61,7 @@ import { normalizeHeartbeatReplanObligationId as normalizeReplanObligationId, normalizeHeartbeatTodoId as normalizeTodoId, optionalHeartbeatString as optionalString, + selectAdmissionHeartbeatReceipt, selectEffectiveHeartbeatReceipt, heartbeatWorkRequalification, type HeartbeatReceiptFact, @@ -744,6 +745,24 @@ function effectiveHeartbeatReceipt( : selectEffectiveHeartbeatReceipt(identity.goal_id, identity.agent_id, entries); } +/** First bound receipt in the same already filtered Turn list. */ +function admissionHeartbeatReceipt( + events: readonly JsonObject[], + identity: Pick, +): JsonObject | null { + const entries: { fact: HeartbeatReceiptFact; value: JsonObject }[] = []; + for (const event of events) { + if (event.event_kind !== "quota_should_run") continue; + if (optionalString(event.goal_id) !== identity.goal_id) continue; + if (optionalString(event.agent_id) !== identity.agent_id) continue; + if (optionalString(event.run_id) !== identity.turn_instance_id) continue; + entries.push({ fact: heartbeatReceiptFactFromEvent(event), value: event }); + } + return entries.length === 0 + ? null + : selectAdmissionHeartbeatReceipt(identity.goal_id, identity.agent_id, entries); +} + function writebackResult( identity: SettlementIdentity, run: JsonObject | null, @@ -1376,6 +1395,7 @@ function readQuotaSettlementFromRequest( quotaOwnerOwnsProjection(request.owner, run.goal_ref) ); const heartbeatReceipt = effectiveHeartbeatReceipt(events, identity); + const admissionReceipt = admissionHeartbeatReceipt(events, identity); if (heartbeatReceipt === null) { return failedReadback( failedIdentity( @@ -1533,6 +1553,10 @@ function readQuotaSettlementFromRequest( ), spend_run: includeRecords ? spendRun : null, heartbeat_receipt: includeRecords ? heartbeatReceipt : null, + admission_recorded_at: typeof admissionReceipt?.recorded_at === "string" + && admissionReceipt.recorded_at.trim() ? admissionReceipt.recorded_at : null, + admission_event_id: typeof admissionReceipt?.event_id === "string" + && admissionReceipt.event_id.trim() ? admissionReceipt.event_id : null, writeback_event: includeRecords ? writebackEvent : null, spend_event: includeRecords ? spendEvent : null, completion_event: includeRecords ? completionEvent : null, diff --git a/loopx/control_plane/work_items/autonomous_replan_ack.py b/loopx/control_plane/work_items/autonomous_replan_ack.py index 2c16a75ccc..06f5109f17 100644 --- a/loopx/control_plane/work_items/autonomous_replan_ack.py +++ b/loopx/control_plane/work_items/autonomous_replan_ack.py @@ -274,11 +274,30 @@ def _event_details(event: dict[str, Any]) -> dict[str, Any]: def _admission_event_index( events: list[dict[str, Any]], *, goal_id: str, agent_id: str, - turn_instance_id: str, recorded_at: str, + turn_instance_id: str, recorded_at: str, event_id: str | None = None, ) -> int | None: - if not turn_instance_id or not recorded_at: + """Log position of the Turn's original bound admission. + + The settlement readback names that event after GoalRef filtering. Matching + the id keeps a retired Goal instance that reused this Turn id out of the + order. Callers without an id use the first row with the admission time. + """ + + if not turn_instance_id: + return None + if event_id: + for index, event in enumerate(events): + if ( + event.get("event_id") == event_id + and 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 + ): + return index + return None + if not recorded_at: return None - found: int | None = None for index, event in enumerate(events): if ( event.get("event_kind") == "quota_should_run" @@ -287,8 +306,8 @@ def _admission_event_index( and event.get("run_id") == turn_instance_id and event.get("recorded_at") == recorded_at ): - found = index - return found + return index + return None def _binding_text(value: Any) -> str: @@ -406,6 +425,7 @@ def attach_historical_ack_writeback_order( 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, + admission_event_id: str | None = None, ) -> None: """Copy the original refresh event order onto matching ACK candidates. @@ -417,6 +437,7 @@ def attach_historical_ack_writeback_order( 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(), + event_id=str(admission_event_id or "").strip() or None, ) for candidate in candidates: turn_instance_id = _binding_text(candidate.get("turn_instance_id")) @@ -443,6 +464,7 @@ def historical_ack_candidates_with_writeback_order( 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, + admission_event_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 @@ -459,7 +481,7 @@ def historical_ack_candidates_with_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, + runs=newest_first_runs, admission_event_id=admission_event_id, ) return candidates @@ -467,6 +489,7 @@ def historical_ack_candidates_with_writeback_order( 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, + admission_event_id: str | None = None, ) -> list[dict[str, Any]]: """Read exact recovery candidates without widening ordinary status history.""" from ...history import load_index @@ -479,6 +502,7 @@ def load_receipt_replan_ack_candidates( 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, + admission_event_id=admission_event_id, ) diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index 22eee62fda..9bc1804e1f 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -233,6 +233,7 @@ def qualify_replan_writeback( receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, Any] | None = None, + admission_event_id: str | None = None, replan_source_route: Mapping[str, Any] | None = None, replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None = None, ) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: @@ -300,6 +301,7 @@ def qualify_replan_writeback( source_route=replan_source_route, guard_recorded_at=receipt_bound_guard_recorded_at, guard_turn_instance_id=receipt_bound_guard_turn_instance_id, + admission_event_id=admission_event_id, ) if capability_evidence is not None: status_payload["bounded_research_frontier"] = capability_evidence.frontier @@ -456,6 +458,7 @@ def enforce_open_replan_writeback( receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, Any] | None = None, + admission_event_id: str | None = None, todo_fields: dict[str, Any] | None = None, external_progress_review: Mapping[str, Any] | None = None, capability_evidence: CapabilityReplanEvidence | None = None, @@ -493,6 +496,7 @@ def enforce_open_replan_writeback( receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, receipt_bound_replan_review=receipt_bound_replan_review, + admission_event_id=admission_event_id, replan_source_route=replan_source_route, replan_explore_reader=replan_explore_reader, ) if not obligation: @@ -542,6 +546,7 @@ def qualify_refresh_replan_writeback( receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, Any] | None = None, + admission_event_id: str | None = None, newest_first_runs: list[dict[str, Any]], state_text: str, goal_id: str, @@ -629,6 +634,7 @@ def qualify_refresh_replan_writeback( receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, receipt_bound_replan_review=receipt_bound_replan_review, + admission_event_id=admission_event_id, replan_source_route=replan_source_route, replan_explore_reader=replan_explore_reader, ) if semantic_delta: diff --git a/loopx/state_refresh.py b/loopx/state_refresh.py index 2859286fa8..a175ab4d07 100644 --- a/loopx/state_refresh.py +++ b/loopx/state_refresh.py @@ -1155,7 +1155,15 @@ def read_explore_context(read_goal_id: str, read_agent_id: str | None): settlement_guard_scoped=( settlement_replan_guard.get("scope") == "turn_guard" ), - receipt_bound_guard_recorded_at=(settlement_readback.heartbeat_receipt or {}).get("recorded_at") if settlement_readback else None, + receipt_bound_guard_recorded_at=( + settlement_readback.admission_recorded_at + if settlement_readback is not None and settlement_readback.admission_recorded_at + else (settlement_readback.heartbeat_receipt or {}).get("recorded_at") + if settlement_readback else None + ), + admission_event_id=( + settlement_readback.admission_event_id if settlement_readback is not None else None + ), receipt_bound_guard_turn_instance_id=(settlement_identity.turn_instance_id if settlement_identity else None), receipt_bound_replan_review=settlement_replan_guard.get("selected_review_source"), settlement_guard_semantic_replan_obligation_id=( diff --git a/tests/control_plane/test_autonomous_replan_ack.py b/tests/control_plane/test_autonomous_replan_ack.py index 70b0594896..551a44ceba 100644 --- a/tests/control_plane/test_autonomous_replan_ack.py +++ b/tests/control_plane/test_autonomous_replan_ack.py @@ -401,3 +401,63 @@ def test_same_second_candidate_keeps_the_todo_bound_writeback_order() -> None: runs=[sparse_run], ) assert "writeback_recorded_at" not in blank + + +def test_same_turn_receipt_upgrade_keeps_writeback_after_original_admission() -> None: + """A later same-Turn upgrade must not become the admission log index. + + The compact ACK stamp is the admission second. Its refresh writeback is + after the original quota_should_run and before the upgrade. Passing the + upgrade's recorded_at, which is what the latest receipt exposes, still + has to order that writeback after the first bound receipt. + """ + + turn = "guided-start:later" + guard_turn = "guided-start:original" + binding = { + "replan_obligation_id": LONG_CHAIN_OBLIGATION_ID, + "settlement_effect_id": "effect-original", + } + retired = { + "event_kind": "quota_should_run", "event_id": "evt-retired", + "goal_id": GOAL_ID, "agent_id": AGENT_ID, "run_id": guard_turn, + "recorded_at": "2026-07-01T00:00:00.000000Z", + "goal_ref": { + "goal_id": GOAL_ID, + "goal_instance_id": "ginst_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + }, + "details": { + "replan_obligation_id": "replan-ffffffffffffffff", + "settlement_effect_id": "effect-retired", + }, + } + admission = { + "event_kind": "quota_should_run", "event_id": "evt-admission", + "goal_id": GOAL_ID, "agent_id": AGENT_ID, "run_id": guard_turn, + "recorded_at": "2026-08-01T00:00:01.500000Z", "details": binding, + } + upgrade = { + "event_kind": "quota_should_run", "event_id": "evt-upgrade", + "goal_id": GOAL_ID, "agent_id": AGENT_ID, "run_id": guard_turn, + "recorded_at": "2026-08-01T00:00:05.000000Z", + "causality": {"source_event_id": "evt-admission", "caused_by": "evt-admission"}, + "details": {**binding, "settlement_receipt_revision": "work_admission"}, + } + todo_event = { + "event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": turn, "recorded_at": "2026-08-01T00:00:01.900000Z", + "details": { + "autonomous_replan_recorded": True, + "replan_obligation_id": LONG_CHAIN_OBLIGATION_ID, + }, + } + candidate = {"turn_instance_id": turn, "generated_at": "2026-08-01T00:00:01Z"} + attach_historical_ack_writeback_order( + [candidate], [retired, admission, todo_event, upgrade], + goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=upgrade["recorded_at"], guard_turn_instance_id=guard_turn, + admission_event_id=admission["event_id"], + ) + assert candidate["writeback_recorded_at"] == todo_event["recorded_at"] + assert candidate["writeback_follows_admission"] is True + assert candidate["writeback_obligation_id"] == LONG_CHAIN_OBLIGATION_ID diff --git a/tests/control_plane/test_effect_turn_live_quota_decision.py b/tests/control_plane/test_effect_turn_live_quota_decision.py index bc02deab96..23a75384df 100644 --- a/tests/control_plane/test_effect_turn_live_quota_decision.py +++ b/tests/control_plane/test_effect_turn_live_quota_decision.py @@ -55,6 +55,18 @@ def test_receipt_guard_fields_use_the_typed_identity_and_guard( assert fields["receipt_bound_replan_execution_pending"] is expected_pending assert fields["receipt_bound_guard_turn_instance_id"] == "original-turn" assert fields["receipt_bound_guard_recorded_at"] == "2026-08-01T00:00:00Z" + assert fields["receipt_bound_admission_event_id"] is None + upgraded = _receipt_bound_guard_fields(SimpleNamespace( + semantic_replan_guard={"scope": "turn_guard", "selected_obligation_id": selected}, + identity=SimpleNamespace(value=SimpleNamespace(turn_instance_id="original-turn")), + heartbeat_receipt={"recorded_at": "2026-08-01T02:00:00Z"}, + admission_recorded_at="2026-08-01T00:00:00Z", + admission_event_id="evt-admission", + successor_replan_pending=False, + replan_execution_pending=execution_pending, + ), obligation) + assert upgraded["receipt_bound_guard_recorded_at"] == "2026-08-01T00:00:00Z" + assert upgraded["receipt_bound_admission_event_id"] == "evt-admission" @pytest.mark.parametrize("binding", ["todo", "autonomous_replan", "unbound"]) diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index 7c98cd6960..e72fa9a67a 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -33,7 +33,11 @@ ) from loopx.heartbeat_prompt import build_heartbeat_prompt from loopx.paths import shell_selected_global_registry -from loopx.rollout_event_log import build_rollout_event +from loopx.rollout_event_log import ( + append_rollout_event, + build_rollout_event, + rollout_event_log_path, +) from tests.control_plane.canonical_authority_fixture import ( initialize_canonical_source_fixture, read_fixture_todos, @@ -9381,3 +9385,112 @@ def test_same_second_historical_ack_requires_writeback_after_admission( 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 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_same_turn_receipt_upgrade_keeps_historical_ack_admission( + tmp_path: Path, provider: str, +) -> None: + """A same-Turn review upgrade must not move the historical ACK admission clock. + + Turn A is admitted at T0 on one settlement identity. Turn B accepts that + review after T0. A review_guard_upgrade then appends another + quota_should_run for A at T2, after the ACK, caused by the original + receipt. The upgrade stays the effective receipt. The ACK still settles + against the original admission. + """ + + 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-ack-after-upgrade" + admitted = _bind_selected_replan_guard(registry, runtime, project, original_turn) + original_identity = admitted["heartbeat_receipt"]["settlement_identity"] + obligation = admitted["replan_action_packet"]["obligation_id"] + recorded = datetime.fromisoformat( + admitted["heartbeat_receipt"]["recorded_at"].replace("Z", "+00:00") + ) + ack_at = (recorded + timedelta(seconds=30)).isoformat() + upgrade_at = ( + (recorded + timedelta(hours=1)) + .astimezone(timezone.utc) + .isoformat() + .replace("+00:00", "Z") + ) + assert datetime.fromisoformat(upgrade_at.replace("Z", "+00:00")) > datetime.fromisoformat(ack_at) + runs_dir = runtime / "goals" / GOAL_ID / "runs" + runs_dir.mkdir(parents=True, exist_ok=True) + run = { + "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "turn_instance_id": "later-accepted-upgrade", + "generated_at": ack_at, + "classification": "bounded_replan_progress", + "autonomous_replan_ack": { + "schema_version": "autonomous_replan_ack_v0", "recorded": True, + "source": "refresh_state", + "semantic_delta": { + "schema_version": "replan_semantic_delta_v0", + "accepted": True, "obligation_id": obligation, + "outcomes": ["fresh_vision_path_outcome"], + "satisfying_outcomes": ["fresh_vision_path_outcome"], + }, + }, + } + source = runs_dir / "later-accepted-upgrade.json" + source.write_text(json.dumps(run)) + markdown = source.with_suffix(".md") + markdown.write_text("# Accepted independent historical review\n") + with (runs_dir / "index.jsonl").open("a", encoding="utf-8") as stream: + stream.write(json.dumps({ + **run, "json_path": str(source), "markdown_path": str(markdown), + }) + "\n") + receipts = _heartbeat_receipt_events(runtime, original_turn) + assert len(receipts) == 1 + original_event = receipts[0] + upgrade = json.loads(json.dumps(original_event)) + upgrade["event_id"] = f"upgrade-{original_event['event_id']}" + upgrade["recorded_at"] = upgrade_at + upgrade["summary"] = "same-Turn review guard upgraded without rebinding" + upgrade["causality"] = { + "source_event_id": original_event["event_id"], + "caused_by": original_event["event_id"], + } + upgrade["details"] = { + **upgrade["details"], + "settlement_receipt_revision": "review_guard_upgrade", + } + append_rollout_event(rollout_event_log_path(runtime, GOAL_ID), upgrade) + 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") + assert rc == 0, { + "reason": recovery.get("reason"), + "error_code": recovery.get("error_code"), + "decision": decision, + "effective_action": recovery.get("effective_action"), + } + assert recovery["heartbeat_receipt"]["settlement_identity"] == original_identity + assert recovery["heartbeat_receipt"]["event_id"] == upgrade["event_id"] + assert recovery["heartbeat_receipt"]["recorded_at"] == upgrade_at + assert decision == "historical_ack_recorded", { + "decision": decision, + "error": recovery.get("error"), + "error_code": recovery.get("error_code"), + "effective_action": recovery.get("effective_action"), + } + 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 = _run_generated_cli(writeback, registry_path=registry) + assert rc == 0 and written["ok"] is True and written["appended"] is True, written + assert written["settlement_identity"] == original_identity + 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/quota_settlement_readback.test.ts b/tests/control_plane_ts/quota_settlement_readback.test.ts index 9a50f9f0dc..3c3ebf646a 100644 --- a/tests/control_plane_ts/quota_settlement_readback.test.ts +++ b/tests/control_plane_ts/quota_settlement_readback.test.ts @@ -626,6 +626,55 @@ test("pending closeout recovers positively admitted replan work without creating } finally {await rm(root, {recursive: true, force: true});} }); +test("receipt upgrade admission stays on the admitted Goal instance", async () => { + const currentRef = {goal_id: goalId, goal_instance_id: instanceA}; + const root = await fixture({goalRef: currentRef}); + try { + const log = join(root, "goals", goalId, "rollout-event-log.jsonl"); + const current = JSON.parse((await readFile(log, "utf8")).trim()) as Record; + const details = current.details as Record; + const retiredTodo = "todo_retired_instance"; + const retiredIdentity = settlementIdentity({ + goal_id: goalId, agent_id: agentId, todo_id: retiredTodo, turn_instance_id: turnId, + }); + const retired = { + ...current, event_id: "event-retired", recorded_at: "2026-01-01T00:00:00Z", + goal_ref: {goal_id: goalId, goal_instance_id: instanceB}, + details: {todo_id: retiredTodo, settlement_effect_id: retiredIdentity.effect_id}, + }; + const admitted = { + ...current, event_id: "event-admitted", recorded_at: "2026-02-01T00:00:00Z", + }; + const upgraded = { + ...current, event_id: "event-upgraded", recorded_at: "2026-02-01T02:00:00Z", + causality: {source_event_id: "event-admitted", caused_by: "event-admitted"}, + details: {...details, settlement_receipt_revision: "review_guard_upgrade"}, + }; + await writeFile(log, [retired, admitted, upgraded].map(event => JSON.stringify(event)).join("\n") + "\n"); + await withSourceAdmission(root, instanceA, instanceA, async binding => { + const result = await readQuotaSettlement(request(root, binding)); + assert.equal(result.found, true); + assert.equal(result.admission_recorded_at, "2026-02-01T00:00:00Z"); + assert.equal(result.admission_event_id, "event-admitted"); + const receipt = result.heartbeat_receipt as {event_id: string, recorded_at: string}; + assert.equal(receipt.event_id, "event-upgraded"); + assert.equal(receipt.recorded_at, "2026-02-01T02:00:00Z"); + }); + const sameBinding = { + ...retired, + details: {todo_id: todoId, settlement_effect_id: identity.effect_id}, + }; + await writeFile(log, [sameBinding, admitted, upgraded].map(event => JSON.stringify(event)).join("\n") + "\n"); + await withSourceAdmission(root, instanceA, instanceA, async binding => { + const result = await readQuotaSettlement(request(root, binding)); + assert.equal(result.admission_recorded_at, admitted.recorded_at); + assert.equal(result.admission_event_id, "event-admitted"); + }); + } finally { + await rm(root, {recursive: true, force: true}); + } +}); + test("pending closeout cannot adopt another Goal instance's receipts", async () => { const root = await fixture({goalRef: {goal_id: goalId, goal_instance_id: instanceA}}); try {