diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index 89013b23fe..1734638130 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -4,11 +4,12 @@ import argparse from collections.abc import Callable, Mapping -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import TYPE_CHECKING, Any from ..capabilities.progress_review.context import external_progress_review_context +from ..control_plane.effect_runtime import EffectRuntimeRejected from ..control_plane.quota.effective_action import EffectiveAction from ..control_plane.quota.effect_program import SettlementIdentity from ..control_plane.quota.error_codes import HeartbeatReceiptIdentityConflictError @@ -18,6 +19,12 @@ find_heartbeat_receipt, heartbeat_receipt_request_subject, heartbeat_receipt_view, + repair_orphaned_identity_upgrade_heartbeat_receipt, + repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent, +) +from ..control_plane.quota.semantic_replan_guard_merge import ( + has_orphaned_identity_upgrade_replan_guard, + is_malformed_settlement_state_error, ) from ..control_plane.turn_driver.codex_context import context_delivery_for_arguments from ..file_lock import LockAcquireTimeoutError @@ -430,6 +437,28 @@ def execute_quota_should_run( execution.heartbeat_receipt_existing = action_selection.receipt execution.heartbeat_receipt_existing_status = "replayed" execution.heartbeat_receipt_existing_appended = False + mutable_should_run = ( + not getattr(args, "dry_run", False) + and not getattr(args, "scheduler_observation", False) + ) + if ( + mutable_should_run + and heartbeat_turn_id + and has_orphaned_identity_upgrade_replan_guard(execution.heartbeat_receipt_existing) + ): + repaired_receipt, repaired = repair_orphaned_identity_upgrade_heartbeat_receipt( + runtime_root, + goal_id=args.goal_id, + agent_id=args.agent_id, + turn_instance_id=heartbeat_turn_id, + goal_ref=goal_ref, + ) + if repaired and repaired_receipt is not None: + action_selection = replace(action_selection, receipt=repaired_receipt) + execution.action_selection = action_selection + execution.heartbeat_receipt_existing = repaired_receipt + execution.heartbeat_receipt_existing_status = "upgraded" + execution.heartbeat_receipt_existing_appended = True context_projector = turn_context_projector( registry_path=registry_path, @@ -440,39 +469,56 @@ def execute_quota_should_run( ) complete_context = not getattr(args, "scheduler_observation", False) outcome_navigation = complete_context and context_delivery_for_arguments(args)["progressive_enabled"] - payload = export("build_live_quota_should_run_decision")( - status_payload, - goal_id=args.goal_id, - agent_id=args.agent_id, - inline_goal_source=complete_context, - available_capabilities=args.available_capabilities, - include_scheduler_detail="scheduler" in detail_sections, - include_agent_todo_detail="agent-todos" in detail_sections, - codex_app_current_rrule=args.app_automation_current_rrule, - registry_path=registry_path, - runtime_root=runtime_root, - host_observation_resolver=export("resolve_codex_app_automation_rrule"), - scheduler_execution_context=scheduler_context, - operator_inbox_urgency_projector=operator_inbox_urgency_projector, - bounded_research_frontier_projector=export( + decision_builder = export("build_live_quota_should_run_decision") + decision_kwargs = { + "goal_id": args.goal_id, + "agent_id": args.agent_id, + "inline_goal_source": complete_context, + "available_capabilities": args.available_capabilities, + "include_scheduler_detail": "scheduler" in detail_sections, + "include_agent_todo_detail": "agent-todos" in detail_sections, + "codex_app_current_rrule": args.app_automation_current_rrule, + "registry_path": registry_path, + "runtime_root": runtime_root, + "host_observation_resolver": export("resolve_codex_app_automation_rrule"), + "scheduler_execution_context": scheduler_context, + "operator_inbox_urgency_projector": operator_inbox_urgency_projector, + "bounded_research_frontier_projector": export( "project_live_explore_composition_frontier" ), - progress_review_context_reader=external_progress_review_context, - receipt_bound_todo_id=action_selection.receipt_bound_todo_id, - requested_action_todo_id=action_selection.requested_todo_id_for_decision, - receipt_bound_replan_obligation_id=( + "progress_review_context_reader": external_progress_review_context, + "receipt_bound_todo_id": action_selection.receipt_bound_todo_id, + "requested_action_todo_id": action_selection.requested_todo_id_for_decision, + "receipt_bound_replan_obligation_id": ( action_selection.receipt_bound_replan_obligation_id ), - retained_action_selection_todo_id=( + "retained_action_selection_todo_id": ( action_selection.retained_todo_id_for_decision ), - turn_instance_id=heartbeat_turn_id, - interaction_projection_hooks=interaction_projection_hooks, - turn_start_hook_dispatch=turn_start_hook_dispatch, - turn_context_projector=context_projector, - context_navigation=outcome_navigation, - goal_ref=goal_ref, - ) + "turn_instance_id": heartbeat_turn_id, + "interaction_projection_hooks": interaction_projection_hooks, + "turn_start_hook_dispatch": turn_start_hook_dispatch, + "turn_context_projector": context_projector, + "context_navigation": outcome_navigation, + "goal_ref": goal_ref, + } + try: + payload = decision_builder(status_payload, **decision_kwargs) + except (ValueError, EffectRuntimeRejected) as exc: + if ( + mutable_should_run + and is_malformed_settlement_state_error(exc) + and repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent( + runtime_root, + goal_id=args.goal_id, + agent_id=args.agent_id, + goal_ref=goal_ref, + ) + > 0 + ): + payload = decision_builder(status_payload, **decision_kwargs) + else: + raise execution.payload = payload action_selection_preflight = export("reconcile_requested_quota_action_selection")( payload, @@ -520,6 +566,7 @@ def execute_quota_should_run( execution.heartbeat_receipt_existing and not execution.upgrade_recovery_wait ): + prior_repaired = execution.heartbeat_receipt_existing_appended ( execution.heartbeat_receipt_existing, execution.heartbeat_receipt_existing_status, @@ -536,6 +583,9 @@ def execute_quota_should_run( scheduler_execution_context=context.scheduler_context, status_payload=status_payload, ) + if prior_repaired and not execution.heartbeat_receipt_existing_appended: + execution.heartbeat_receipt_existing_status = "upgraded" + execution.heartbeat_receipt_existing_appended = True else: ( execution.payload, diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index a685d67086..109c6bce0a 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -392,6 +392,7 @@ export function createEffectRuntimeHandlers( ["quota.settlement.read", lazyHandler(() => import("./quota/settlement_readback.ts"), ({readQuotaSettlement}) => readQuotaSettlement)], ["quota.execution_loss_closeout.commit", lazyHandler(() => import("./quota/execution_loss_closeout.ts"), ({commitExecutionLossCloseout}) => commitExecutionLossCloseout)], ["quota.heartbeat_receipt.select", lazyHandler(() => import("./quota/heartbeat_receipt_identity.ts"), ({projectHeartbeatReceiptSelection}) => projectHeartbeatReceiptSelection)], + ["quota.semantic_replan_guard.validate", lazyHandler(() => import("./quota/semantic_replan_guard.ts"), ({validateSemanticReplanGuard}) => validateSemanticReplanGuard)], [ "quota.prior_host_turn_closeout.preflight", lazyHandler(() => import("./quota/unsettled_host_turn_recovery.ts"), ({preflightPriorHostTurnCloseout}) => preflightPriorHostTurnCloseout), diff --git a/loopx/control_plane/quota/error_codes.py b/loopx/control_plane/quota/error_codes.py index 83d988997c..4ee50be314 100644 --- a/loopx/control_plane/quota/error_codes.py +++ b/loopx/control_plane/quota/error_codes.py @@ -36,6 +36,12 @@ class HeartbeatReceiptIdentityConflictError(ValueError): """Public-safe diagnostic for a same-turn settlement identity conflict.""" +class MalformedSettlementStateError(ValueError): + """Public-safe diagnostic for persisted settlement state rejected by TS readback.""" + + diagnostic_code = "malformed_settlement_state" + + class QuotaRunIndexConflict(ValueError): """A quota spend was definitively rejected by the run-index CAS.""" diff --git a/loopx/control_plane/quota/heartbeat_receipt.py b/loopx/control_plane/quota/heartbeat_receipt.py index 7c02e42db0..14fa1798ec 100644 --- a/loopx/control_plane/quota/heartbeat_receipt.py +++ b/loopx/control_plane/quota/heartbeat_receipt.py @@ -18,6 +18,15 @@ from .effective_action import EffectiveAction from .effect_program import SettlementBindingKind, SettlementIdentity from .error_codes import HeartbeatReceiptIdentityConflictError +from .semantic_replan_guard_merge import ( + SEMANTIC_REPLAN_REVIEW_FIELDS, + append_repaired_identity_upgrade_receipt, + compute_repaired_identity_upgrade_replan_guard_details, + merge_semantic_replan_guard_details, + repair_orphaned_identity_upgrade_heartbeat_receipt as repair_orphaned_identity_upgrade_heartbeat_receipt, # noqa: F401 + repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent as repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent, # noqa: F401 + strip_semantic_replan_companions, +) from .settlement_workspace_causality import ( delivery_workspace_causality_from_event_details, ) @@ -26,12 +35,11 @@ HEARTBEAT_RECEIPT_SCHEMA_VERSION = "heartbeat_quota_receipt_v0" -def _heartbeat_receipt_events( +def _agent_heartbeat_receipt_events( events: list[dict[str, object]], *, goal_id: str, agent_id: str, - turn_instance_id: str, goal_ref: Mapping[str, object] | None, ) -> list[dict[str, object]]: from ..goals.source_session_registry_state import exact_goal_ref @@ -52,7 +60,6 @@ def _heartbeat_receipt_events( if event.get("event_kind") == "quota_should_run" and str(event.get("goal_id") or "") == goal_id and str(event.get("agent_id") or "") == agent_id - and str(event.get("run_id") or "") == turn_instance_id and ( event.get("goal_ref") == expected_goal_ref if expected_goal_ref is not None @@ -61,6 +68,23 @@ def _heartbeat_receipt_events( ] +def _heartbeat_receipt_events( + events: list[dict[str, object]], + *, + goal_id: str, + agent_id: str, + turn_instance_id: str, + goal_ref: Mapping[str, object] | None, +) -> list[dict[str, object]]: + return [ + event + for event in _agent_heartbeat_receipt_events( + events, goal_id=goal_id, agent_id=agent_id, goal_ref=goal_ref, + ) + if str(event.get("run_id") or "") == turn_instance_id + ] + + def heartbeat_receipt_request_subject(event: Mapping[str, object] | None) -> dict | None: """Transport the original request's path-free identity from scalar event details.""" details = (event or {}).get("details") @@ -241,6 +265,14 @@ def ensure_turn_heartbeat_settlement_receipt( and normalized_semantic_replan_obligation_id is None ): raise ValueError("Turn semantic replan obligation id is malformed") + if ( + semantic_replan_guard_scoped + and semantic_replan_capability_guard is not None + and normalized_semantic_replan_obligation_id is None + ): + raise ValueError( + "Turn semantic replan capability guard requires a selected obligation" + ) if quota_spend_source is not None and quota_spend_source not in TURN_SCOPED_SLOT_SPEND_SOURCES: raise ValueError("Turn quota spend source must be heartbeat or visible-goal") @@ -355,6 +387,12 @@ def ensure_turn_heartbeat_settlement_receipt( if task_lease_epoch is None: details.pop("prepared_lease_epoch", None) if semantic_replan_guard_scoped: + if semantic_replan_capability_guard is not None and any( + field in details for field in SEMANTIC_REPLAN_REVIEW_FIELDS + ): + raise HeartbeatReceiptIdentityConflictError( + "Turn heartbeat receipt belongs to a review guard" + ) details["semantic_replan_obligation_id"] = ( normalized_semantic_replan_obligation_id or "" ) @@ -362,6 +400,8 @@ def ensure_turn_heartbeat_settlement_receipt( details["semantic_replan_capability_id"] = semantic_replan_capability_guard["capability_id"] details["semantic_replan_gap_id"] = semantic_replan_capability_guard["gap_id"] details["semantic_replan_frontier_revision"] = semantic_replan_capability_guard["frontier_revision"] + elif normalized_semantic_replan_obligation_id is None: + details = strip_semantic_replan_companions(details) if (source := previous_source or quota_spend_source) is not None: details["quota_spend_source"] = source source_event_id = ( @@ -613,13 +653,32 @@ def upgrade_identityless_heartbeat_receipt( else {} ) if str(existing_details.get("settlement_effect_id") or "").strip(): + repaired_details = ( + compute_repaired_identity_upgrade_replan_guard_details( + effective, matching + ) + ) + if repaired_details is not None: + repaired = append_repaired_identity_upgrade_receipt( + log_path, + goal_id=goal_id, + agent_id=agent_id, + turn_instance_id=turn_instance_id, + effective=effective, + repaired_details=repaired_details, + goal_ref=goal_ref, + ) + return repaired, True return effective, False # The effective receipt was read while holding the rollout lock. Keep - # fields appended by a concurrent same-Turn revision unless this - # correction explicitly replaces them. - corrected_details = dict(effective_details) - corrected_details.update(details) + # non-conflicting fields appended by a concurrent same-Turn revision, + # while stripping orphaned semantic replan companion metadata whenever + # the guard selection clears, rotates, or changes kind. + corrected_details = merge_semantic_replan_guard_details( + effective_details, + details, + ) corrected_details.update( { "turn_instance_id": turn_instance_id, diff --git a/loopx/control_plane/quota/semantic_replan_guard.ts b/loopx/control_plane/quota/semantic_replan_guard.ts new file mode 100644 index 0000000000..778fce9ea5 --- /dev/null +++ b/loopx/control_plane/quota/semantic_replan_guard.ts @@ -0,0 +1,238 @@ +import { createHash } from "node:crypto"; +import { BARE_SHA256_PATTERN } from "../content_digest.ts"; +import type { JsonObject } from "../effect_program.ts"; +import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; +import { jsonObject, requireJsonObject, requireNonEmptyString } from "../runtime_decode.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 { normalizeHeartbeatReplanObligationId as normalizeReplanObligationId } from "./heartbeat_receipt_identity.ts"; + +export const SEMANTIC_REPLAN_GUARD_SCHEMA = "semantic_replan_guard_v0"; + +function decodeCapabilityGuard(value: unknown): JsonObject { + const guard = jsonObject(value); + if ( + !guard || + guard.schema_version !== "semantic_replan_capability_guard_v0" || + typeof guard.capability_id !== "string" || + !/^[a-z][a-z0-9-]{0,63}$/.test(guard.capability_id) || + typeof guard.gap_id !== "string" || + !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(guard.gap_id) || + typeof guard.frontier_revision !== "string" || + !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(guard.frontier_revision) || + Object.keys(guard).some( + (key) => + ![ + "schema_version", + "capability_id", + "gap_id", + "frontier_revision", + ].includes(key), + ) + ) { + throw new EffectRuntimeRequestError( + "heartbeat receipt capability guard is malformed", + "malformed_settlement_state", + ); + } + return guard; +} + +export function projectSemanticReplanGuard( + receiptDetails: JsonObject, +): 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", + "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", + ); + } + if (!Object.hasOwn(receiptDetails, "semantic_replan_obligation_id")) { + if (hasCapability) { + throw new EffectRuntimeRequestError( + "a capability guard requires a selected obligation", + "malformed_settlement_state", + ); + } + if (hasReview) { + throw new EffectRuntimeRequestError( + "a review source requires a selected obligation", + "malformed_settlement_state", + ); + } + return { + schema_version: SEMANTIC_REPLAN_GUARD_SCHEMA, + scope: "legacy_unscoped", + selected_obligation_id: null, + }; + } + const rawObligationId = receiptDetails.semantic_replan_obligation_id; + if (rawObligationId === "" || rawObligationId === null) { + if (hasCapability) { + throw new EffectRuntimeRequestError( + "a capability guard requires a selected obligation", + "malformed_settlement_state", + ); + } + if (hasReview) { + throw new EffectRuntimeRequestError( + "a review source requires a selected obligation", + "malformed_settlement_state", + ); + } + return { + schema_version: SEMANTIC_REPLAN_GUARD_SCHEMA, + scope: "turn_guard", + selected_obligation_id: null, + }; + } + const selectedObligationId = normalizeReplanObligationId(rawObligationId); + if (selectedObligationId === null) { + throw new EffectRuntimeRequestError( + "heartbeat receipt semantic replan guard is malformed", + "malformed_settlement_state", + ); + } + const reviewKind = hasReview + ? requireNonEmptyString( + receiptDetails.semantic_replan_review_kind, + "receipt review kind", + ) + : 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 === 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, + frontier_revision: receiptDetails.semantic_replan_frontier_revision, + }), + } + : {}), + }; +} + +/** Pure authoritative semantic replan guard validator for control-plane callers. */ +export function validateSemanticReplanGuard(value: unknown): JsonObject { + const input = requireJsonObject(value, "semantic replan guard validation request"); + const receiptDetails = requireJsonObject( + input.details, + "semantic replan guard details", + ); + try { + return { + valid: true, + guard: projectSemanticReplanGuard(receiptDetails), + }; + } catch (error) { + if (error instanceof EffectRuntimeRequestError) { + return { + valid: false, + diagnostic_code: error.code, + reason: error.message, + }; + } + throw error; + } +} diff --git a/loopx/control_plane/quota/semantic_replan_guard_merge.py b/loopx/control_plane/quota/semantic_replan_guard_merge.py new file mode 100644 index 0000000000..5ffe9a6509 --- /dev/null +++ b/loopx/control_plane/quota/semantic_replan_guard_merge.py @@ -0,0 +1,492 @@ +"""Semantic replan guard companion-field merge and repair helpers.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from functools import lru_cache +from pathlib import Path + +from ...file_lock import exclusive_cross_runtime_file_lock +from ...rollout_event_log import ( + _append_rollout_event_line, + build_rollout_event, + load_rollout_events, + rollout_event_log_path, +) +from ..effect_runtime import effect_runtime_result +from ..todos.contract import normalize_todo_id, normalize_todo_replan_obligation_id +from ..work_items.autonomous_replan_obligation import ( + AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION, +) +from .error_codes import ( + HeartbeatReceiptIdentityConflictError, + MalformedSettlementStateError, +) + +SEMANTIC_REPLAN_REVIEW_FIELDS = ( + "semantic_replan_review_kind", + "semantic_replan_review_stop_condition", + "semantic_replan_review_stop_condition_sha256", + "semantic_replan_review_stop_contract_id", +) +SEMANTIC_REPLAN_CAPABILITY_FIELDS = ( + "semantic_replan_capability_id", + "semantic_replan_gap_id", + "semantic_replan_frontier_revision", +) +SEMANTIC_REPLAN_COMPANION_FIELDS = ( + SEMANTIC_REPLAN_REVIEW_FIELDS + SEMANTIC_REPLAN_CAPABILITY_FIELDS +) +_SEMANTIC_REPLAN_GUARD_FIELDS = ( + "semantic_replan_obligation_id", + *SEMANTIC_REPLAN_COMPANION_FIELDS, +) + + +def _non_empty_str(value: object) -> str | None: + return value if isinstance(value, str) and value.strip() else None + + +@lru_cache(maxsize=512) +def _ts_semantic_replan_guard_valid(guard_json: str) -> bool: + """Validate guard fields through the single authoritative TypeScript owner.""" + + result = effect_runtime_result( + "quota.semantic_replan_guard.validate", + {"details": json.loads(guard_json)}, + ) + valid = result.get("valid") if isinstance(result, Mapping) else None + if not isinstance(valid, bool): + raise TypeError("TypeScript semantic replan guard validation shape mismatch") + return valid + + +def is_valid_semantic_replan_guard_details( + details: Mapping[str, object], +) -> bool: + """Delegate semantic replan guard validation to TS ``projectSemanticReplanGuard``.""" + + guard_fields = { + field: details[field] + for field in _SEMANTIC_REPLAN_GUARD_FIELDS + if field in details + } + if not guard_fields or ( + len(guard_fields) == 1 + and guard_fields.get("semantic_replan_obligation_id") in ("", None) + ): + return True + try: + guard_json = json.dumps(guard_fields, sort_keys=True, allow_nan=False) + except (TypeError, ValueError): + return False + return _ts_semantic_replan_guard_valid(guard_json) + + +def strip_semantic_replan_companions( + details: Mapping[str, object], +) -> dict[str, object]: + """Return a copy of receipt details with all semantic replan companions removed.""" + + stripped = dict(details) + for field in SEMANTIC_REPLAN_COMPANION_FIELDS: + stripped.pop(field, None) + return stripped + + +def merge_semantic_replan_guard_details( + effective_details: Mapping[str, object], + incoming_details: Mapping[str, object], +) -> dict[str, object]: + """Merge receipt details without leaving orphaned replan companion fields.""" + + corrected_details = dict(effective_details) + touches_semantic_guard = "semantic_replan_obligation_id" in incoming_details or any( + field in incoming_details for field in SEMANTIC_REPLAN_COMPANION_FIELDS + ) + if not touches_semantic_guard: + corrected_details.update(incoming_details) + return corrected_details + + existing_obligation = normalize_todo_replan_obligation_id( + effective_details.get("semantic_replan_obligation_id") + ) + if "semantic_replan_obligation_id" in incoming_details: + raw_incoming = incoming_details.get("semantic_replan_obligation_id") + incoming_obligation = normalize_todo_replan_obligation_id(raw_incoming) + if raw_incoming not in (None, "") and incoming_obligation is None: + raise HeartbeatReceiptIdentityConflictError( + "heartbeat receipt semantic replan guard is malformed" + ) + else: + incoming_obligation = existing_obligation + + incoming_has_review = any( + field in incoming_details for field in SEMANTIC_REPLAN_REVIEW_FIELDS + ) + incoming_has_capability = any( + field in incoming_details for field in SEMANTIC_REPLAN_CAPABILITY_FIELDS + ) + if incoming_has_review and incoming_has_capability: + raise HeartbeatReceiptIdentityConflictError( + "a review source cannot replace a capability guard" + ) + if (incoming_has_review or incoming_has_capability) and incoming_obligation is None: + raise HeartbeatReceiptIdentityConflictError( + "heartbeat receipt semantic replan guard requires a selected obligation" + ) + + if ( + incoming_obligation is None + or incoming_obligation != existing_obligation + or incoming_has_review + or incoming_has_capability + ): + corrected_details = strip_semantic_replan_companions(corrected_details) + + corrected_details.update(incoming_details) + return corrected_details + + +def has_orphaned_identity_upgrade_replan_guard( + event: Mapping[str, object] | None, +) -> bool: + """Fast check for an identity_upgrade receipt failing semantic replan validation.""" + + if not isinstance(event, Mapping): + return False + details = event.get("details") + if not isinstance(details, Mapping): + return False + if details.get("settlement_receipt_revision") != "identity_upgrade": + return False + if not str(details.get("settlement_effect_id") or "").strip(): + return False + return not is_valid_semantic_replan_guard_details(details) + + +def _causal_parent_receipt( + effective: Mapping[str, object], + matching: Sequence[Mapping[str, object]], +) -> tuple[Mapping[str, object], Mapping[str, object]] | None: + causality = effective.get("causality") + if not isinstance(causality, Mapping): + return None + source_event_id = str(causality.get("source_event_id") or "").strip() + caused_by = str(causality.get("caused_by") or "").strip() + if source_event_id and caused_by and source_event_id != caused_by: + return None + parent_id = source_event_id or caused_by + if not parent_id: + return None + effective_id = str(effective.get("event_id") or "").strip() + prior_events: Sequence[Mapping[str, object]] = matching + for index, event in enumerate(matching): + if event is effective or ( + effective_id and str(event.get("event_id") or "").strip() == effective_id + ): + prior_events = matching[:index] + break + parent = next( + ( + event + for event in reversed(prior_events) + if str(event.get("event_id") or "").strip() == parent_id + ), + None, + ) + if parent is None: + return None + parent_details = parent.get("details") + if not isinstance(parent_details, Mapping): + return None + if str(parent_details.get("settlement_effect_id") or "").strip(): + return None + if ( + normalize_todo_replan_obligation_id( + parent_details.get("semantic_replan_obligation_id") + ) + is None + ): + return None + if not is_valid_semantic_replan_guard_details(parent_details): + return None + return parent, parent_details + + +def _stale_fields_from_parent_overlay( + details: Mapping[str, object], + parent_details: Mapping[str, object], +) -> tuple[list[str], bool] | None: + """Identify parent-attributable stale guard fields left by legacy dict overlay.""" + + present_review = [f for f in SEMANTIC_REPLAN_REVIEW_FIELDS if f in details] + present_cap = [f for f in SEMANTIC_REPLAN_CAPABILITY_FIELDS if f in details] + parent_has_review = any(f in parent_details for f in SEMANTIC_REPLAN_REVIEW_FIELDS) + parent_has_cap = any(f in parent_details for f in SEMANTIC_REPLAN_CAPABILITY_FIELDS) + if parent_has_review == parent_has_cap: + return None + + raw_obligation = details.get("semantic_replan_obligation_id") + if "semantic_replan_obligation_id" in details and raw_obligation in (None, ""): + if present_review and present_cap: + return None + present = present_review + present_cap + if not present or not all( + f in parent_details and parent_details[f] == details[f] for f in present + ): + return None + return present, True + + if normalize_todo_replan_obligation_id(raw_obligation) is None: + return None + + # Mode B: review <-> capability kind rotation while parent was identity-less. + if present_review and present_cap: + stale = present_review if parent_has_review else present_cap + if not all( + f in parent_details and parent_details[f] == details[f] for f in stale + ): + return None + return stale, False + + if not present_review or not parent_has_review: + return None + + eff_stop = ( + _non_empty_str(details.get("semantic_replan_review_stop_condition")) + if "semantic_replan_review_stop_condition" in details + else None + ) + if "semantic_replan_review_stop_condition" in details and eff_stop is None: + return None + + # Mode C: digest-bound review rotated/shortened to an inline stop condition. + if ( + eff_stop is not None + and eff_stop != AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION + and parent_details.get("semantic_replan_review_stop_condition") + in (None, AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION) + and "semantic_replan_review_stop_condition_sha256" in parent_details + ): + stale_review: list[str] = [] + if "semantic_replan_review_stop_condition_sha256" in details: + if ( + details["semantic_replan_review_stop_condition_sha256"] + != parent_details["semantic_replan_review_stop_condition_sha256"] + ): + return None + stale_review.append("semantic_replan_review_stop_condition_sha256") + if "semantic_replan_review_stop_contract_id" in details: + if ( + "semantic_replan_review_stop_contract_id" not in parent_details + or details["semantic_replan_review_stop_contract_id"] + != parent_details["semantic_replan_review_stop_contract_id"] + ): + return None + stale_review.append("semantic_replan_review_stop_contract_id") + return (stale_review, False) if stale_review else None + + # Mode D: default-contract digest review rotated to a non-default digest review. + if ( + eff_stop in (None, AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION) + and "semantic_replan_review_stop_condition_sha256" in details + and details["semantic_replan_review_stop_condition_sha256"] + != parent_details.get("semantic_replan_review_stop_condition_sha256") + and "semantic_replan_review_stop_contract_id" in details + and "semantic_replan_review_stop_contract_id" in parent_details + and details["semantic_replan_review_stop_contract_id"] + == parent_details["semantic_replan_review_stop_contract_id"] + ): + return ["semantic_replan_review_stop_contract_id"], False + + return None + + +def compute_repaired_identity_upgrade_replan_guard_details( + effective: Mapping[str, object], + matching: Sequence[Mapping[str, object]], +) -> dict[str, object] | None: + """Derive cleaned details for a broken identity_upgrade if parent proof holds.""" + + if not has_orphaned_identity_upgrade_replan_guard(effective): + return None + details = effective.get("details") + if not isinstance(details, Mapping): + return None + causal = _causal_parent_receipt(effective, matching) + if causal is None: + return None + _, parent_details = causal + resolution = _stale_fields_from_parent_overlay(details, parent_details) + if resolution is None: + return None + stale_fields, clear_obligation = resolution + repaired_details = dict(details) + for field in stale_fields: + repaired_details.pop(field, None) + if clear_obligation: + repaired_details["semantic_replan_obligation_id"] = "" + repaired_details["settlement_receipt_revision"] = "identity_upgrade" + if not is_valid_semantic_replan_guard_details(repaired_details): + return None + return repaired_details + + +def is_repairable_orphaned_identity_upgrade_receipt( + effective: Mapping[str, object], + matching: Sequence[Mapping[str, object]], +) -> bool: + """Prove via causal parent lineage that identity_upgrade left stale guard fields.""" + + return ( + compute_repaired_identity_upgrade_replan_guard_details(effective, matching) + is not None + ) + + +def is_malformed_settlement_state_error(error: BaseException) -> bool: + """Return True when TS settlement readback emitted ``malformed_settlement_state``.""" + + return ( + isinstance(error, MalformedSettlementStateError) + or getattr(error, "diagnostic_code", None) == "malformed_settlement_state" + ) + + +def append_repaired_identity_upgrade_receipt( + log_path: Path, + *, + goal_id: str, + agent_id: str, + turn_instance_id: str, + effective: Mapping[str, object], + repaired_details: Mapping[str, object], + goal_ref: Mapping[str, object] | None, +) -> dict[str, object]: + """Append a corrective quota_should_run receipt preserving settlement binding.""" + + effective_details_value = effective.get("details") + effective_details: Mapping[str, object] = ( + effective_details_value if isinstance(effective_details_value, Mapping) else {} + ) + source_event_id = str(effective.get("event_id") or "").strip() or None + repaired = build_rollout_event( + goal_id=goal_id, + event_kind="quota_should_run", + goal_ref=goal_ref, + agent_id=agent_id, + todo_id=normalize_todo_id( + repaired_details.get("todo_id") or effective_details.get("todo_id") + ), + run_id=turn_instance_id, + status=str(effective.get("status") or "normal_run"), + summary=( + "heartbeat quota receipt repaired stale semantic replan guard " + f"for turn={turn_instance_id}" + ), + source_event_id=source_event_id, + caused_by=source_event_id, + details=dict(repaired_details), + ) + _append_rollout_event_line(log_path, repaired) + return repaired + + +def repair_orphaned_identity_upgrade_heartbeat_receipt( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, + turn_instance_id: str, + goal_ref: Mapping[str, object] | None = None, +) -> tuple[dict[str, object] | None, bool]: + """Append a same-binding cleanup event when identity_upgrade leaked parent guard.""" + + from .heartbeat_receipt import _effective_heartbeat_receipt, _heartbeat_receipt_events + + log_path = rollout_event_log_path(runtime_root, goal_id) + if not log_path.exists(): + return None, False + with exclusive_cross_runtime_file_lock( + log_path, operation="repair_heartbeat_receipt_replan_guard" + ): + events = load_rollout_events(log_path) + matching = _heartbeat_receipt_events( + events, + goal_id=goal_id, + agent_id=agent_id, + turn_instance_id=turn_instance_id, + goal_ref=goal_ref, + ) + effective, existing_identity = _effective_heartbeat_receipt(matching) + if effective is None or existing_identity is None: + return effective, False + repaired_details = compute_repaired_identity_upgrade_replan_guard_details( + effective, matching + ) + if repaired_details is None: + return effective, False + repaired = append_repaired_identity_upgrade_receipt( + log_path, + goal_id=goal_id, + agent_id=agent_id, + turn_instance_id=turn_instance_id, + effective=effective, + repaired_details=repaired_details, + goal_ref=goal_ref, + ) + return repaired, True + + +def repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, + goal_ref: Mapping[str, object] | None = None, +) -> int: + """Repair all historical Turn receipts for one agent that leaked parent guards.""" + + from .heartbeat_receipt import ( + _agent_heartbeat_receipt_events, + _effective_heartbeat_receipt, + ) + + log_path = rollout_event_log_path(runtime_root, goal_id) + if not log_path.exists(): + return 0 + with exclusive_cross_runtime_file_lock( + log_path, operation="repair_heartbeat_receipt_replan_guard" + ): + events = load_rollout_events(log_path) + agent_events = _agent_heartbeat_receipt_events( + events, goal_id=goal_id, agent_id=agent_id, goal_ref=goal_ref, + ) + events_by_turn: dict[str, list[dict[str, object]]] = {} + for event in agent_events: + turn_id = str(event.get("run_id") or "").strip() + if turn_id: + events_by_turn.setdefault(turn_id, []).append(event) + repaired_count = 0 + for turn_id, turn_events in events_by_turn.items(): + effective, existing_identity = _effective_heartbeat_receipt(turn_events) + if effective is None or existing_identity is None: + continue + repaired_details = compute_repaired_identity_upgrade_replan_guard_details( + effective, turn_events + ) + if repaired_details is None: + continue + append_repaired_identity_upgrade_receipt( + log_path, + goal_id=goal_id, + agent_id=agent_id, + turn_instance_id=turn_id, + effective=effective, + repaired_details=repaired_details, + goal_ref=goal_ref, + ) + repaired_count += 1 + return repaired_count diff --git a/loopx/control_plane/quota/settlement.py b/loopx/control_plane/quota/settlement.py index 455d202680..d1bb5edb18 100644 --- a/loopx/control_plane/quota/settlement.py +++ b/loopx/control_plane/quota/settlement.py @@ -12,7 +12,10 @@ from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result from ..settlement_driver import decode_settlement_result from .accounting_admission import quota_accounting_admission -from .error_codes import HeartbeatReceiptIdentityConflictError +from .error_codes import ( + HeartbeatReceiptIdentityConflictError, + MalformedSettlementStateError, +) from .effect_program import ( SETTLEMENT_IDENTITY_SCHEMA_VERSION, SETTLEMENT_PLAN_SCHEMA_VERSION, @@ -418,6 +421,8 @@ def read(admission: Mapping[str, Any] | None) -> Any: except EffectRuntimeRejected as exc: if exc.diagnostic_code == "heartbeat_receipt_identity_conflict": raise HeartbeatReceiptIdentityConflictError(str(exc)) from None + if exc.diagnostic_code == "malformed_settlement_state": + raise MalformedSettlementStateError(str(exc)) from None raise ValueError(str(exc)) from None if source_admission is not None: diff --git a/loopx/control_plane/quota/settlement_cli.py b/loopx/control_plane/quota/settlement_cli.py index b4f94e367d..3ff42d8fc9 100644 --- a/loopx/control_plane/quota/settlement_cli.py +++ b/loopx/control_plane/quota/settlement_cli.py @@ -599,10 +599,26 @@ def quota_rollout_details( ) 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 + capability_guard = ( + replan_packet.get("capability_guard") + if isinstance(replan_packet, Mapping) + else None ) - if isinstance(capability_guard, Mapping): + if ( + capability_guard is None + and semantic_replan_obligation_id + and isinstance(receipt, Mapping) + and normalize_todo_replan_obligation_id( + receipt.get("semantic_replan_obligation_id") + ) + == semantic_replan_obligation_id + ): + capability_guard = receipt.get("semantic_replan_capability_guard") + if ( + semantic_replan_obligation_id + and "semantic_replan_review_kind" not in details + and isinstance(capability_guard, Mapping) + ): details["semantic_replan_capability_id"] = capability_guard["capability_id"] details["semantic_replan_gap_id"] = capability_guard["gap_id"] details["semantic_replan_frontier_revision"] = capability_guard["frontier_revision"] diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index d4f46cbe19..64347eb04c 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { isAbsolute, join } from "node:path"; import {isDeepStrictEqual} from "node:util"; import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts"; @@ -26,7 +25,6 @@ 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 { @@ -84,10 +82,11 @@ 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"; + projectSemanticReplanGuard, + SEMANTIC_REPLAN_GUARD_SCHEMA, +} from "./semantic_replan_guard.ts"; + +export { projectSemanticReplanGuard, SEMANTIC_REPLAN_GUARD_SCHEMA }; import { parseQuotaAccountingOwner, quotaGoalRef, @@ -101,7 +100,6 @@ export const QUOTA_SETTLEMENT_READBACK_REQUEST_SCHEMA = "loopx_quota_settlement_readback_request_v0"; export const QUOTA_SETTLEMENT_READBACK_RESULT_SCHEMA = "loopx_quota_settlement_readback_result_v0"; -export const SEMANTIC_REPLAN_GUARD_SCHEMA = "semantic_replan_guard_v0"; // Where the guard compiles the repair for an owed prior Turn. The repair lane // depends on the bound Todo's facts, which this read model does not read, so @@ -560,85 +558,6 @@ function runEffectMatches( quotaSpendMetadataMatches(run.quota_spend_commit, effectRef, expectedEffectRef)); } -export function projectSemanticReplanGuard( - receiptDetails: JsonObject, -): 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", - "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"); - if (!Object.hasOwn(receiptDetails, "semantic_replan_obligation_id")) { - if (hasCapability) throw new EffectRuntimeRequestError("a capability guard requires a selected obligation", "malformed_settlement_state"); - if (hasReview) throw new EffectRuntimeRequestError("a review source requires a selected obligation", "malformed_settlement_state"); - return { - schema_version: SEMANTIC_REPLAN_GUARD_SCHEMA, - scope: "legacy_unscoped", - selected_obligation_id: null, - }; - } - const rawObligationId = receiptDetails.semantic_replan_obligation_id; - if (rawObligationId === "" || rawObligationId === null) { - if (hasCapability) throw new EffectRuntimeRequestError("a capability guard requires a selected obligation", "malformed_settlement_state"); - if (hasReview) throw new EffectRuntimeRequestError("a review source requires a selected obligation", "malformed_settlement_state"); - return { - schema_version: SEMANTIC_REPLAN_GUARD_SCHEMA, - scope: "turn_guard", - selected_obligation_id: null, - }; - } - const selectedObligationId = normalizeReplanObligationId(rawObligationId); - if (selectedObligationId === null) { - throw new EffectRuntimeRequestError( - "heartbeat receipt semantic replan guard is malformed", - "malformed_settlement_state", - ); - } - const reviewKind = hasReview ? requireNonEmptyString(receiptDetails.semantic_replan_review_kind, "receipt review kind") : 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 === 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, - frontier_revision: receiptDetails.semantic_replan_frontier_revision}), - } : {}), - }; -} - /** Upgrade a legacy bound review receipt without changing its Turn identity. * * Older receipts retained the selected replan obligation but not the review @@ -681,18 +600,6 @@ function requalifyHeartbeatReceipt( return {append: true, details: upgraded}; } -function decodeCapabilityGuard(value: unknown): JsonObject { - const guard = jsonObject(value); - if (!guard || guard.schema_version !== "semantic_replan_capability_guard_v0" - || typeof guard.capability_id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(guard.capability_id) - || typeof guard.gap_id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(guard.gap_id) - || typeof guard.frontier_revision !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(guard.frontier_revision) - || Object.keys(guard).some(key => !["schema_version", "capability_id", "gap_id", "frontier_revision"].includes(key))) { - throw new EffectRuntimeRequestError("heartbeat receipt capability guard is malformed", "malformed_settlement_state"); - } - return guard; -} - function runMatchesBinding(run: JsonObject, identity: SettlementIdentity): boolean { return normalizeTodoId(run.todo_id) === identity.todo_id && normalizeReplanObligationId(run.replan_obligation_id) === diff --git a/tests/control_plane/test_heartbeat_receipt.py b/tests/control_plane/test_heartbeat_receipt.py index 12064c82d3..f2f0159a58 100644 --- a/tests/control_plane/test_heartbeat_receipt.py +++ b/tests/control_plane/test_heartbeat_receipt.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from pathlib import Path @@ -458,3 +459,1487 @@ def rows(): assert replay["effective_action"] == "heartbeat_settled_skip" assert replay["heartbeat_receipt"]["settlement_identity"] == identity assert rows() == before + + +def _digest_review_details(obligation_id: str) -> dict[str, object]: + import hashlib + from loopx.control_plane.work_items.autonomous_replan_obligation import ( + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID, + AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION, + ) + + return { + "semantic_replan_obligation_id": 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": hashlib.sha256( + AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION.encode("utf-8") + ).hexdigest(), + "semantic_replan_review_stop_contract_id": AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID, + } + + +def _capability_guard_details(obligation_id: str) -> dict[str, object]: + return { + "semantic_replan_obligation_id": obligation_id, + "semantic_replan_capability_id": "explore", + "semantic_replan_gap_id": "research-composition-0123456789abcdef", + "semantic_replan_frontier_revision": "research-composition-v0:0123456789abcdef", + } + + +def test_identity_upgrade_clearing_semantic_replan_strips_stale_review_fields( + tmp_path: Path, +) -> None: + append_rollout_event( + rollout_event_log_path(tmp_path, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=TURN_ID, + status="normal_run", + details={ + "stall_observation": "not_applicable", + **_digest_review_details("replan-1111111111111111"), + }, + ), + ) + + upgraded, appended = upgrade_identityless_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=EFFECT_ID, + status="normal_run", + summary="heartbeat quota receipt upgraded after periodic review cleared", + details={ + "stall_observation": "not_applicable", + "todo_id": TODO_ID, + "semantic_replan_obligation_id": "", + }, + ) + + assert appended is True + for field in ( + "semantic_replan_review_kind", + "semantic_replan_review_stop_condition", + "semantic_replan_review_stop_condition_sha256", + "semantic_replan_review_stop_contract_id", + ): + assert field not in upgraded["details"] + + readback = read_heartbeat_settlement( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=TODO_ID, + turn_instance_id=TURN_ID, + ) + assert readback is not None + assert readback.identity.failure is None + assert readback.semantic_replan_guard == { + "schema_version": "semantic_replan_guard_v0", + "scope": "turn_guard", + "selected_obligation_id": None, + } + + +def test_identity_upgrade_clearing_semantic_replan_strips_stale_capability_fields( + tmp_path: Path, +) -> None: + append_rollout_event( + rollout_event_log_path(tmp_path, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=TURN_ID, + status="normal_run", + details={ + "stall_observation": "not_applicable", + **_capability_guard_details("replan-1111111111111111"), + }, + ), + ) + + upgraded, appended = upgrade_identityless_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=EFFECT_ID, + status="normal_run", + summary="heartbeat quota receipt upgraded after capability guard cleared", + details={ + "stall_observation": "not_applicable", + "todo_id": TODO_ID, + "semantic_replan_obligation_id": "", + }, + ) + + assert appended is True + for field in ( + "semantic_replan_capability_id", + "semantic_replan_gap_id", + "semantic_replan_frontier_revision", + ): + assert field not in upgraded["details"] + + readback = read_heartbeat_settlement( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=TODO_ID, + turn_instance_id=TURN_ID, + ) + assert readback is not None + assert readback.identity.failure is None + assert readback.semantic_replan_guard == { + "schema_version": "semantic_replan_guard_v0", + "scope": "turn_guard", + "selected_obligation_id": None, + } + + +def test_identity_upgrade_replan_guard_rotation_and_review_kind_switch( + tmp_path: Path, +) -> None: + cap_to_review = tmp_path / "cap-to-review" + append_rollout_event( + rollout_event_log_path(cap_to_review, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=TURN_ID, + status="normal_run", + details={ + "stall_observation": "not_applicable", + **_capability_guard_details("replan-1111111111111111"), + }, + ), + ) + switched, appended = upgrade_identityless_heartbeat_receipt( + cap_to_review, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=EFFECT_ID, + status="normal_run", + summary="capability guard replaced by review guard", + details={ + "stall_observation": "not_applicable", + "todo_id": TODO_ID, + "semantic_replan_obligation_id": "replan-2222222222222222", + "semantic_replan_review_kind": "goal_outcome_uncovered", + "semantic_replan_review_stop_condition": "Stop at owner-only decisions.", + }, + ) + assert appended is True + for field in ( + "semantic_replan_capability_id", + "semantic_replan_gap_id", + "semantic_replan_frontier_revision", + ): + assert field not in switched["details"] + readback_cap = read_heartbeat_settlement( + cap_to_review, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=TODO_ID, + turn_instance_id=TURN_ID, + ) + assert readback_cap is not None + assert readback_cap.semantic_replan_guard == { + "schema_version": "semantic_replan_guard_v0", + "scope": "turn_guard", + "selected_obligation_id": "replan-2222222222222222", + "selected_review_source": { + "kind": "goal_outcome_uncovered", + "stop_condition": "Stop at owner-only decisions.", + }, + } + + digest_to_inline = tmp_path / "digest-to-inline" + append_rollout_event( + rollout_event_log_path(digest_to_inline, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=TURN_ID, + status="normal_run", + details={ + "stall_observation": "not_applicable", + **_digest_review_details("replan-1111111111111111"), + }, + ), + ) + inline, appended_inline = upgrade_identityless_heartbeat_receipt( + digest_to_inline, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=EFFECT_ID, + status="normal_run", + summary="digest review guard replaced by short inline review guard", + details={ + "stall_observation": "not_applicable", + "todo_id": TODO_ID, + "semantic_replan_obligation_id": "replan-2222222222222222", + "semantic_replan_review_kind": "goal_outcome_uncovered", + "semantic_replan_review_stop_condition": "Stop at owner-only decisions.", + }, + ) + assert appended_inline is True + assert "semantic_replan_review_stop_condition_sha256" not in inline["details"] + assert "semantic_replan_review_stop_contract_id" not in inline["details"] + readback_inline = read_heartbeat_settlement( + digest_to_inline, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=TODO_ID, + turn_instance_id=TURN_ID, + ) + assert readback_inline is not None + assert readback_inline.semantic_replan_guard == { + "schema_version": "semantic_replan_guard_v0", + "scope": "turn_guard", + "selected_obligation_id": "replan-2222222222222222", + "selected_review_source": { + "kind": "goal_outcome_uncovered", + "stop_condition": "Stop at owner-only decisions.", + }, + } + + +def test_replan_binding_preserves_existing_review_guard_when_details_empty( + tmp_path: Path, +) -> None: + obligation_id = "replan-2222222222222222" + review_details = _digest_review_details(obligation_id) + append_rollout_event( + rollout_event_log_path(tmp_path, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=TURN_ID, + status="autonomous_replan_required", + summary="identity-less autonomous replan receipt with review source", + details={ + "interaction_mode": "autonomous_replan", + "ok": True, + "should_run": True, + "must_attempt_work": True, + "delivery_allowed": False, + "quiet_noop_allowed": False, + **review_details, + }, + ), + ) + + bound, appended = bind_replan_successor_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + replan_obligation_id=obligation_id, + ) + + assert appended is True + for key, value in review_details.items(): + assert bound["details"][key] == value + + readback = read_heartbeat_settlement( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=None, + turn_instance_id=TURN_ID, + replan_obligation_id=obligation_id, + ) + assert readback is not None + assert readback.identity.failure is None + assert readback.semantic_replan_guard is not None + assert readback.semantic_replan_guard["selected_obligation_id"] == obligation_id + assert readback.semantic_replan_guard["selected_review_source"] == { + "kind": "periodic_review_due", + "stop_condition": review_details["semantic_replan_review_stop_condition"], + "stop_condition_sha256": review_details["semantic_replan_review_stop_condition_sha256"], + "stop_contract_id": review_details["semantic_replan_review_stop_contract_id"], + } + + +def test_identity_upgrade_rejects_contradictory_semantic_replan_details_without_appending( + tmp_path: Path, +) -> None: + log_path = rollout_event_log_path(tmp_path, GOAL_ID) + append_rollout_event( + log_path, + build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=TURN_ID, + status="normal_run", + details={ + "stall_observation": "not_applicable", + "semantic_replan_obligation_id": "replan-1111111111111111", + }, + ), + ) + before = log_path.read_bytes() + + with pytest.raises(HeartbeatReceiptIdentityConflictError, match="selected obligation"): + upgrade_identityless_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=EFFECT_ID, + status="normal_run", + summary="invalid empty obligation with review field", + details={ + "semantic_replan_obligation_id": "", + "semantic_replan_review_kind": "periodic_review_due", + }, + ) + with pytest.raises(HeartbeatReceiptIdentityConflictError, match="capability guard"): + upgrade_identityless_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=EFFECT_ID, + status="normal_run", + summary="invalid simultaneous review and capability fields", + details={ + "semantic_replan_obligation_id": "replan-1111111111111111", + "semantic_replan_review_kind": "periodic_review_due", + "semantic_replan_capability_id": "explore", + }, + ) + + assert log_path.read_bytes() == before + + +def test_quota_rollout_details_capability_guard_fallback_boundaries() -> None: + from argparse import Namespace + from loopx.control_plane.quota.settlement_cli import quota_rollout_details + + cap_guard = { + "schema_version": "semantic_replan_capability_guard_v0", + "capability_id": "explore", + "gap_id": "research-composition-0123456789abcdef", + "frontier_revision": "research-composition-v0:0123456789abcdef", + } + args = Namespace(quota_command="should-run", agent_id=AGENT_ID) + stale_receipt = { + "semantic_replan_obligation_id": "replan-1111111111111111", + "semantic_replan_capability_guard": cap_guard, + } + + # 1. Packet has no obligation -> stale capability guard must NOT be copied. + cleared = quota_rollout_details( + {"heartbeat_receipt": stale_receipt, "replan_action_packet": None}, + args, + todo_id=TODO_ID, + ) + assert cleared["semantic_replan_obligation_id"] == "" + assert "semantic_replan_capability_id" not in cleared + + # 2. Packet rotates to a different obligation -> stale capability guard must NOT be copied. + rotated = quota_rollout_details( + { + "heartbeat_receipt": stale_receipt, + "replan_action_packet": {"obligation_id": "replan-2222222222222222"}, + }, + args, + todo_id=None, + replan_obligation_id="replan-2222222222222222", + ) + assert "semantic_replan_capability_id" not in rotated + + # 3. Same obligation populates a review kind -> capability guard must NOT mix with review fields. + review_same = quota_rollout_details( + { + "heartbeat_receipt": stale_receipt, + "replan_action_packet": {"obligation_id": "replan-1111111111111111"}, + "autonomous_replan_obligation": { + "schema_version": "autonomous_replan_obligation_v0", + "required": True, + "agent_id": AGENT_ID, + "obligation_id": "replan-1111111111111111", + "trigger_count": 1, + "triggers": [{"kind": "periodic_review_due"}], + "stop_condition": "Stop at owner-only decisions.", + }, + }, + args, + todo_id=None, + replan_obligation_id="replan-1111111111111111", + ) + assert review_same["semantic_replan_review_kind"] == "periodic_review_due" + assert "semantic_replan_capability_id" not in review_same + + # 4. Matching non-review obligation without inline capability_guard -> preserve receipt fallback. + preserved = quota_rollout_details( + { + "heartbeat_receipt": stale_receipt, + "replan_action_packet": {"obligation_id": "replan-1111111111111111"}, + }, + args, + todo_id=None, + replan_obligation_id="replan-1111111111111111", + ) + assert preserved["semantic_replan_capability_id"] == "explore" + assert preserved["semantic_replan_gap_id"] == cap_guard["gap_id"] + assert preserved["semantic_replan_frontier_revision"] == cap_guard["frontier_revision"] + + +def test_turn_guard_rejects_capability_guard_without_obligation_before_lock_and_before_bind( + tmp_path: Path, +) -> None: + from loopx.control_plane.quota.effect_program import SettlementIdentity + from loopx.control_plane.quota.heartbeat_receipt import ( + ensure_turn_heartbeat_settlement_receipt, + ) + + called: list[bool] = [] + identity = SettlementIdentity(GOAL_ID, AGENT_ID, TODO_ID, TURN_ID) + cap_guard = { + "schema_version": "semantic_replan_capability_guard_v0", + "capability_id": "explore", + "gap_id": "research-composition-0123456789abcdef", + "frontier_revision": "research-composition-v0:0123456789abcdef", + } + + with pytest.raises(ValueError, match="selected obligation"): + ensure_turn_heartbeat_settlement_receipt( + tmp_path, + identity, + semantic_replan_guard_scoped=True, + semantic_replan_obligation_id=None, + semantic_replan_capability_guard=cap_guard, + before_bind=lambda: called.append(True), + ) + + assert called == [] + assert not rollout_event_log_path(tmp_path, GOAL_ID).exists() + + +def _append_legacy_main_orphaned_identity_upgrade_receipt( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, + todo_id: str, + turn_instance_id: str, + companion_details: dict[str, object], + upgrade_overlay: dict[str, object] | None = None, + bind_parent: bool = False, + break_lineage: bool = False, +) -> tuple[dict[str, object], dict[str, object], str]: + from loopx.control_plane.quota.effect_program import SettlementIdentity + + identity = SettlementIdentity( + goal_id=goal_id, + agent_id=agent_id, + todo_id=todo_id, + turn_instance_id=turn_instance_id, + ) + log_path = rollout_event_log_path(runtime_root, goal_id) + base_details: dict[str, object] = { + "command": "quota", + "quota_command": "should-run", + "ok": True, + "should_run": True, + "must_attempt_work": True, + "delivery_allowed": True, + "quiet_noop_allowed": False, + "interaction_mode": "execution", + "closeout_required": True, + "stall_observation": "not_applicable", + "quota_spend_source": "heartbeat", + "selected_todo_id": todo_id, + "todo_id": todo_id if bind_parent else "", + "replan_obligation_id": "", + "settlement_effect_id": identity.effect_id if bind_parent else "", + } + parent_details = {**base_details, **companion_details} + parent = append_rollout_event( + log_path, + build_rollout_event( + goal_id=goal_id, + event_kind="quota_should_run", + agent_id=agent_id, + run_id=turn_instance_id, + status="should-run", + summary="legacy identity-less receipt with semantic replan guard", + details=parent_details, + ), + ) + orphaned_source = ( + None if break_lineage else str(parent["event_id"]) + ) + upgraded_details: dict[str, object] = { + **parent_details, + "turn_instance_id": turn_instance_id, + "todo_id": todo_id, + "semantic_replan_obligation_id": "", + "settlement_effect_id": identity.effect_id, + "settlement_receipt_revision": "identity_upgrade", + } + if upgrade_overlay is not None: + upgraded_details.update(upgrade_overlay) + bad_upgrade = append_rollout_event( + log_path, + build_rollout_event( + goal_id=goal_id, + event_kind="quota_should_run", + agent_id=agent_id, + todo_id=todo_id, + run_id=turn_instance_id, + status="should-run", + summary=f"heartbeat quota receipt upgraded for turn={turn_instance_id}", + source_event_id=orphaned_source, + caused_by=orphaned_source, + details=upgraded_details, + ), + ) + return parent, bad_upgrade, identity.effect_id + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_cli_recovers_legacy_main_orphaned_identity_upgrade_receipt_and_settles( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID as actor, + GOAL_ID as goal, + TODO_ID as work, + _initialize_fixture_authority, + _run_cli, + _run_generated_cli, + _spend_run_count, + _write_fixture, + ) + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider=provider) + turn = "recover-legacy-main-identity-upgrade" + _, bad_upgrade, expected_effect_id = ( + _append_legacy_main_orphaned_identity_upgrade_receipt( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + companion_details=_digest_review_details("replan-1111111111111111"), + ) + ) + log_path = rollout_event_log_path(runtime, goal) + before_bytes = log_path.read_bytes() + + guard_args = ( + "quota", + "should-run", + "--codex-app", + "--goal-id", + goal, + "--agent-id", + actor, + "--todo-id", + work, + "--turn-instance-id", + turn, + ) + + # Dry-run stays strictly read-only even when the historical receipt is broken. + _run_cli(registry, runtime, *guard_args, "--dry-run") + assert log_path.read_bytes() == before_bytes + + rc1, retry1 = _run_cli(registry, runtime, *guard_args) + assert rc1 == 0, retry1 + assert retry1["ok"] is True + assert retry1["state"] == "eligible" + assert retry1["heartbeat_receipt"]["status"] == "upgraded" + assert ( + retry1["heartbeat_receipt"]["settlement_identity"]["effect_id"] + == expected_effect_id + ) + events_after_r1 = load_rollout_events(log_path) + assert len(events_after_r1) == 3 + repaired_event = events_after_r1[-1] + assert repaired_event["causality"]["caused_by"] == bad_upgrade["event_id"] + for field in ( + "semantic_replan_review_kind", + "semantic_replan_review_stop_condition", + "semantic_replan_review_stop_condition_sha256", + "semantic_replan_review_stop_contract_id", + ): + assert field not in repaired_event["details"] + + readback = read_heartbeat_settlement( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + registry_path=registry, + ) + assert readback is not None + assert readback.identity.failure is None + assert readback.admission_event_id == bad_upgrade["event_id"] + assert readback.semantic_replan_guard == { + "schema_version": "semantic_replan_guard_v0", + "scope": "turn_guard", + "selected_obligation_id": None, + } + + bytes_after_r1 = log_path.read_bytes() + rc2, retry2 = _run_cli(registry, runtime, *guard_args) + assert rc2 == 0, retry2 + assert retry2["ok"] is True + assert retry2["state"] == "eligible" + assert retry2["heartbeat_receipt"]["status"] == "replayed" + assert ( + retry2["heartbeat_receipt"]["settlement_identity"] + == retry1["heartbeat_receipt"]["settlement_identity"] + ) + assert log_path.read_bytes() == bytes_after_r1 + + (project / "validated-result.txt").write_text( + "Validated delivery after identity_upgrade companion cleanup.\n" + ) + plan = retry2["interaction_contract"]["cli_channel"]["settlement_plan"] + command = next( + s["command_template"] + for s in plan["ordered_steps"] + if s["kind"] == "durable_writeback" + ) + command = ( + command.replace("", "recovered_identity_upgrade") + .replace("", "single_surface") + .replace("", "outcome_progress") + ) + command += ( + " --delivery-boundary in_flight_continuation" + " --progress-result-class advanced" + f" --progress-work-item-id {work}" + " --progress-evidence-id evidence:recovered-result" + " --no-global-sync --suppress-external-sinks" + ) + rc_wb, written = _run_generated_cli(command, registry_path=registry, cwd=project) + assert rc_wb == 0, written + assert written["settlement_progress"]["state"] == "settled" + assert _spend_run_count(runtime) == 1 + + rc3, settled = _run_cli(registry, runtime, *guard_args) + assert rc3 == 0, settled + assert settled["effective_action"] == "heartbeat_settled_skip" + assert ( + settled["heartbeat_receipt"]["settlement_identity"] + == retry1["heartbeat_receipt"]["settlement_identity"] + ) + + +def test_cli_recovers_prior_turn_orphaned_identity_upgrade_without_blocked_health( + tmp_path: Path, +) -> None: + from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID as actor, + GOAL_ID as goal, + TODO_ID as work, + _initialize_fixture_authority, + _run_cli, + _write_fixture, + ) + + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider="file") + prior_turn = "prior-turn-main-identity-upgrade" + _, _, expected_effect_id = _append_legacy_main_orphaned_identity_upgrade_receipt( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=prior_turn, + companion_details=_digest_review_details("replan-1111111111111111"), + ) + + rc, result = _run_cli( + registry, + runtime, + "quota", + "should-run", + "--codex-app", + "--goal-id", + goal, + "--agent-id", + actor, + "--turn-instance-id", + "fresh-followup-turn", + ) + assert rc == 0, result + assert result["state"] != "blocked_health" + assert ( + result["unsettled_host_turn_recovery"]["prior_turn_instance_id"] + == prior_turn + ) + repaired_prior = find_heartbeat_receipt( + runtime, goal_id=goal, agent_id=actor, turn_instance_id=prior_turn + ) + assert repaired_prior is not None + assert repaired_prior["details"]["settlement_effect_id"] == expected_effect_id + assert "semantic_replan_review_kind" not in repaired_prior["details"] + + +@pytest.mark.parametrize( + ("companion_builder", "stripped_fields"), + [ + ( + _digest_review_details, + ( + "semantic_replan_review_kind", + "semantic_replan_review_stop_condition", + "semantic_replan_review_stop_condition_sha256", + "semantic_replan_review_stop_contract_id", + ), + ), + ( + _capability_guard_details, + ( + "semantic_replan_capability_id", + "semantic_replan_gap_id", + "semantic_replan_frontier_revision", + ), + ), + ], + ids=["review-companions", "capability-companions"], +) +def test_upgrade_api_recovers_existing_bound_identity_upgrade_idempotently( + tmp_path: Path, + companion_builder: Callable[[str], dict[str, object]], + stripped_fields: tuple[str, ...], +) -> None: + companion_details = companion_builder("replan-1111111111111111") + _, _, expected_effect_id = _append_legacy_main_orphaned_identity_upgrade_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=TODO_ID, + turn_instance_id=TURN_ID, + companion_details=companion_details, + ) + + repaired, appended = upgrade_identityless_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=expected_effect_id, + status="normal_run", + summary="recover bound identity_upgrade receipt", + details={ + "stall_observation": "not_applicable", + "todo_id": TODO_ID, + "semantic_replan_obligation_id": "", + }, + ) + assert appended is True + assert repaired["details"]["settlement_effect_id"] == expected_effect_id + for field in stripped_fields: + assert field not in repaired["details"] + + log_path = rollout_event_log_path(tmp_path, GOAL_ID) + after_first = log_path.read_bytes() + replayed, appended_again = upgrade_identityless_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=expected_effect_id, + status="normal_run", + summary="replay after repair", + details={ + "stall_observation": "not_applicable", + "todo_id": TODO_ID, + "semantic_replan_obligation_id": "", + }, + ) + assert appended_again is False + assert replayed == repaired + assert log_path.read_bytes() == after_first + + readback = read_heartbeat_settlement( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=TODO_ID, + turn_instance_id=TURN_ID, + ) + assert readback is not None + assert readback.identity.failure is None + assert readback.semantic_replan_guard == { + "schema_version": "semantic_replan_guard_v0", + "scope": "turn_guard", + "selected_obligation_id": None, + } + + +def test_orphaned_identity_upgrade_without_causal_lineage_fails_closed( + tmp_path: Path, +) -> None: + from loopx.control_plane.quota.heartbeat_receipt import ( + repair_orphaned_identity_upgrade_heartbeat_receipt, + ) + from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID as actor, + GOAL_ID as goal, + TODO_ID as work, + _initialize_fixture_authority, + _run_cli, + _write_fixture, + ) + + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider="file") + turn = "parentless-bad-upgrade" + _, bad_upgrade, _ = _append_legacy_main_orphaned_identity_upgrade_receipt( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + companion_details=_digest_review_details("replan-1111111111111111"), + break_lineage=True, + ) + log_path = rollout_event_log_path(runtime, goal) + before = log_path.read_bytes() + + effective, repaired = repair_orphaned_identity_upgrade_heartbeat_receipt( + runtime, + goal_id=goal, + agent_id=actor, + turn_instance_id=turn, + ) + assert repaired is False + assert effective == bad_upgrade + assert log_path.read_bytes() == before + + rc, failed = _run_cli( + registry, + runtime, + "quota", + "should-run", + "--codex-app", + "--goal-id", + goal, + "--agent-id", + actor, + "--todo-id", + work, + "--turn-instance-id", + turn, + ) + assert rc == 1 + assert failed["state"] == "blocked_health" + assert log_path.read_bytes() == before + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_cli_recovers_legacy_main_rotated_digest_to_inline_review_and_settles( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + from loopx.control_plane.quota.error_codes import MalformedSettlementStateError + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID as actor, + GOAL_ID as goal, + TODO_ID as work, + _initialize_fixture_authority, + _run_cli, + _run_generated_cli, + _spend_run_count, + _write_fixture, + ) + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider=provider) + turn = "recover-rotated-digest-to-inline" + rotated_obligation = "replan-2222222222222222" + rotated_stop = "Stop after validating rotated obligation B." + _, bad_upgrade, expected_effect_id = ( + _append_legacy_main_orphaned_identity_upgrade_receipt( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + companion_details=_digest_review_details("replan-1111111111111111"), + upgrade_overlay={ + "semantic_replan_obligation_id": rotated_obligation, + "semantic_replan_review_kind": "goal_outcome_uncovered", + "semantic_replan_review_stop_condition": rotated_stop, + }, + ) + ) + log_path = rollout_event_log_path(runtime, goal) + before_bytes = log_path.read_bytes() + + with pytest.raises(MalformedSettlementStateError) as exc_info: + read_heartbeat_settlement( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + registry_path=registry, + ) + assert exc_info.value.diagnostic_code == "malformed_settlement_state" + + guard_args = ( + "quota", + "should-run", + "--codex-app", + "--goal-id", + goal, + "--agent-id", + actor, + "--todo-id", + work, + "--turn-instance-id", + turn, + ) + + _run_cli(registry, runtime, *guard_args, "--dry-run") + assert log_path.read_bytes() == before_bytes + + rc1, retry1 = _run_cli(registry, runtime, *guard_args) + assert rc1 == 0, retry1 + assert retry1["ok"] is True + assert retry1["state"] == "eligible" + assert retry1["heartbeat_receipt"]["status"] == "upgraded" + assert ( + retry1["heartbeat_receipt"]["settlement_identity"]["effect_id"] + == expected_effect_id + ) + events_after_r1 = load_rollout_events(log_path) + assert len(events_after_r1) == 3 + repaired_event = events_after_r1[-1] + assert repaired_event["causality"]["caused_by"] == bad_upgrade["event_id"] + assert repaired_event["details"]["semantic_replan_obligation_id"] == rotated_obligation + assert repaired_event["details"]["semantic_replan_review_stop_condition"] == rotated_stop + assert "semantic_replan_review_stop_condition_sha256" not in repaired_event["details"] + assert "semantic_replan_review_stop_contract_id" not in repaired_event["details"] + + readback = read_heartbeat_settlement( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + registry_path=registry, + ) + assert readback is not None + assert readback.identity.failure is None + assert readback.admission_event_id == bad_upgrade["event_id"] + assert readback.semantic_replan_guard == { + "schema_version": "semantic_replan_guard_v0", + "scope": "turn_guard", + "selected_obligation_id": rotated_obligation, + "selected_review_source": { + "kind": "goal_outcome_uncovered", + "stop_condition": rotated_stop, + }, + } + + bytes_after_r1 = log_path.read_bytes() + rc2, retry2 = _run_cli(registry, runtime, *guard_args) + assert rc2 == 0, retry2 + assert retry2["ok"] is True + assert retry2["state"] == "eligible" + assert retry2["heartbeat_receipt"]["status"] == "replayed" + assert ( + retry2["heartbeat_receipt"]["settlement_identity"] + == retry1["heartbeat_receipt"]["settlement_identity"] + ) + assert log_path.read_bytes() == bytes_after_r1 + + (project / "validated-rotated-result.txt").write_text( + "Validated delivery after rotated identity_upgrade cleanup.\n" + ) + plan = retry2["interaction_contract"]["cli_channel"]["settlement_plan"] + command = next( + s["command_template"] + for s in plan["ordered_steps"] + if s["kind"] == "durable_writeback" + ) + command = ( + command.replace("", "recovered_rotated_identity_upgrade") + .replace("", "single_surface") + .replace("", "outcome_progress") + ) + command += ( + " --delivery-boundary semantic_closeout" + " --autonomous-replan-recorded" + " --repair-delta-kind successor_or_supersede" + " --progress-result-class advanced" + f" --progress-work-item-id {work}" + " --progress-surface-id surface:rotated-review" + " --progress-hypothesis-id hypothesis:rotated-review" + " --progress-probe-kind probe:rotated-review" + " --progress-evidence-id evidence:recovered-rotated-result" + " --no-global-sync --suppress-external-sinks" + ) + rc_wb, written = _run_generated_cli(command, registry_path=registry, cwd=project) + assert rc_wb == 0, written + if written["settlement_progress"]["state"] != "settled": + spend_command = next( + s["command_template"] + for s in plan["ordered_steps"] + if s["kind"] == "quota_spend" + ) + rc_sp, spent = _run_generated_cli( + spend_command, registry_path=registry, cwd=project + ) + assert rc_sp == 0, spent + assert spent["settlement_progress"]["state"] == "settled" + assert _spend_run_count(runtime) == 1 + + rc3, settled = _run_cli(registry, runtime, *guard_args) + assert rc3 == 0, settled + assert settled["effective_action"] == "heartbeat_settled_skip" + assert ( + settled["heartbeat_receipt"]["settlement_identity"] + == retry1["heartbeat_receipt"]["settlement_identity"] + ) + + +@pytest.mark.parametrize( + ("parent_builder", "overlay_builder", "removed_fields", "expected_source_key"), + [ + ( + _digest_review_details, + lambda ob_id: { + "semantic_replan_obligation_id": ob_id, + "semantic_replan_review_kind": "periodic_review_due", + "semantic_replan_review_stop_condition_sha256": "b" * 64, + }, + ("semantic_replan_review_stop_contract_id",), + "selected_review_source", + ), + ( + _digest_review_details, + _capability_guard_details, + ( + "semantic_replan_review_kind", + "semantic_replan_review_stop_condition", + "semantic_replan_review_stop_condition_sha256", + "semantic_replan_review_stop_contract_id", + ), + "selected_capability_guard", + ), + ( + _capability_guard_details, + _digest_review_details, + ( + "semantic_replan_capability_id", + "semantic_replan_gap_id", + "semantic_replan_frontier_revision", + ), + "selected_review_source", + ), + ], + ids=["default-digest-to-custom-digest", "review-to-capability", "capability-to-review"], +) +def test_upgrade_api_recovers_rotated_identity_upgrade_idempotently( + tmp_path: Path, + parent_builder: Callable[[str], dict[str, object]], + overlay_builder: Callable[[str], dict[str, object]], + removed_fields: tuple[str, ...], + expected_source_key: str, +) -> None: + rotated_obligation = "replan-2222222222222222" + overlay = overlay_builder(rotated_obligation) + _, _, expected_effect_id = _append_legacy_main_orphaned_identity_upgrade_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=TODO_ID, + turn_instance_id=TURN_ID, + companion_details=parent_builder("replan-1111111111111111"), + upgrade_overlay=overlay, + ) + + repaired, appended = upgrade_identityless_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=expected_effect_id, + status="normal_run", + summary="recover rotated identity_upgrade receipt", + details={ + "stall_observation": "not_applicable", + "todo_id": TODO_ID, + **overlay, + }, + ) + assert appended is True + assert repaired["details"]["settlement_effect_id"] == expected_effect_id + assert repaired["details"]["semantic_replan_obligation_id"] == rotated_obligation + for field in removed_fields: + assert field not in repaired["details"] + + log_path = rollout_event_log_path(tmp_path, GOAL_ID) + after_first = log_path.read_bytes() + replayed, appended_again = upgrade_identityless_heartbeat_receipt( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + turn_instance_id=TURN_ID, + todo_id=TODO_ID, + settlement_effect_id=expected_effect_id, + status="normal_run", + summary="replay after rotated repair", + details={ + "stall_observation": "not_applicable", + "todo_id": TODO_ID, + **overlay, + }, + ) + assert appended_again is False + assert replayed == repaired + assert log_path.read_bytes() == after_first + + readback = read_heartbeat_settlement( + tmp_path, + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=TODO_ID, + turn_instance_id=TURN_ID, + ) + assert readback is not None + assert readback.identity.failure is None + assert readback.semantic_replan_guard is not None + assert readback.semantic_replan_guard["selected_obligation_id"] == rotated_obligation + assert expected_source_key in readback.semantic_replan_guard + + +def test_cli_recovers_prior_turn_rotated_digest_to_inline_without_blocked_health( + tmp_path: Path, +) -> None: + from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID as actor, + GOAL_ID as goal, + TODO_ID as work, + _initialize_fixture_authority, + _run_cli, + _write_fixture, + ) + + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider="file") + prior_turn = "prior-turn-rotated-digest-inline" + rotated_obligation = "replan-2222222222222222" + rotated_stop = "Stop after validating rotated prior Turn." + _, _, expected_effect_id = _append_legacy_main_orphaned_identity_upgrade_receipt( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=prior_turn, + companion_details=_digest_review_details("replan-1111111111111111"), + upgrade_overlay={ + "semantic_replan_obligation_id": rotated_obligation, + "semantic_replan_review_kind": "periodic_review_due", + "semantic_replan_review_stop_condition": rotated_stop, + }, + ) + + rc, result = _run_cli( + registry, + runtime, + "quota", + "should-run", + "--codex-app", + "--goal-id", + goal, + "--agent-id", + actor, + "--turn-instance-id", + "fresh-followup-after-rotated", + ) + assert rc == 0, result + assert result["state"] != "blocked_health" + assert ( + result["unsettled_host_turn_recovery"]["prior_turn_instance_id"] + == prior_turn + ) + repaired_prior = find_heartbeat_receipt( + runtime, goal_id=goal, agent_id=actor, turn_instance_id=prior_turn + ) + assert repaired_prior is not None + assert repaired_prior["details"]["settlement_effect_id"] == expected_effect_id + assert repaired_prior["details"]["semantic_replan_obligation_id"] == rotated_obligation + assert repaired_prior["details"]["semantic_replan_review_stop_condition"] == rotated_stop + assert "semantic_replan_review_stop_condition_sha256" not in repaired_prior["details"] + + +@pytest.mark.parametrize( + ("case_id", "overlay_overrides", "bind_parent", "break_lineage"), + [ + ( + "broken-lineage", + { + "semantic_replan_obligation_id": "replan-2222222222222222", + "semantic_replan_review_kind": "goal_outcome_uncovered", + "semantic_replan_review_stop_condition": "Short clause without causal proof.", + }, + False, + True, + ), + ( + "unattributable-digest", + { + "semantic_replan_obligation_id": "replan-2222222222222222", + "semantic_replan_review_kind": "goal_outcome_uncovered", + "semantic_replan_review_stop_condition": "Short clause with foreign digest.", + "semantic_replan_review_stop_condition_sha256": "c" * 64, + }, + False, + False, + ), + ( + "invalid-post-repair-stop-length", + { + "semantic_replan_obligation_id": "replan-2222222222222222", + "semantic_replan_review_kind": "goal_outcome_uncovered", + "semantic_replan_review_stop_condition": "x" * 241, + }, + False, + False, + ), + ( + "already-bound-parent", + { + "semantic_replan_obligation_id": "replan-2222222222222222", + "semantic_replan_review_kind": "goal_outcome_uncovered", + "semantic_replan_review_stop_condition": "Short clause from bound parent.", + }, + True, + False, + ), + ], +) +def test_rotated_identity_upgrade_with_insufficient_proof_fails_closed( + tmp_path: Path, + case_id: str, + overlay_overrides: dict[str, object], + bind_parent: bool, + break_lineage: bool, +) -> None: + from loopx.control_plane.quota.heartbeat_receipt import ( + repair_orphaned_identity_upgrade_heartbeat_receipt, + ) + from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID as actor, + GOAL_ID as goal, + TODO_ID as work, + _initialize_fixture_authority, + _run_cli, + _write_fixture, + ) + + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider="file") + turn = f"rotated-fail-closed-{case_id}" + _, bad_upgrade, _ = _append_legacy_main_orphaned_identity_upgrade_receipt( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + companion_details=_digest_review_details("replan-1111111111111111"), + upgrade_overlay=overlay_overrides, + bind_parent=bind_parent, + break_lineage=break_lineage, + ) + log_path = rollout_event_log_path(runtime, goal) + before = log_path.read_bytes() + + effective, repaired = repair_orphaned_identity_upgrade_heartbeat_receipt( + runtime, + goal_id=goal, + agent_id=actor, + turn_instance_id=turn, + ) + assert repaired is False + assert effective == bad_upgrade + assert log_path.read_bytes() == before + + rc, failed = _run_cli( + registry, + runtime, + "quota", + "should-run", + "--codex-app", + "--goal-id", + goal, + "--agent-id", + actor, + "--todo-id", + work, + "--turn-instance-id", + turn, + ) + assert rc == 1 + assert failed["state"] == "blocked_health" + assert log_path.read_bytes() == before + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize( + ("astral_chars", "expect_recoverable"), + [(120, True), (121, False)], + ids=["utf16-240", "utf16-242"], +) +def test_cli_rotated_stop_condition_utf16_boundary_matches_ts_owner( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, + astral_chars: int, + expect_recoverable: bool, +) -> None: + from loopx.control_plane.quota.heartbeat_receipt import ( + repair_orphaned_identity_upgrade_heartbeat_receipt, + ) + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + from tests.control_plane.test_quota_settlement_cli import ( + AGENT_ID as actor, + GOAL_ID as goal, + TODO_ID as work, + _initialize_fixture_authority, + _run_cli, + _write_fixture, + ) + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider=provider) + turn = f"rotated-utf16-{provider}-{astral_chars * 2}" + rotated_obligation = "replan-2222222222222222" + stop_clause = "\U00020000" * astral_chars + assert len(stop_clause) == astral_chars + assert len(stop_clause.encode("utf-16-le")) // 2 == astral_chars * 2 + + _, bad_upgrade, expected_effect_id = ( + _append_legacy_main_orphaned_identity_upgrade_receipt( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + companion_details=_digest_review_details("replan-1111111111111111"), + upgrade_overlay={ + "semantic_replan_obligation_id": rotated_obligation, + "semantic_replan_review_kind": "goal_outcome_uncovered", + "semantic_replan_review_stop_condition": stop_clause, + }, + ) + ) + log_path = rollout_event_log_path(runtime, goal) + before = log_path.read_bytes() + assert len(load_rollout_events(log_path)) == 2 + + guard_args = ( + "quota", + "should-run", + "--codex-app", + "--goal-id", + goal, + "--agent-id", + actor, + "--todo-id", + work, + "--turn-instance-id", + turn, + ) + + if expect_recoverable: + rc1, retry1 = _run_cli(registry, runtime, *guard_args) + assert rc1 == 0, retry1 + assert retry1["state"] == "eligible" + assert retry1["heartbeat_receipt"]["status"] == "upgraded" + assert ( + retry1["heartbeat_receipt"]["settlement_identity"]["effect_id"] + == expected_effect_id + ) + assert len(load_rollout_events(log_path)) == 3 + readback = read_heartbeat_settlement( + runtime, + goal_id=goal, + agent_id=actor, + todo_id=work, + turn_instance_id=turn, + registry_path=registry, + ) + assert readback is not None + assert readback.identity.failure is None + assert readback.admission_event_id == bad_upgrade["event_id"] + assert readback.semantic_replan_guard == { + "schema_version": "semantic_replan_guard_v0", + "scope": "turn_guard", + "selected_obligation_id": rotated_obligation, + "selected_review_source": { + "kind": "goal_outcome_uncovered", + "stop_condition": stop_clause, + }, + } + bytes_after_r1 = log_path.read_bytes() + rc2, retry2 = _run_cli(registry, runtime, *guard_args) + assert rc2 == 0, retry2 + assert retry2["heartbeat_receipt"]["status"] == "replayed" + assert log_path.read_bytes() == bytes_after_r1 + else: + effective, repaired = repair_orphaned_identity_upgrade_heartbeat_receipt( + runtime, + goal_id=goal, + agent_id=actor, + turn_instance_id=turn, + ) + assert repaired is False + assert effective == bad_upgrade + assert log_path.read_bytes() == before + + for _ in range(2): + rc_fail, failed_cli = _run_cli(registry, runtime, *guard_args) + assert rc_fail == 1 + assert failed_cli["state"] == "blocked_health" + assert log_path.read_bytes() == before + assert len(load_rollout_events(log_path)) == 2 diff --git a/tests/control_plane_ts/effect_runtime_handlers.test.ts b/tests/control_plane_ts/effect_runtime_handlers.test.ts index 0b19e40237..c72b6e08d9 100644 --- a/tests/control_plane_ts/effect_runtime_handlers.test.ts +++ b/tests/control_plane_ts/effect_runtime_handlers.test.ts @@ -273,3 +273,32 @@ test("explicit Host retry is registered and requires a valid typed failure and i await assert.rejects(dispatchEffectRuntimeMethod(handlers, "host_failure.retry", params)); } }); + +test("runtime validates semantic replan guard stop clauses using UTF-16 code units", async () => { + const validBoundary = await dispatchEffectRuntimeMethod( + handlers, + "quota.semantic_replan_guard.validate", + { + details: { + semantic_replan_obligation_id: "replan-2222222222222222", + semantic_replan_review_kind: "goal_outcome_uncovered", + semantic_replan_review_stop_condition: "\u{20000}".repeat(120), + }, + }, + ) as Record; + assert.equal(validBoundary.valid, true); + + const rejectedBoundary = await dispatchEffectRuntimeMethod( + handlers, + "quota.semantic_replan_guard.validate", + { + details: { + semantic_replan_obligation_id: "replan-2222222222222222", + semantic_replan_review_kind: "goal_outcome_uncovered", + semantic_replan_review_stop_condition: "\u{20000}".repeat(121), + }, + }, + ) as Record; + assert.equal(rejectedBoundary.valid, false); + assert.equal(rejectedBoundary.diagnostic_code, "malformed_settlement_state"); +});