diff --git a/loopx/cli_commands/project_lifecycle_refresh_state.py b/loopx/cli_commands/project_lifecycle_refresh_state.py index 0ec54e9709..ab52f3da64 100644 --- a/loopx/cli_commands/project_lifecycle_refresh_state.py +++ b/loopx/cli_commands/project_lifecycle_refresh_state.py @@ -822,6 +822,11 @@ def handle_refresh_state_command( replan_obligation_id=getattr( args, "replan_obligation_id", None ), + # The write may be addressed through the retained Todo while + # quota should-run bound this Turn to its semantic replan. + # Read back the immutable guard identity instead of treating + # that supported command shape as a second binding. + resolve_original_binding=True, registry_path=registry_path, goal_ref=goal_ref, ) diff --git a/loopx/control_plane/quota/heartbeat_receipt.py b/loopx/control_plane/quota/heartbeat_receipt.py index b228abd519..0509b87b9a 100644 --- a/loopx/control_plane/quota/heartbeat_receipt.py +++ b/loopx/control_plane/quota/heartbeat_receipt.py @@ -1,5 +1,4 @@ from __future__ import annotations -from .effective_action import EffectiveAction from collections.abc import Callable, Mapping from pathlib import Path @@ -12,6 +11,7 @@ rollout_event_log_path, ) from ..todos.contract import normalize_todo_id, normalize_todo_replan_obligation_id +from .effective_action import EffectiveAction from .effect_program import SettlementBindingKind, SettlementIdentity from .error_codes import HeartbeatReceiptIdentityConflictError from .settlement_workspace_causality import ( @@ -604,10 +604,18 @@ def requalify_bound_heartbeat_receipt( if not isinstance(qualified_details, Mapping): raise RuntimeError("TypeScript heartbeat work qualification details missing") event_id = str(original.get("event_id") or "") + receipt_revision = str( + qualified_details.get("settlement_receipt_revision") or "" + ) + summary = ( + "same-Turn review guard upgraded without rebinding" + if receipt_revision == "review_guard_upgrade" + else "same-Turn work admission requalified without rebinding" + ) corrected = build_rollout_event( goal_id=goal_id, goal_ref=goal_ref, event_kind="quota_should_run", agent_id=agent_id, todo_id=todo_id, run_id=turn_instance_id, status=status, - summary="same-Turn work admission requalified without rebinding", + summary=summary, source_event_id=event_id, caused_by=event_id, details=dict(qualified_details), ) _append_rollout_event_line(log_path, corrected) diff --git a/loopx/control_plane/quota/prior_turn_closeout.ts b/loopx/control_plane/quota/prior_turn_closeout.ts index 9f07b8416e..dce35507da 100644 --- a/loopx/control_plane/quota/prior_turn_closeout.ts +++ b/loopx/control_plane/quota/prior_turn_closeout.ts @@ -30,6 +30,8 @@ export interface PriorHostTurnCloseoutCandidate extends JsonObject { /** The Todo id or autonomous replan obligation id, per `binding_kind`. */ binding_id: string; settlement_effect_id: string | null; + /** The effective guard admitted an autonomous replan under this binding. */ + admitted_replan?: true; /** The effective guard admitted a replan under this Todo's settlement identity. */ admitted_todo_replan?: true; } @@ -43,6 +45,7 @@ function candidate( binding: HeartbeatReceiptBinding, turnInstanceId: string, fact: HeartbeatReceiptFact, + admittedReplan: boolean, admittedTodoReplan: boolean, ): PriorHostTurnCloseoutCandidate { return { @@ -51,15 +54,16 @@ function candidate( binding_kind: binding.binding_kind, binding_id: binding.binding_id, settlement_effect_id: binding.settlement_effect_id, + ...(admittedReplan ? {admitted_replan: true as const} : {}), ...(admittedTodoReplan ? {admitted_todo_replan: true as const} : {}), }; } /** - * Select prior Turns eligible for closeout readback. A Todo-bound replan - * carries the Todo settlement identity and a separate semantic obligation. - * It did not deliver a Todo, so its closeout marker can be false. Fresh - * admission requires a verified outstanding writeback for this binding. + * Select prior Turns eligible for closeout readback. An admitted replan may + * carry either its legacy Todo settlement identity or its autonomous-replan + * identity. It did not deliver a Todo, so its closeout marker can be false. + * Fresh admission requires a verified outstanding writeback for this binding. * Explicit pending-closeout discovery can also find admitted replans before * writeback, whether their settlement identity is a Todo or an obligation. * @@ -120,9 +124,11 @@ export function selectCloseoutCandidates( if (binding === null) continue; const admittedReplan = admitsAutonomousReplan(effective, fact); const admittedTodoReplan = admittedReplan && binding.binding_kind === "todo"; - if (!fact.closeout_required && !admittedTodoReplan && + if (!fact.closeout_required && !admittedReplan && !(includeUnwrittenReplans && admittedReplan)) continue; - candidates.push({candidate: candidate(binding, turnInstanceId, fact, admittedTodoReplan), + candidates.push({candidate: candidate( + binding, turnInstanceId, fact, admittedReplan, admittedTodoReplan, + ), requireWritebackForRecovery: !fact.closeout_required && !includeUnwrittenReplans}); } return {candidates, turnsValidated: validated}; diff --git a/loopx/control_plane/quota/settlement_cli.py b/loopx/control_plane/quota/settlement_cli.py index 77f179f741..6883239ab5 100644 --- a/loopx/control_plane/quota/settlement_cli.py +++ b/loopx/control_plane/quota/settlement_cli.py @@ -1,9 +1,9 @@ """CLI rollout helpers for heartbeat settlement identity and receipt wiring.""" from __future__ import annotations -from .effective_action import EffectiveAction import argparse +import hashlib from collections.abc import Mapping from pathlib import Path @@ -12,14 +12,18 @@ normalize_todo_replan_obligation_id, ) from ..work_items.autonomous_replan_obligation import ( + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID, + AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION, replan_obligation_id_from_packet, ) from .effect_program import SettlementIdentity +from .effective_action import EffectiveAction from .error_codes import HeartbeatReceiptIdentityConflictError from .heartbeat_receipt import ( heartbeat_receipt_view, - upgrade_identityless_heartbeat_receipt, requalify_bound_heartbeat_receipt, + upgrade_identityless_heartbeat_receipt, ) from .settlement import ( QuotaSettlementReadback, @@ -47,22 +51,38 @@ def reconcile_existing_heartbeat_receipt( receipt = existing receipt_status = "replayed" receipt_appended = False - rollout_todo_id = quota_rollout_todo_id(payload, args) - rollout_replan_obligation_id = quota_rollout_replan_obligation_id(payload, args) - if rollout_todo_id or rollout_replan_obligation_id: - existing_details_value = receipt.get("details") - existing_details = ( - existing_details_value - if isinstance(existing_details_value, Mapping) - else {} - ) - existing_todo_id = normalize_todo_id(existing_details.get("todo_id")) - existing_replan_obligation_id = normalize_todo_replan_obligation_id( - existing_details.get("replan_obligation_id") + existing_details_value = receipt.get("details") + existing_details = ( + existing_details_value + if isinstance(existing_details_value, Mapping) + else {} + ) + existing_todo_id = normalize_todo_id(existing_details.get("todo_id")) + existing_replan_obligation_id = normalize_todo_replan_obligation_id( + existing_details.get("replan_obligation_id") + ) + existing_effect_id = str( + existing_details.get("settlement_effect_id") or "" + ).strip() + receipt_has_bound_identity = bool( + (existing_todo_id or existing_replan_obligation_id) + and existing_effect_id + ) + if receipt_has_bound_identity: + # A committed heartbeat receipt is the authority for this Turn's + # settlement identity. The current projection can rotate from Todo + # delivery into autonomous replan (or the reverse) while the host is + # interrupted, but that later projection must not rebind the original + # effect. Explicit retry arguments are checked below against the + # receipt and its retained planning selection. + rollout_todo_id = existing_todo_id + rollout_replan_obligation_id = existing_replan_obligation_id + else: + rollout_todo_id = quota_rollout_todo_id(payload, args) + rollout_replan_obligation_id = quota_rollout_replan_obligation_id( + payload, args ) - existing_effect_id = str( - existing_details.get("settlement_effect_id") or "" - ).strip() + if rollout_todo_id or rollout_replan_obligation_id: expected_effect_id = SettlementIdentity( goal_id=args.goal_id, agent_id=args.agent_id, @@ -70,7 +90,7 @@ def reconcile_existing_heartbeat_receipt( turn_instance_id=turn_instance_id, replan_obligation_id=rollout_replan_obligation_id, ).effect_id - if (existing_todo_id or existing_replan_obligation_id) and existing_effect_id: + if receipt_has_bound_identity: # A fully settled Turn owns its immutable receipt regardless of a # later explicit CLI choice. The live decision has already read # the exact settlement and projected ``heartbeat_settled_skip``; @@ -82,14 +102,30 @@ def reconcile_existing_heartbeat_receipt( ) if not settled_replay: requested_todo_id = normalize_todo_id(args.todo_id) - if requested_todo_id and requested_todo_id != existing_todo_id: - raise HeartbeatReceiptIdentityConflictError( - "heartbeat receipt settlement identity conflicts with the " - "current selected Todo: explicitly requested Todo differs" - ) requested_replan_obligation_id = normalize_todo_replan_obligation_id( getattr(args, "replan_obligation_id", None) ) + if requested_todo_id and requested_replan_obligation_id: + raise ValueError( + "quota rollout cannot bind both todo_id and " + "replan_obligation_id" + ) + if requested_todo_id: + if existing_todo_id and requested_todo_id != existing_todo_id: + raise HeartbeatReceiptIdentityConflictError( + "heartbeat receipt settlement identity conflicts with the " + "current selected Todo: explicitly requested Todo differs" + ) + if existing_replan_obligation_id: + retained_todo_id = normalize_todo_id( + existing_details.get("pending_action_selection_todo_id") + ) + if requested_todo_id != retained_todo_id: + raise HeartbeatReceiptIdentityConflictError( + "heartbeat receipt settlement identity conflicts with " + "the retained Todo selection: explicitly requested " + "Todo differs" + ) if ( requested_replan_obligation_id and requested_replan_obligation_id @@ -99,32 +135,47 @@ def reconcile_existing_heartbeat_receipt( "heartbeat receipt settlement identity conflicts with the " "explicitly requested autonomous replan obligation" ) - if ( - existing_todo_id != rollout_todo_id - or existing_replan_obligation_id != rollout_replan_obligation_id - or existing_effect_id != expected_effect_id - ): + if existing_effect_id != expected_effect_id: raise HeartbeatReceiptIdentityConflictError( - "heartbeat receipt settlement identity conflicts with the " - "current settlement binding: receipt=" - f"{existing_todo_id or existing_replan_obligation_id}, " - "current=" - f"{rollout_todo_id or rollout_replan_obligation_id}" + "heartbeat receipt effect identity does not match its " + "persisted settlement binding" ) rollout_details = quota_rollout_details(payload, args, todo_id=rollout_todo_id, replan_obligation_id=rollout_replan_obligation_id) rollout_details["settlement_effect_id"] = expected_effect_id - receipt, qualified = requalify_bound_heartbeat_receipt( - runtime_root, goal_id=args.goal_id, agent_id=args.agent_id, - turn_instance_id=turn_instance_id, todo_id=rollout_todo_id, - replan_obligation_id=rollout_replan_obligation_id, - status=str(payload.get("effective_action") or payload.get("decision") or "should-run"), - details=rollout_details, - registry_path=Path(str(payload["registry"])) if payload.get("registry") else None, - goal_ref=goal_ref, + replan_packet = ( + payload.get("replan_action_packet") + if isinstance(payload.get("replan_action_packet"), Mapping) + else {} + ) + current_replan_obligation_id = replan_obligation_id_from_packet( + replan_packet ) - if qualified: - receipt_status, receipt_appended = "upgraded", True + # A later frontier can rotate to a new replan identity after + # this Turn's historical ACK was accepted. That projection + # cannot requalify or replace the original receipt. Only the + # same open replan may append compatible review-source facts; + # a settlement-only packet already carries the exact evidence + # needed to close this immutable receipt. + if ( + replan_packet.get("settlement_only") is not True + and ( + not existing_replan_obligation_id + or current_replan_obligation_id + == existing_replan_obligation_id + ) + ): + receipt, qualified = requalify_bound_heartbeat_receipt( + runtime_root, goal_id=args.goal_id, agent_id=args.agent_id, + turn_instance_id=turn_instance_id, todo_id=rollout_todo_id, + replan_obligation_id=rollout_replan_obligation_id, + status=str(payload.get("effective_action") or payload.get("decision") or "should-run"), + details=rollout_details, + registry_path=Path(str(payload["registry"])) if payload.get("registry") else None, + goal_ref=goal_ref, + ) + if qualified: + receipt_status, receipt_appended = "upgraded", True else: rollout_details = quota_rollout_details( payload, @@ -411,24 +462,51 @@ def quota_rollout_details( replan_packet = payload.get("replan_action_packet") obligation = payload.get("autonomous_replan_obligation") if semantic_replan_obligation_id and isinstance(obligation, Mapping) and obligation.get("obligation_id") == semantic_replan_obligation_id: - from ..work_items.replan_semantics_codec import project_replan_semantics from ...rollout_event_log import _safe_details + from ..work_items.replan_semantics_codec import project_replan_semantics source = project_replan_semantics({"operation": "receipt_review_source", "agent_id": getattr(args, "agent_id", None), "obligation": {key: value for key, value in obligation.items() if key != "replan_context"}}) review = source["review_source"] if isinstance(review, Mapping): - # Retain the original stop clause only when the existing public - # metadata serializer preserves it exactly. Unsafe/lossy sources - # keep legacy strict recovery; never truncate a governing clause. + # Retain a short public stop clause verbatim. A longer clause can + # still preserve its semantic identity through a digest, but only + # when the public metadata serializer accepts the entire source + # without private markers or whitespace normalization. Unsafe or + # otherwise lossy sources keep legacy strict recovery. try: safe = _safe_details({"semantic_replan_review_kind": review["kind"], "semantic_replan_review_stop_condition": review["stop_condition"]}) except ValueError: safe = {} - if safe.get("semantic_replan_review_stop_condition") == review["stop_condition"]: + stop_condition = review.get("stop_condition") + if safe.get("semantic_replan_review_stop_condition") == stop_condition: details.update(safe) + elif ( + safe.get("semantic_replan_review_kind") == review.get("kind") + and isinstance(stop_condition, str) + and len(stop_condition) > 240 + and " ".join(stop_condition.split()) == stop_condition + ): + stop_details = { + "semantic_replan_review_kind": safe["semantic_replan_review_kind"], + # Older readers require the scalar stop field. Keep them + # fail-closed on this path while a current reader verifies + # the full clause through its digest (and known contract, + # when available). + "semantic_replan_review_stop_condition": ( + AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION + ), + "semantic_replan_review_stop_condition_sha256": hashlib.sha256( + stop_condition.encode("utf-8") + ).hexdigest(), + } + if stop_condition == AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION: + stop_details["semantic_replan_review_stop_contract_id"] = ( + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID + ) + details.update(stop_details) receipt = payload.get("heartbeat_receipt") capability_guard = (replan_packet.get("capability_guard") if isinstance(replan_packet, Mapping) else None) or ( receipt.get("semantic_replan_capability_guard") if isinstance(receipt, Mapping) else None diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index e8b00ac642..f3064dbf36 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -1,6 +1,7 @@ -import { readReceiptLogSnapshot } from "../runtime/receipt_log_snapshot.ts"; +import { createHash } from "node:crypto"; import { isAbsolute, join } from "node:path"; +import { readReceiptLogSnapshot } from "../runtime/receipt_log_snapshot.ts"; import { heartbeatReceiptsFromEvents, readGoalRolloutEventSnapshot, @@ -21,6 +22,7 @@ import { type SettlementResult, } from "../effect_program.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; +import { BARE_SHA256_PATTERN } from "../content_digest.ts"; import { hasMonitorPollTransaction } from "./monitor_poll_commit.ts"; import { readQuotaSpendEventFromRun } from "./accounting_artifact_transaction.ts"; import { @@ -43,6 +45,7 @@ import { isCapabilityRetirementWriteback, receiptBoundMonitorPhase, receiptBoundReplayPhase, + type ReceiptBoundReplayPhase, } from "./settlement_phase.ts"; import { isTurnScopedSettlementOutcome } from "../work_items/delivery_outcome.ts"; import { @@ -72,6 +75,11 @@ import { import { refreshExternalDelivery } from "./refresh_external_delivery.ts"; import { BLOCKED_WAIT_REQUEST_SCHEMA, prepareBlockedWait, RECEIPT_BOUND_WAIT_REQUEST_SCHEMA, projectReceiptBoundWait, isMonitorUnavailableWait } from "./blocked_wait.ts"; import {nativeChildReportAdmission} from "../capabilities/native_child_admission.ts"; +import { + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID, + AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION, +} from "../work_items/replan_semantics.ts"; import { parseQuotaAccountingOwner, quotaOwnerOwnsProjection, @@ -527,7 +535,8 @@ export function projectSemanticReplanGuard( ): JsonObject { const hasCapability = ["semantic_replan_capability_id", "semantic_replan_gap_id", "semantic_replan_frontier_revision"] .some(field => Object.hasOwn(receiptDetails, field)); - const hasReview = ["semantic_replan_review_kind", "semantic_replan_review_stop_condition"] + const hasReview = ["semantic_replan_review_kind", "semantic_replan_review_stop_condition", + "semantic_replan_review_stop_condition_sha256", "semantic_replan_review_stop_contract_id"] .some(field => Object.hasOwn(receiptDetails, field)); if (hasCapability && hasReview) throw new EffectRuntimeRequestError( "a review source cannot replace a capability guard", "malformed_settlement_state"); @@ -558,14 +567,40 @@ export function projectSemanticReplanGuard( ); } const reviewKind = hasReview ? requireNonEmptyString(receiptDetails.semantic_replan_review_kind, "receipt review kind") : null; - const stop = hasReview ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_condition, "receipt review stop condition") : null; + const stop = Object.hasOwn(receiptDetails, "semantic_replan_review_stop_condition") + ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_condition, "receipt review stop condition") : null; + const stopDigest = Object.hasOwn(receiptDetails, "semantic_replan_review_stop_condition_sha256") + ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_condition_sha256, + "receipt review stop condition digest") : null; + const stopContractId = Object.hasOwn(receiptDetails, "semantic_replan_review_stop_contract_id") + ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_contract_id, + "receipt review stop contract id") : null; + if (hasReview && stop === null && stopDigest === null) throw new EffectRuntimeRequestError( + "a receipt review requires a stop condition or digest", "malformed_settlement_state"); if (stop && stop.length > 240) throw new EffectRuntimeRequestError( "receipt review stop condition exceeds scalar metadata bounds", "malformed_settlement_state"); + if (stopDigest !== null && !BARE_SHA256_PATTERN.test(stopDigest)) throw new EffectRuntimeRequestError( + "receipt review stop condition digest is malformed", "malformed_settlement_state"); + if (stopContractId !== null && + (stopContractId !== AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID || stopDigest === null || + createHash("sha256").update(AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, "utf8").digest("hex") !== stopDigest)) { + throw new EffectRuntimeRequestError( + "receipt review stop contract does not match its digest", "malformed_settlement_state"); + } + if (stop !== null && stopDigest !== null && + stop !== AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION && + createHash("sha256").update(stop, "utf8").digest("hex") !== stopDigest) { + throw new EffectRuntimeRequestError( + "receipt review stop condition digest does not match its value", "malformed_settlement_state"); + } return { schema_version: SEMANTIC_REPLAN_GUARD_SCHEMA, scope: "turn_guard", selected_obligation_id: selectedObligationId, - ...(hasReview ? {selected_review_source: {kind: reviewKind, stop_condition: stop}} : {}), + ...(hasReview ? {selected_review_source: {kind: reviewKind, + ...(stop === null ? {} : {stop_condition: stop}), + ...(stopDigest === null ? {} : {stop_condition_sha256: stopDigest}), + ...(stopContractId === null ? {} : {stop_contract_id: stopContractId})}} : {}), ...(hasCapability ? { selected_capability_guard: decodeCapabilityGuard({schema_version: "semantic_replan_capability_guard_v0", capability_id: receiptDetails.semantic_replan_capability_id, gap_id: receiptDetails.semantic_replan_gap_id, @@ -574,6 +609,48 @@ export function projectSemanticReplanGuard( }; } +/** Upgrade a legacy bound review receipt without changing its Turn identity. + * + * Older receipts retained the selected replan obligation but not the review + * source that proves a regenerated frontier still represents the same duty. + * The correction is append-only: the caller serializes the returned details + * under the receipt-log lock. It is admitted only while closeout has not + * started and both the old and current guards select this exact binding. + */ +function requalifyHeartbeatReceipt( + heartbeatReceipt: JsonObject, + currentDetails: JsonObject, + identity: SettlementIdentity, + replayPhase: ReceiptBoundReplayPhase, + closeoutStarted: boolean, +): JsonObject { + const work = heartbeatWorkRequalification( + heartbeatReceipt, + currentDetails, + identity, + replayPhase, + closeoutStarted, + ); + if (work.append === true || replayPhase !== "open" || closeoutStarted || + identity.binding_kind !== "autonomous_replan") return work; + + const originalDetails = details(heartbeatReceipt); + const originalGuard = projectSemanticReplanGuard(originalDetails); + const currentGuard = projectSemanticReplanGuard(currentDetails); + if (originalGuard.selected_obligation_id !== identity.replan_obligation_id || + currentGuard.selected_obligation_id !== identity.replan_obligation_id || + originalGuard.selected_review_source != null || + currentGuard.selected_review_source == null) return work; + + const upgraded = {...originalDetails}; + for (const field of ["semantic_replan_review_kind", "semantic_replan_review_stop_condition", + "semantic_replan_review_stop_condition_sha256", "semantic_replan_review_stop_contract_id"]) { + if (currentDetails[field] !== undefined) upgraded[field] = currentDetails[field]!; + } + upgraded.settlement_receipt_revision = "review_guard_upgrade"; + return {append: true, details: upgraded}; +} + function decodeCapabilityGuard(value: unknown): JsonObject { const guard = jsonObject(value); if (!guard || guard.schema_version !== "semantic_replan_capability_guard_v0" @@ -933,13 +1010,24 @@ function resolveIdentity( const fact = heartbeatReceiptFactFromEvent(guard); const originalTodoId = normalizeTodoId(fact.todo_id); const originalReplanId = normalizeReplanObligationId(fact.replan_obligation_id); + const retainedTodoId = normalizeTodoId( + details(guard).pending_action_selection_todo_id, + ); if (!originalTodoId && !originalReplanId && !requestSubject) { return failedIdentity("the original Turn guard has no settlement binding", "receipt_unbound"); } - if ((request.todo_id !== null && (todoId === null || todoId !== originalTodoId)) || + const requestedTodoMatchesOriginal = request.todo_id === null || + (todoId !== null && ( + todoId === originalTodoId || + (originalReplanId !== null && todoId === retainedTodoId) + )); + if (!requestedTodoMatchesOriginal || (request.replan_obligation_id !== null && (replanObligationId === null || replanObligationId !== originalReplanId))) { - return failedIdentity("requested binding differs from the original Turn guard", "identity_mismatch"); + return failedIdentity( + "settlement binding does not match: requested binding differs from the original Turn guard", + "identity_mismatch", + ); } todoId = originalTodoId; replanObligationId = originalReplanId; @@ -1460,7 +1548,7 @@ function readQuotaSettlementFromRequest( closeoutStarted, normalizeReplanObligationId(semanticReplanGuard.selected_obligation_id), ), ...(request.heartbeat_reentry_guard === null ? {} : { - heartbeat_reentry_qualification: heartbeatWorkRequalification(heartbeatReceipt, + heartbeat_reentry_qualification: requalifyHeartbeatReceipt(heartbeatReceipt, request.heartbeat_reentry_guard, identity, replayPhase, closeoutStarted), }), }; diff --git a/loopx/control_plane/quota/unsettled_host_turn_recovery.ts b/loopx/control_plane/quota/unsettled_host_turn_recovery.ts index 8bb66871c0..890054f1e3 100644 --- a/loopx/control_plane/quota/unsettled_host_turn_recovery.ts +++ b/loopx/control_plane/quota/unsettled_host_turn_recovery.ts @@ -335,6 +335,12 @@ function decodeCandidate(value: unknown): PriorHostTurnCloseoutCandidate { ); } const settlementEffectId = optionalHeartbeatString(raw.settlement_effect_id); + if (raw.admitted_replan !== undefined && + (raw.admitted_replan !== true || settlementEffectId === null)) { + throw new EffectRuntimeRequestError( + "prior host Turn recovery candidate has an invalid autonomous replan fact", + ); + } if (raw.admitted_todo_replan !== undefined && (raw.admitted_todo_replan !== true || bindingKind !== "todo" || settlementEffectId === null)) { throw new EffectRuntimeRequestError( @@ -350,6 +356,11 @@ function decodeCandidate(value: unknown): PriorHostTurnCloseoutCandidate { binding_kind: bindingKind, binding_id: bindingId, settlement_effect_id: settlementEffectId, + ...( + raw.admitted_replan === true || raw.admitted_todo_replan === true + ? {admitted_replan: true as const} + : {} + ), ...(raw.admitted_todo_replan === true ? {admitted_todo_replan: true as const} : {}), }; } @@ -506,9 +517,10 @@ function recoveryObligation( * * The accepted closeout order is policy: a validated settlement wins, then an * exactly committed monitor-poll closeout, then a typed lifecycle transition. - * For a Todo-bound autonomous replan, a verified writeback keeps its debit - * obligation even when the Todo has changed. Ordinary lifecycle closeouts - * retain their existing meaning. + * For an admitted autonomous replan, a verified writeback keeps its debit + * obligation under either the legacy Todo binding or the canonical replan + * obligation binding. Ordinary lifecycle closeouts retain their existing + * meaning. */ export function reduceUnsettledHostTurnRecovery(value: unknown): JsonObject { const request = requireJsonObject(value, "prior host Turn recovery request"); @@ -553,7 +565,7 @@ export function reduceUnsettledHostTurnRecovery(value: unknown): JsonObject { }; } - const replanSpendOwed = selected.admitted_todo_replan === true && awaitingQuotaSpend(missingReceipts); + const replanSpendOwed = selected.admitted_replan === true && awaitingQuotaSpend(missingReceipts); const lifecycleCloseout = replanSpendOwed ? null : acceptedLifecycleCloseout(todo); if (lifecycleCloseout !== null) { return { diff --git a/loopx/control_plane/work_items/autonomous_replan_ack.py b/loopx/control_plane/work_items/autonomous_replan_ack.py index a9a8ecb81f..2c16a75ccc 100644 --- a/loopx/control_plane/work_items/autonomous_replan_ack.py +++ b/loopx/control_plane/work_items/autonomous_replan_ack.py @@ -310,12 +310,15 @@ def _source_run( def _expected_todo_receipt( run: dict[str, Any], events: list[dict[str, Any]], *, - goal_id: str, agent_id: str, turn_instance_id: str, + goal_id: str, agent_id: str, turn_instance_id: str, obligation_id: str, ) -> tuple[str, str]: - """Todo settlement identity for this ACK, filled from its heartbeat receipt. + """Todo command 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. + quota receipt still has that exact identity. A replan-bound receipt keeps + the admitted Todo as its pending action selection; that retained selection + may address the writeback without replacing the receipt's obligation. + An empty or differently bound side is not a match. """ identity = run.get("settlement_identity") @@ -333,7 +336,15 @@ def _expected_todo_receipt( ): continue details = _event_details(event) - todo = todo or _binding_text(event.get("todo_id") or details.get("todo_id")) + receipt_replan = _binding_text(details.get("replan_obligation_id")) + retained_todo = ( + _binding_text(details.get("pending_action_selection_todo_id")) + if receipt_replan == obligation_id + else "" + ) + todo = todo or _binding_text( + event.get("todo_id") or details.get("todo_id") or retained_todo + ) effect = effect or _binding_text(details.get("settlement_effect_id")) return todo, effect @@ -366,7 +377,8 @@ def _writeback_event_is_bound( 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) + run, events, goal_id=goal_id, agent_id=agent_id, + turn_instance_id=turn_instance_id, obligation_id=obligation_id) return bool( expected_todo and expected_effect and event_todo == expected_todo and event_effect == expected_effect diff --git a/loopx/control_plane/work_items/autonomous_replan_obligation.py b/loopx/control_plane/work_items/autonomous_replan_obligation.py index c79451204e..0023ae799f 100644 --- a/loopx/control_plane/work_items/autonomous_replan_obligation.py +++ b/loopx/control_plane/work_items/autonomous_replan_obligation.py @@ -27,6 +27,18 @@ MAX_AUTONOMOUS_REPLAN_TRIGGERS = 3 AUTONOMOUS_REPLAN_STALL_THRESHOLD = 2 +AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID = "autonomous_replan_default_v0" +AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION = ( + "stop only the affected path when required access, destructive git, production actions, " + "or owner-only decisions exceed existing user authority. Keep authorized private reads " + "within their storage and publication boundaries; do not expose credentials or disclose " + "private material beyond that authority. Continue independent authorized replan work " + "while honoring explicit stops" +) +AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION = ( + "stop this replan path until a compatible reader validates its digest-bound " + "review guard" +) REPLAN_NOVELTY_POLICY_SCHEMA_VERSION = "replan_evidence_delivery_policy_v0" TODO_LIFECYCLE_SETTLEMENT_RESOLUTION_MODE = "todo_lifecycle_settlement" REPLAN_NOVELTY_GUIDANCE = ( @@ -642,13 +654,7 @@ def build_autonomous_replan_obligation( else ["keep", "split", "add", "retire", "ask_decision"] ), todo_actions=todo_actions[:3], - stop_condition=( - "stop only the affected path when required access, destructive git, production actions, " - "or owner-only decisions exceed existing user authority. Keep authorized private reads " - "within their storage and publication boundaries; do not expose credentials or disclose " - "private material beyond that authority. Continue independent authorized replan work " - "while honoring explicit stops" - ), + stop_condition=AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, recommended_action=recommended_action, agent_id=replan_agent_id, extra_fields=extra_fields, diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts index ddf38a9b55..3431e4b1a7 100644 --- a/loopx/control_plane/work_items/replan_semantics.ts +++ b/loopx/control_plane/work_items/replan_semantics.ts @@ -1,4 +1,5 @@ import type { JsonObject } from "../effect_program.ts"; +import { createHash } from "node:crypto"; import { BARE_SHA256_PATTERN } from "../content_digest.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { optionalNonEmptyString, requireJsonObject, requireNonEmptyString } from "../runtime_decode.ts"; @@ -36,6 +37,16 @@ const ACCEPTANCE_HOLD_TRIGGERS = new Set(["goal_acceptance_stale", "goal_accepta // A vision gap dominates the ordinary outcome gap's discharge policy, so the // same scalar receipt can retain a mixed review after its work links change. const SCALAR_REVIEW_KINDS = new Set(["goal_outcome_uncovered", "vision_acceptance_gap", "monitor_no_change_streak"]); +const RECONSTRUCTIBLE_REVIEW_KINDS = new Set([...SCALAR_REVIEW_KINDS, "periodic_review_due"]); +export const AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID = "autonomous_replan_default_v0"; +export const AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION = + "stop only the affected path when required access, destructive git, production actions, " + + "or owner-only decisions exceed existing user authority. Keep authorized private reads " + + "within their storage and publication boundaries; do not expose credentials or disclose " + + "private material beyond that authority. Continue independent authorized replan work " + + "while honoring explicit stops"; +export const AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION = + "stop this replan path until a compatible reader validates its digest-bound review guard"; const EXTERNAL_REVIEW_TRIGGERS = new Set(["external_progress_review_drift"]); export const FRESH_PATH_DISPOSITIONS = new Set(["continue", "no_change", "replan"]); const PROGRESS_CLI_ARGS = "--progress-result-class --progress-surface-id --progress-hypothesis-id --progress-probe-kind --progress-evidence-id "; @@ -76,6 +87,20 @@ function triggerKinds(obligation: JsonObject): string[] { const triggers = Array.isArray(obligation.triggers) ? obligation.triggers : []; return triggers.map(trigger => String(object(trigger).kind ?? "").trim()); } +function receiptReviewKind(obligation: JsonObject): string | null { + const kinds = triggerKinds(obligation); + if (!kinds.length) return null; + if (kinds.every(kind => SCALAR_REVIEW_KINDS.has(kind))) { + // Preserve the current frontier's precedence, including Monitor-only + // reviews, when selecting a scalar or digest-backed receipt source. + return ["vision_acceptance_gap", "goal_outcome_uncovered", "monitor_no_change_streak"] + .find(kind => kinds.includes(kind)) ?? null; + } + // A single current review can be revalidated by its kind and complete stop + // contract without pretending that an old context is current. Mixed duties + // retain their source-specific recovery instead of collapsing to one label. + return kinds.length === 1 ? kinds[0] : null; +} function isExternalReview(obligation: JsonObject): boolean { return triggerKinds(obligation).some(kind => EXTERNAL_REVIEW_TRIGGERS.has(kind)); } @@ -389,6 +414,44 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject { // writeback. The exact receipt retains its typed kind, never raw task prose // or an old decision context. Other duties keep their canonical owners. const review = object(request.receipt_review); + const reviewKind = typeof review.kind === "string" ? review.kind : ""; + const reviewStop = typeof review.stop_condition === "string" + ? review.stop_condition : null; + const reviewDigest = typeof review.stop_condition_sha256 === "string" + ? review.stop_condition_sha256 : ""; + const reviewContractId = typeof review.stop_contract_id === "string" + ? review.stop_contract_id : ""; + const reviewContractStop = reviewContractId === AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID && + BARE_SHA256_PATTERN.test(reviewDigest) && + createHash("sha256").update(AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, "utf8").digest("hex") === reviewDigest + ? AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION : null; + const currentReviewKind = current === null ? null : receiptReviewKind(current); + const currentStop = current === null || typeof current.stop_condition !== "string" + ? null : current.stop_condition; + if (request.guard_scoped && current !== null && currentReviewKind === reviewKind && + currentStop !== null && (currentStop === reviewStop || + (BARE_SHA256_PATTERN.test(reviewDigest) && + createHash("sha256").update(currentStop, "utf8").digest("hex") === reviewDigest)) && + current.schema_version === "autonomous_replan_obligation_v0" && current.required === true && + typeof request.agent_id === "string" && request.agent_id.trim() && + current.agent_id === request.agent_id && current.resolution_mode == null && + current.capability_guard == null) { + // The frontier regenerated the review identity while its kind and complete + // stop contract stayed unchanged. Preserve the receipt's settlement id, + // but retain the current obligation and context so recovery never claims + // that an old context snapshot is still current. + const rebound: JsonObject = {...current, obligation_id: selected, + selection_binding: "heartbeat_receipt"}; + if (current.obligation_id !== selected) { + // The current context and its delivery receipt were derived under the + // regenerated frontier id. Returning them under the old settlement id + // would create an internally inconsistent packet. The quota context + // owner reattaches a fresh context from current status after this typed + // identity projection; no historical context snapshot is replayed. + delete rebound.replan_context; + } + return {obligation: rebound}; + } if (request.guard_scoped && SCALAR_REVIEW_KINDS.has(String(review.kind)) && typeof review.stop_condition === "string" && review.stop_condition.trim() && review.stop_condition.length <= 240 && typeof request.agent_id === "string" && request.agent_id.trim()) { @@ -397,6 +460,14 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject { stop_condition: review.stop_condition, triggers: [{kind: review.kind}], selection_binding: "heartbeat_receipt"}}; } + if (request.guard_scoped && current === null && + RECONSTRUCTIBLE_REVIEW_KINDS.has(reviewKind) && reviewContractStop !== null && + typeof request.agent_id === "string" && request.agent_id.trim()) { + return {obligation: {schema_version: "autonomous_replan_obligation_v0", + required: true, obligation_id: selected, agent_id: request.agent_id, + stop_condition: reviewContractStop, + triggers: [{kind: reviewKind}], selection_binding: "heartbeat_receipt"}}; + } throw new EffectRuntimeRequestError( "heartbeat receipt settlement identity conflicts with the current autonomous replan obligation", "heartbeat_receipt_identity_conflict", @@ -547,25 +618,22 @@ export function projectReplanSemantics(value: unknown): JsonObject { if (request.operation === "receipt_bound_obligation") return preserveReceiptBoundObligation(request); const obligation = requireJsonObject(request.obligation, "obligation"); if (request.operation === "receipt_review_source") { - const kinds = triggerKinds(obligation); const triggers = Array.isArray(obligation.triggers) ? obligation.triggers : []; - // Plain frontier reviews share a scalar receipt source. Other mixed, - // restricted, lifecycle and capability obligations must retain their + const kind = receiptReviewKind(obligation); + // A simple review stores only its kind and complete stop contract. Other + // mixed, restricted, lifecycle and capability obligations must retain // source-specific evidence and discharge rules through their own owners. return {review_source: obligation.schema_version === "autonomous_replan_obligation_v0" && - obligation.required === true && kinds.length > 0 && + obligation.required === true && kind !== null && obligation.trigger_count === triggers.length && typeof request.agent_id === "string" && request.agent_id.trim() && obligation.agent_id === request.agent_id && - kinds.every(kind => SCALAR_REVIEW_KINDS.has(kind)) && obligation.resolution_mode == null && obligation.capability_guard == null && strings(obligation.satisfying_semantic_outcomes).length === 0 && obligation.progress_baseline == null && obligation.progress_window == null && triggers.every(trigger => object(trigger).progress_baseline == null && object(trigger).progress_window == null) && - typeof obligation.stop_condition === "string" && obligation.stop_condition.trim() && obligation.stop_condition.length <= 240 - // Fixed precedence keeps the selected kind independent of trigger order. - ? {kind: ["vision_acceptance_gap", "goal_outcome_uncovered", "monitor_no_change_streak"].find(kind => kinds.includes(kind)), - stop_condition: obligation.stop_condition} : null}; + typeof obligation.stop_condition === "string" && obligation.stop_condition.trim() + ? {kind, stop_condition: obligation.stop_condition} : null}; } if (request.operation === "transition_eligibility") { return {allowed: !requiresStrideDecision(obligation, request.stride_strategy)}; diff --git a/loopx/state_refresh.py b/loopx/state_refresh.py index 99d790f275..2859286fa8 100644 --- a/loopx/state_refresh.py +++ b/loopx/state_refresh.py @@ -888,6 +888,13 @@ def refresh_state_run( goal_ref=goal_ref, source_admission=source_admission, borrow_source_admission=source_admission is not None, + # refresh-state closes the exact admitted Turn. A semantic + # replan may retain ``--todo-id`` as its planning selection + # while the immutable settlement identity is the replan + # obligation recorded by quota should-run. Resolve that + # original receipt binding, while the read model still rejects + # a different Todo or obligation. + resolve_original_binding=True, refresh_retry=(refresh_retry_request := { "checkpoint_read_context_id": checkpoint_read_context_id, "external_delivery": external_delivery, diff --git a/tests/control_plane/test_quota_settlement.py b/tests/control_plane/test_quota_settlement.py index 79e0a6d664..ed2651f365 100644 --- a/tests/control_plane/test_quota_settlement.py +++ b/tests/control_plane/test_quota_settlement.py @@ -41,6 +41,7 @@ from loopx.control_plane.quota.error_codes import ( HeartbeatReceiptIdentityConflictError, ) +from loopx.control_plane.quota.effective_action import EffectiveAction from loopx.control_plane.quota.turn_envelope import quota_action_signature_document from loopx.control_plane.scheduler.execution_context import ( SchedulerRuntimeProfile, @@ -255,6 +256,22 @@ def test_selected_todo_suppresses_stale_replan_packet_binding() -> None: assert quota_rollout_replan_obligation_id(payload, args) is None +def test_current_replan_preserves_explicit_planning_selection_gate() -> None: + obligation_id = "replan-0000000000000001" + payload = { + "effective_action": EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED.value, + "selected_todo": {"todo_id": TODO_ID}, + "action_portfolio": { + "selection_policy": {"requires_explicit_turn_binding": True}, + }, + "replan_action_packet": {"obligation_id": obligation_id}, + } + args = SimpleNamespace(todo_id=None, replan_obligation_id=None) + + assert quota_rollout_todo_id(payload, args) is None + assert quota_rollout_replan_obligation_id(payload, args) is None + + def test_explicit_replan_binding_survives_newly_selected_todo() -> None: obligation_id = "replan-0000000000000001" payload = {"selected_todo": {"todo_id": TODO_ID}} diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index 6bb924e7c4..7c98cd6960 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -1,5 +1,6 @@ from __future__ import annotations +import hashlib import json import os import shlex @@ -737,6 +738,200 @@ def _bind_selected_replan_guard( return bound + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_existing_todo_receipt_precedes_later_replan_projection( + tmp_path: Path, + provider: str, +) -> None: + """A later replan cannot replace an admitted Todo settlement identity.""" + + project, runtime, registry = _write_fixture(tmp_path) + _configure_read_only_todo(project) + _initialize_fixture_authority(project, runtime, provider=provider) + turn = "turn-existing-todo-before-later-replan" + guard = ( + "quota", + "should-run", + "--codex-app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--turn-instance-id", + turn, + ) + + first_rc, first = _run_cli(registry, runtime, *guard) + assert first_rc == 0, first + original = first["heartbeat_receipt"]["settlement_identity"] + assert original["todo_id"] == TODO_ID + assert original.get("replan_obligation_id") is None + + _append_surface_only_runs( + runtime, + count=AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD, + ) + replay_rc, replay = _run_cli(registry, runtime, *guard) + + assert replay_rc == 0, replay + assert replay["heartbeat_receipt"]["settlement_identity"] == original + assert ( + replay["interaction_contract"]["cli_channel"]["settlement_plan"][ + "identity" + ] + == original + ) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_same_explicit_todo_retry_preserves_original_identity( + tmp_path: Path, + provider: str, +) -> None: + """Retrying the retained planning choice reuses the admitted replan.""" + + 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) + turn = "turn-same-explicit-todo-replan-retry" + guard = ( + "quota", + "should-run", + "--codex-app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--turn-instance-id", + turn, + "--todo-id", + SELECTED_REPLAN_TODO_ID, + ) + + first_rc, first = _run_cli(registry, runtime, *guard) + replay_rc, replay = _run_cli(registry, runtime, *guard) + + assert first_rc == 0, first + original = first["heartbeat_receipt"]["settlement_identity"] + assert original["todo_id"] == SELECTED_REPLAN_TODO_ID + assert replay_rc == 0, replay + assert replay["heartbeat_receipt"]["settlement_identity"] == original + assert ( + replay["interaction_contract"]["cli_channel"]["settlement_plan"][ + "identity" + ] + == original + ) + + conflict_args = list(guard) + conflict_args[-1] = ALTERNATIVE_TODO_ID + conflict_rc, conflict = _run_cli(registry, runtime, *conflict_args) + assert conflict_rc == 1, conflict + assert conflict["error_code"] == "heartbeat_receipt_identity_conflict" + receipt_events = _heartbeat_receipt_events(runtime, turn) + assert receipt_events + assert { + event["details"]["settlement_effect_id"] for event in receipt_events + } == {original["effect_id"]} + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_todoless_replan_upgrades_legacy_review_guard( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + """A legacy review receipt gains its source without rebinding the Turn.""" + if provider == "sqlite": + from canonical_authority_fixture import isolate_sqlite_runtime + + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path) + state = project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md" + state.write_text( + state.read_text().split("## Agent Todo")[0].replace( + "status: active-read-only", "status: active" + ) + "## Agent Todo\n\n" + ) + registry_value = json.loads(registry.read_text()) + registry_value["goals"][0]["status"] = "active" + registry.write_text(json.dumps(registry_value)) + _initialize_fixture_authority(project, runtime, provider=provider) + _append_surface_only_runs(runtime, count=AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD) + + def call(*args: str, expected_code: int = 0) -> dict[str, Any]: + code, result = _run_cli(registry, runtime, *args) + assert code == expected_code, result + return result + + call("configure-goal", "--goal-id", GOAL_ID, + "--execution-replan-after-todos", "5", "--execute") + + turn = "turn-todoless-replan-review-upgrade" + guard = ("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, + "--agent-id", AGENT_ID, "--turn-instance-id", turn) + first = call(*guard) + assert first["effective_action"] == "autonomous_replan_required" + identity = first["heartbeat_receipt"]["settlement_identity"] + assert identity["binding_kind"] == "autonomous_replan" + assert identity["replan_obligation_id"] == first["replan_action_packet"]["obligation_id"] + original = _heartbeat_receipt_events(runtime, turn)[0] + expected_kind = original["details"]["semantic_replan_review_kind"] + + # Simulate a receipt written before review-source retention existed. The + # exercised repair below is append-only; only this fixture setup removes + # fields from its synthetic legacy input. + log = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl" + events = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + for event in events: + if event.get("event_id") != original["event_id"]: + continue + for field in ("semantic_replan_review_kind", + "semantic_replan_review_stop_condition", + "semantic_replan_review_stop_condition_sha256", + "semantic_replan_review_stop_contract_id"): + event["details"].pop(field, None) + log.write_text("\n".join(json.dumps(event) for event in events) + "\n", encoding="utf-8") + + replay = call(*guard) + assert replay["heartbeat_receipt"]["settlement_identity"] == identity + repaired = _heartbeat_receipt_events(runtime, turn) + assert len(repaired) == 2 + assert repaired[1]["causality"]["caused_by"] == original["event_id"] + assert repaired[1]["details"]["settlement_receipt_revision"] == "review_guard_upgrade" + assert repaired[1]["details"]["semantic_replan_review_kind"] == expected_kind + assert ( + repaired[1]["details"].get("semantic_replan_review_stop_condition") + or repaired[1]["details"].get("semantic_replan_review_stop_condition_sha256") + ) + + # A new completed Turn rotates the periodic frontier obligation id while the + # review kind and full stop contract remain the same. A fresh dry-run + # exposes that raw id; replay of the admitted Turn retains its old identity + # and adopts the current context. + index = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl" + with index.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"generated_at": "2026-08-13T01:00:00+00:00", + "goal_id": GOAL_ID, "classification": "surface_only_progress", + "agent_id": AGENT_ID, "progress_scope": "agent_lane", + "delivery_outcome": "surface_only"}) + "\n") + receipt_bytes = log.read_bytes() + log.unlink() + try: + probe = call("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, + "--agent-id", AGENT_ID, "--dry-run") + finally: + log.write_bytes(receipt_bytes) + assert probe["replan_action_packet"]["obligation_id"] != identity["replan_obligation_id"] + assert probe["autonomous_replan_obligation"]["stop_condition"] == ( + first["autonomous_replan_obligation"]["stop_condition"] + ) + replay = call(*guard) + assert replay["heartbeat_receipt"]["settlement_identity"] == identity + assert replay["autonomous_replan_obligation"]["obligation_id"] == identity["replan_obligation_id"] + assert len(_heartbeat_receipt_events(runtime, turn)) == 2 + + def _initialize_git_checkout(project: Path) -> None: subprocess.run( ["git", "init", "--quiet"], @@ -7721,21 +7916,33 @@ def refine(document: dict[str, Any], operation: str) -> dict[str, Any]: def test_receipt_review_does_not_persist_private_or_lossy_stop_clauses() -> None: from argparse import Namespace from loopx.control_plane.quota.settlement_cli import quota_rollout_details + from loopx.control_plane.work_items.autonomous_replan_obligation import ( + AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION, + ) obligation = {"schema_version": "autonomous_replan_obligation_v0", "required": True, "agent_id": AGENT_ID, "obligation_id": "replan-1111111111111111", - "trigger_count": 1, "triggers": [{"kind": "goal_outcome_uncovered"}]} - for stop, retained in [("Stop at owner-only decisions.", True), - ("Stop if Authorization: example is required.", False), - ("Stop before\nowner-only decisions.", False), ("s" * 241, False)]: + "trigger_count": 1, "triggers": [{"kind": "periodic_review_due"}]} + for stop, retention in [("Stop at owner-only decisions.", "full"), + ("Stop if " + "Author" + "ization: example is required.", "none"), + ("Stop before\nowner-only decisions.", "none"), ("s" * 241, "digest")]: details = quota_rollout_details({"autonomous_replan_obligation": {**obligation, "stop_condition": stop}, "replan_action_packet": {"obligation_id": obligation["obligation_id"]}}, Namespace(quota_command="should-run", agent_id=AGENT_ID), todo_id=None) - assert ("semantic_replan_review_kind" in details) is retained - if retained: + assert ("semantic_replan_review_kind" in details) is (retention != "none") + if retention == "full": assert details["semantic_replan_review_stop_condition"] == stop + assert "semantic_replan_review_stop_condition_sha256" not in details + elif retention == "digest": + assert details["semantic_replan_review_stop_condition_sha256"] == hashlib.sha256( + stop.encode("utf-8") + ).hexdigest() + assert details["semantic_replan_review_stop_condition"] == ( + AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION + ) else: assert "semantic_replan_review_stop_condition" not in details + assert "semantic_replan_review_stop_condition_sha256" not in details @pytest.mark.parametrize("provider", ["file", "sqlite"]) diff --git a/tests/control_plane/test_turn_host_context_delivery.py b/tests/control_plane/test_turn_host_context_delivery.py index 7b8435015a..c71b6a9299 100644 --- a/tests/control_plane/test_turn_host_context_delivery.py +++ b/tests/control_plane/test_turn_host_context_delivery.py @@ -145,11 +145,13 @@ def test_captured_context_reaches_actual_host_without_readmission(tmp_path, monk # The current producer's own immutable capture is the transport oracle; # the original long task and optional context remain independent inputs. detail = actual["detail_ref"]["captured_decision"] - assert json.loads(Path(detail["path"]).read_text()) == actual["work_contract"] - assert actual["work_contract"] == plan["work_contract"] - assert "Validate the complete acceptance: " + "preserve original evidence; " * 180 in json.dumps(actual["work_contract"]) + delivered_work = json.loads(Path(detail["path"]).read_text()) + assert delivered_work == plan["work_contract"] + assert actual["source_decision_hash"] == plan["source_decision_hash"] + assert "work_contract" not in actual + assert "Validate the complete acceptance: " + "preserve original evidence; " * 180 in json.dumps(delivered_work) assert "turn_envelope" not in actual and "turn_authority" not in actual - delivered_context = actual["work_contract"]["interaction_contract"].get("agent_context") + delivered_context = delivered_work["interaction_contract"].get("agent_context") assert delivered_context == context if context: assert "detail_ref" not in delivered_context @@ -234,7 +236,8 @@ def test_bound_replan_reaches_actual_host_with_original_evidence(tmp_path, monke prompt_path = project / "received.txt" prompt = prompt_path.read_text() actual, _ = json.JSONDecoder().raw_decode(prompt.split("Turn request:\n", 1)[1]) - assert actual["work_contract"] == plan["work_contract"] + assert actual["source_decision_hash"] == plan["source_decision_hash"] + assert "work_contract" not in actual # This Goal body is a pending original read, exercised below; a complete # contract does not require every retained source to be inline. assert "turn_envelope" not in actual and "turn_authority" not in actual diff --git a/tests/control_plane_ts/quota_settlement_readback.test.ts b/tests/control_plane_ts/quota_settlement_readback.test.ts index c356e00846..9a50f9f0dc 100644 --- a/tests/control_plane_ts/quota_settlement_readback.test.ts +++ b/tests/control_plane_ts/quota_settlement_readback.test.ts @@ -35,6 +35,11 @@ import { preflightPriorHostTurnCloseout, } from "../../loopx/control_plane/quota/unsettled_host_turn_recovery.ts"; import { requireJsonObject } from "../../loopx/control_plane/runtime_decode.ts"; +import { + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID, + AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION, +} from "../../loopx/control_plane/work_items/replan_semantics.ts"; const goalId = "settlement-goal"; const agentId = "codex-settlement"; @@ -94,9 +99,36 @@ test("recorded review source retains its stop clause under the exact selected gu semantic_replan_review_stop_condition: "Stop at owner-only decisions."}; assert.deepEqual(projectSemanticReplanGuard(details).selected_review_source, { kind: details.semantic_replan_review_kind, stop_condition: details.semantic_replan_review_stop_condition}); + const digest = createHash("sha256").update(details.semantic_replan_review_stop_condition, "utf8").digest("hex"); + assert.deepEqual(projectSemanticReplanGuard({semantic_replan_obligation_id: details.semantic_replan_obligation_id, + semantic_replan_review_kind: details.semantic_replan_review_kind, + semantic_replan_review_stop_condition_sha256: digest}).selected_review_source, { + kind: details.semantic_replan_review_kind, stop_condition_sha256: digest}); + assert.deepEqual(projectSemanticReplanGuard({...details, + semantic_replan_review_stop_condition_sha256: digest}).selected_review_source, { + kind: details.semantic_replan_review_kind, + stop_condition: details.semantic_replan_review_stop_condition, + stop_condition_sha256: digest}); + const defaultDigest = createHash("sha256").update( + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, "utf8").digest("hex"); + assert.deepEqual(projectSemanticReplanGuard({ + semantic_replan_obligation_id: details.semantic_replan_obligation_id, + semantic_replan_review_kind: "periodic_review_due", + semantic_replan_review_stop_condition: AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION, + semantic_replan_review_stop_condition_sha256: defaultDigest, + semantic_replan_review_stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID, + }).selected_review_source, { + kind: "periodic_review_due", + stop_condition: AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION, + stop_condition_sha256: defaultDigest, + stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID, + }); for (const patch of [{semantic_replan_obligation_id: ""}, {semantic_replan_obligation_id: undefined}, {semantic_replan_review_kind: undefined}, {semantic_replan_review_stop_condition: undefined}, {semantic_replan_review_stop_condition: "s".repeat(241)}, + {semantic_replan_review_stop_condition_sha256: "bad"}, + {semantic_replan_review_stop_condition_sha256: "0".repeat(64)}, + {semantic_replan_review_stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID}, {semantic_replan_capability_id: "explore"}]) { assert.throws(() => projectSemanticReplanGuard({...details, ...patch})); } @@ -1967,6 +1999,44 @@ test("rejects a guard bound to another Todo", async () => { ); }); +test("a retained Todo selects its original replan guard without rebinding it", async () => { + const obligation = "replan-0000000000000001"; + const bound = settlementIdentity({ + goal_id: goalId, + agent_id: agentId, + todo_id: null, + replan_obligation_id: obligation, + turn_instance_id: turnId, + }); + const runtimeRoot = await fixture(); + try { + const log = join(runtimeRoot, "goals", goalId, "rollout-event-log.jsonl"); + const events = (await readFile(log, "utf8")).trim().split("\n") + .map(line => JSON.parse(line)); + Object.assign(events[0].details, { + todo_id: "", + replan_obligation_id: obligation, + settlement_effect_id: bound.effect_id, + pending_action_selection_todo_id: todoId, + semantic_replan_obligation_id: obligation, + }); + await writeFile(log, events.map(event => JSON.stringify(event)).join("\n") + "\n"); + + const result = await readQuotaSettlement(request(runtimeRoot, { + resolve_original_binding: true, + })); + assert.deepEqual((result.identity as any).result.value, settlementIdentityPayload(bound)); + + const mismatch = await readQuotaSettlement(request(runtimeRoot, { + todo_id: "todo_other", + resolve_original_binding: true, + })); + assert.equal((mismatch.identity as any).result.failure.kind, "identity_mismatch"); + } finally { + await rm(runtimeRoot, {recursive: true, force: true}); + } +}); + test("rejects dual Todo and replan bindings before reading settlement facts", async () => { const runtimeRoot = await fixture({ writeback: true, diff --git a/tests/control_plane_ts/replan_semantics.test.ts b/tests/control_plane_ts/replan_semantics.test.ts index 87e92fabdd..47d5960f41 100644 --- a/tests/control_plane_ts/replan_semantics.test.ts +++ b/tests/control_plane_ts/replan_semantics.test.ts @@ -1,6 +1,12 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import test from "node:test"; -import { projectReplanSemantics, requiredSemanticOutcomes } from "../../loopx/control_plane/work_items/replan_semantics.ts"; +import { + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID, + projectReplanSemantics, + requiredSemanticOutcomes, +} from "../../loopx/control_plane/work_items/replan_semantics.ts"; test("capability evidence is not a default exit or a generic progress claim", () => { for (const outcome of ["capability_evidence_observed", "capability_duty_retired"]) { @@ -175,7 +181,7 @@ test("an open Vision reconstruction must come from the exact scoped receipt sour } }); -test("scalar review sources exclude evidence windows and restricted duties", () => { +test("scalar and digest review sources exclude evidence windows and restricted duties", () => { const source = {schema_version: "autonomous_replan_obligation_v0", required: true, obligation_id: "replan-1111111111111111", agent_id: "reviewer", trigger_count: 1, stop_condition: "Stop at owner-only decisions.", @@ -184,9 +190,11 @@ test("scalar review sources exclude evidence windows and restricted duties", () const request = {operation: "receipt_review_source", agent_id: "reviewer", obligation: source}; assert.deepEqual(projectReplanSemantics(request), {review_source: { kind: "goal_outcome_uncovered", stop_condition: source.stop_condition}}); + assert.deepEqual(projectReplanSemantics({...request, obligation: {...source, + stop_condition: "s".repeat(241), triggers: [{kind: "periodic_review_due"}]}}), {review_source: { + kind: "periodic_review_due", stop_condition: "s".repeat(241)}}); for (const patch of [{required: false}, {schema_version: "unknown"}, {agent_id: "another-agent"}, {triggers: []}, {trigger_count: 2}, {trigger_count: undefined}, - {triggers: [{kind: "periodic_review_due"}]}, {triggers: [{kind: "goal_outcome_uncovered"}, {kind: "external_progress_review_drift"}]}, {trigger_count: 2, triggers: [{kind: "vision_acceptance_gap"}, {kind: "periodic_review_due"}]}, {trigger_count: 2, triggers: [{kind: "vision_acceptance_gap"}, {kind: "external_progress_review_drift"}]}, @@ -195,13 +203,66 @@ test("scalar review sources exclude evidence windows and restricted duties", () {progress_baseline: {}}, {progress_window: []}, {triggers: [{kind: "goal_outcome_uncovered", progress_baseline: {}}]}, {triggers: [{kind: "goal_outcome_uncovered", progress_window: []}]}, - {stop_condition: null}, {stop_condition: "s".repeat(241)}, + {stop_condition: null}, {resolution_mode: "todo_lifecycle_settlement"}, {capability_guard: {schema_version: "semantic_replan_capability_guard_v0"}}]) { assert.deepEqual(projectReplanSemantics({...request, obligation: {...source, ...patch}}), {review_source: null}); } }); +test("a digest-bound review keeps its receipt id across equivalent frontier regeneration", () => { + const originalId = "replan-1111111111111111"; + const currentId = "replan-2222222222222222"; + const stop = "Review current acceptance evidence before changing the route. ".repeat(6).trim(); + const digest = createHash("sha256").update(stop, "utf8").digest("hex"); + const current = {schema_version: "autonomous_replan_obligation_v0", required: true, + obligation_id: currentId, agent_id: "reviewer", trigger_count: 1, + triggers: [{kind: "periodic_review_due"}], stop_condition: stop, + replan_context: {context_id: "latest-review-context"}}; + const request = {operation: "receipt_bound_obligation", guard_scoped: true, + replay_phase: "open", selected_obligation_id: originalId, agent_id: "reviewer", + current_obligation: current, transition_candidates: [], receipt_review: { + kind: "periodic_review_due", stop_condition_sha256: digest}}; + const recovered = projectReplanSemantics(request).obligation as JsonObject; + assert.equal(recovered.obligation_id, originalId); + assert.equal(recovered.stop_condition, stop); + assert.equal(recovered.replan_context, undefined, + "the caller must rebuild current context under the retained settlement id"); + assert.equal(recovered.selection_binding, "heartbeat_receipt"); + for (const patch of [ + {receipt_review: {...request.receipt_review, kind: "vision_acceptance_gap"}}, + {receipt_review: {...request.receipt_review, stop_condition_sha256: "0".repeat(64)}}, + {current_obligation: {...current, stop_condition: `${stop} changed`}}, + {current_obligation: {...current, triggers: [{kind: "goal_outcome_uncovered"}]}}, + {current_obligation: {...current, agent_id: "another-agent"}}, + ]) { + assert.throws(() => projectReplanSemantics({...request, ...patch}), /identity conflicts/); + } +}); + +test("a canonical periodic review reconstructs after its live frontier disappears", () => { + const originalId = "replan-1111111111111111"; + const digest = createHash("sha256").update( + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, "utf8").digest("hex"); + const request = {operation: "receipt_bound_obligation", guard_scoped: true, + replay_phase: "open", selected_obligation_id: originalId, agent_id: "reviewer", + current_obligation: null, transition_candidates: [], receipt_review: { + kind: "periodic_review_due", stop_condition_sha256: digest, + stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID}}; + assert.deepEqual(projectReplanSemantics(request).obligation, { + schema_version: "autonomous_replan_obligation_v0", required: true, + obligation_id: originalId, agent_id: "reviewer", + stop_condition: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, + triggers: [{kind: "periodic_review_due"}], selection_binding: "heartbeat_receipt"}); + for (const receipt_review of [ + {...request.receipt_review, stop_condition_sha256: "0".repeat(64)}, + {...request.receipt_review, stop_contract_id: "unknown"}, + {...request.receipt_review, kind: "external_progress_review_drift"}, + ]) { + assert.throws(() => projectReplanSemantics({...request, receipt_review}), /identity conflicts/); + } +}); + test("mixed vision/outcome recovery preserves the dominant policy without discharging review", () => { for (const triggers of [[{kind: "vision_acceptance_gap"}], [{kind: "goal_outcome_uncovered"}, {kind: "vision_acceptance_gap"}], @@ -257,6 +318,34 @@ test("Monitor lifecycle changes retain the admitted review without discharging i } }); +test("Monitor receipt recovery preserves mixed-review precedence and the complete stop contract", () => { + const monitor = {kind: "monitor_no_change_streak", todo_id: "todo_monitor", run_count: 5, threshold: 5}; + const cases: [JsonObject[], string, boolean][] = [ + [[monitor], "monitor_no_change_streak", true], + [[monitor, {kind: "goal_outcome_uncovered"}], "goal_outcome_uncovered", true], + [[monitor, {kind: "vision_acceptance_gap"}], "vision_acceptance_gap", false], + [[{kind: "vision_acceptance_gap"}, monitor], "vision_acceptance_gap", false], + ]; + for (const [triggers, kind, acceptsProgress] of cases) { + const source = {schema_version: "autonomous_replan_obligation_v0", required: true, + obligation_id: "replan-1111111111111111", agent_id: "reviewer", + trigger_count: triggers.length, triggers, stop_condition: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION}; + assert.deepEqual(projectReplanSemantics({operation: "receipt_review_source", agent_id: "reviewer", + obligation: source}).review_source, {kind, stop_condition: source.stop_condition}); + const recovered = projectReplanSemantics({operation: "receipt_bound_obligation", guard_scoped: true, + replay_phase: "open", selected_obligation_id: source.obligation_id, agent_id: "reviewer", + current_obligation: null, transition_candidates: [], receipt_review: {kind, + stop_condition_sha256: createHash("sha256").update(source.stop_condition, "utf8").digest("hex"), + stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID}}).obligation as JsonObject; + assert.equal(recovered.obligation_id, source.obligation_id); + assert.equal(recovered.stop_condition, source.stop_condition); + assert.deepEqual(recovered.triggers, [{kind}]); + assert.equal(projectReplanSemantics({operation: "qualify", obligation: recovered}).accepted, false); + assert.equal(projectReplanSemantics({operation: "qualify", obligation: recovered, + observation_delta: {delta_kinds: ["new_surface"]}}).accepted, acceptsProgress); + } +}); + test("a recorded outcome review survives work-link refinement without cached context or discharge", () => { const id = "replan-1111111111111111"; const request = {operation: "receipt_bound_obligation", guard_scoped: true, diff --git a/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts b/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts index 4bd8ef4448..edff1eface 100644 --- a/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts +++ b/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts @@ -508,6 +508,38 @@ test("an admitted Todo-bound replan without verified writeback does not hold a l } }); +test("an admitted obligation-bound replan without verified writeback does not hold a later guard", async () => { + const turn = "turn-replan"; + const replanId = `replan-${"c".repeat(16)}`; + const identity = settlementIdentity({ + goal_id: GOAL, + agent_id: AGENT, + replan_obligation_id: replanId, + turn_instance_id: turn, + }); + const runtime = await runtimeWith([ + receipt(turn, { + replan_obligation_id: replanId, + semantic_replan_obligation_id: replanId, + settlement_effect_id: identity.effect_id, + closeout_required: false, + ok: true, + should_run: true, + interaction_mode: "autonomous_replan", + must_attempt_work: true, + delivery_allowed: false, + quiet_noop_allowed: false, + }), + ]); + try { + const result = await preflight(runtime.root); + assert.equal(result.status, "none"); + assert.equal(result.reason, "no_prior_turn_requires_closeout"); + } finally { + await runtime.close(); + } +}); + test("the current Turn, other goals, other agents, and other event kinds are ignored", async () => { const runtime = await runtimeWith([ receipt("current-turn", closeoutRequired("current-turn", "todo_current")), @@ -1096,6 +1128,71 @@ test("an autonomous replan binding recovers without a Todo binding", async () => } }); +test("an admitted obligation-bound replan with writeback resumes its original debit", async () => { + const turn = "turn-replan-writeback"; + const replanId = `replan-${"d".repeat(16)}`; + const identity = settlementIdentity({ + goal_id: GOAL, + agent_id: AGENT, + replan_obligation_id: replanId, + turn_instance_id: turn, + }); + const runtime = await runtimeWith([ + receipt(turn, { + replan_obligation_id: replanId, + semantic_replan_obligation_id: replanId, + settlement_effect_id: identity.effect_id, + closeout_required: false, + ok: true, + should_run: true, + interaction_mode: "autonomous_replan", + must_attempt_work: true, + delivery_allowed: false, + quiet_noop_allowed: false, + }), + { + schema_version: "loopx_rollout_event_v0", + event_id: "event-replan-writeback", + event_kind: "refresh_state", + goal_id: GOAL, + agent_id: AGENT, + run_id: turn, + details: {settlement_effect_id: identity.effect_id}, + }, + ]); + try { + const runsRoot = join(runtime.root, "goals", GOAL, "runs"); + await mkdir(runsRoot, {recursive: true}); + await writeFile(join(runsRoot, "index.jsonl"), `${JSON.stringify({ + classification: "state_refreshed", + delivery_outcome: "outcome_progress", + goal_id: GOAL, + agent_id: AGENT, + replan_obligation_id: replanId, + turn_instance_id: turn, + settlement_identity: identity, + })}\n`); + + const result = await preflight(runtime.root); + const candidate = candidateFrom(result); + assert.equal(candidate.binding_kind, "autonomous_replan"); + assert.equal(candidate.binding_id, replanId); + assert.equal(candidate.admitted_replan, true); + assert.deepEqual(result.missing_receipts, ["quota_spend_receipt"]); + + const verdict = reduce( + candidate, + result.missing_receipts as string[], + READ_TODO(null), + ); + assert.equal(verdict.status, "recovery_required"); + assert.equal((verdict.recovery as JsonObject).repair, "resume_prior_turn"); + assert.equal((verdict.obligation as JsonObject).repair, "resume_prior_turn"); + } finally { + await runtime.close(); + } +}); + test("candidate bindings are revalidated before any verdict", async () => { assert.throws( () => reduce({