Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions loopx/cli_commands/project_lifecycle_refresh_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,11 @@ def handle_refresh_state_command(
replan_obligation_id=getattr(
args, "replan_obligation_id", None
),
# The write may be addressed through the retained Todo while
# quota should-run bound this Turn to its semantic replan.
# Read back the immutable guard identity instead of treating
# that supported command shape as a second binding.
resolve_original_binding=True,
registry_path=registry_path,
goal_ref=goal_ref,
)
Expand Down
12 changes: 10 additions & 2 deletions loopx/control_plane/quota/heartbeat_receipt.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from __future__ import annotations
from .effective_action import EffectiveAction

from collections.abc import Callable, Mapping
from pathlib import Path
Expand All @@ -12,6 +11,7 @@
rollout_event_log_path,
)
from ..todos.contract import normalize_todo_id, normalize_todo_replan_obligation_id
from .effective_action import EffectiveAction
from .effect_program import SettlementBindingKind, SettlementIdentity
from .error_codes import HeartbeatReceiptIdentityConflictError
from .settlement_workspace_causality import (
Expand Down Expand Up @@ -604,10 +604,18 @@ def requalify_bound_heartbeat_receipt(
if not isinstance(qualified_details, Mapping):
raise RuntimeError("TypeScript heartbeat work qualification details missing")
event_id = str(original.get("event_id") or "")
receipt_revision = str(
qualified_details.get("settlement_receipt_revision") or ""
)
summary = (
"same-Turn review guard upgraded without rebinding"
if receipt_revision == "review_guard_upgrade"
else "same-Turn work admission requalified without rebinding"
)
corrected = build_rollout_event(
goal_id=goal_id, goal_ref=goal_ref, event_kind="quota_should_run",
agent_id=agent_id, todo_id=todo_id, run_id=turn_instance_id, status=status,
summary="same-Turn work admission requalified without rebinding",
summary=summary,
source_event_id=event_id, caused_by=event_id, details=dict(qualified_details),
)
_append_rollout_event_line(log_path, corrected)
Expand Down
18 changes: 12 additions & 6 deletions loopx/control_plane/quota/prior_turn_closeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export interface PriorHostTurnCloseoutCandidate extends JsonObject {
/** The Todo id or autonomous replan obligation id, per `binding_kind`. */
binding_id: string;
settlement_effect_id: string | null;
/** The effective guard admitted an autonomous replan under this binding. */
admitted_replan?: true;
/** The effective guard admitted a replan under this Todo's settlement identity. */
admitted_todo_replan?: true;
}
Expand All @@ -43,6 +45,7 @@ function candidate(
binding: HeartbeatReceiptBinding,
turnInstanceId: string,
fact: HeartbeatReceiptFact,
admittedReplan: boolean,
admittedTodoReplan: boolean,
): PriorHostTurnCloseoutCandidate {
return {
Expand All @@ -51,15 +54,16 @@ function candidate(
binding_kind: binding.binding_kind,
binding_id: binding.binding_id,
settlement_effect_id: binding.settlement_effect_id,
...(admittedReplan ? {admitted_replan: true as const} : {}),
...(admittedTodoReplan ? {admitted_todo_replan: true as const} : {}),
};
}

/**
* Select prior Turns eligible for closeout readback. A Todo-bound replan
* carries the Todo settlement identity and a separate semantic obligation.
* It did not deliver a Todo, so its closeout marker can be false. Fresh
* admission requires a verified outstanding writeback for this binding.
* Select prior Turns eligible for closeout readback. An admitted replan may
* carry either its legacy Todo settlement identity or its autonomous-replan
* identity. It did not deliver a Todo, so its closeout marker can be false.
* Fresh admission requires a verified outstanding writeback for this binding.
* Explicit pending-closeout discovery can also find admitted replans before
* writeback, whether their settlement identity is a Todo or an obligation.
*
Expand Down Expand Up @@ -120,9 +124,11 @@ export function selectCloseoutCandidates(
if (binding === null) continue;
const admittedReplan = admitsAutonomousReplan(effective, fact);
const admittedTodoReplan = admittedReplan && binding.binding_kind === "todo";
if (!fact.closeout_required && !admittedTodoReplan &&
if (!fact.closeout_required && !admittedReplan &&
!(includeUnwrittenReplans && admittedReplan)) continue;
candidates.push({candidate: candidate(binding, turnInstanceId, fact, admittedTodoReplan),
candidates.push({candidate: candidate(
binding, turnInstanceId, fact, admittedReplan, admittedTodoReplan,
),
requireWritebackForRecovery: !fact.closeout_required && !includeUnwrittenReplans});
}
return {candidates, turnsValidated: validated};
Expand Down
174 changes: 126 additions & 48 deletions loopx/control_plane/quota/settlement_cli.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""CLI rollout helpers for heartbeat settlement identity and receipt wiring."""

from __future__ import annotations
from .effective_action import EffectiveAction

import argparse
import hashlib
from collections.abc import Mapping
from pathlib import Path

Expand All @@ -12,14 +12,18 @@
normalize_todo_replan_obligation_id,
)
from ..work_items.autonomous_replan_obligation import (
AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION,
AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID,
AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION,
replan_obligation_id_from_packet,
)
from .effect_program import SettlementIdentity
from .effective_action import EffectiveAction
from .error_codes import HeartbeatReceiptIdentityConflictError
from .heartbeat_receipt import (
heartbeat_receipt_view,
upgrade_identityless_heartbeat_receipt,
requalify_bound_heartbeat_receipt,
upgrade_identityless_heartbeat_receipt,
)
from .settlement import (
QuotaSettlementReadback,
Expand Down Expand Up @@ -47,30 +51,46 @@ def reconcile_existing_heartbeat_receipt(
receipt = existing
receipt_status = "replayed"
receipt_appended = False
rollout_todo_id = quota_rollout_todo_id(payload, args)
rollout_replan_obligation_id = quota_rollout_replan_obligation_id(payload, args)
if rollout_todo_id or rollout_replan_obligation_id:
existing_details_value = receipt.get("details")
existing_details = (
existing_details_value
if isinstance(existing_details_value, Mapping)
else {}
)
existing_todo_id = normalize_todo_id(existing_details.get("todo_id"))
existing_replan_obligation_id = normalize_todo_replan_obligation_id(
existing_details.get("replan_obligation_id")
existing_details_value = receipt.get("details")
existing_details = (
existing_details_value
if isinstance(existing_details_value, Mapping)
else {}
)
existing_todo_id = normalize_todo_id(existing_details.get("todo_id"))
existing_replan_obligation_id = normalize_todo_replan_obligation_id(
existing_details.get("replan_obligation_id")
)
existing_effect_id = str(
existing_details.get("settlement_effect_id") or ""
).strip()
receipt_has_bound_identity = bool(
(existing_todo_id or existing_replan_obligation_id)
and existing_effect_id
)
if receipt_has_bound_identity:
# A committed heartbeat receipt is the authority for this Turn's
# settlement identity. The current projection can rotate from Todo
# delivery into autonomous replan (or the reverse) while the host is
# interrupted, but that later projection must not rebind the original
# effect. Explicit retry arguments are checked below against the
# receipt and its retained planning selection.
rollout_todo_id = existing_todo_id
rollout_replan_obligation_id = existing_replan_obligation_id
else:
rollout_todo_id = quota_rollout_todo_id(payload, args)
rollout_replan_obligation_id = quota_rollout_replan_obligation_id(
payload, args
)
existing_effect_id = str(
existing_details.get("settlement_effect_id") or ""
).strip()
if rollout_todo_id or rollout_replan_obligation_id:
expected_effect_id = SettlementIdentity(
goal_id=args.goal_id,
agent_id=args.agent_id,
todo_id=rollout_todo_id or None,
turn_instance_id=turn_instance_id,
replan_obligation_id=rollout_replan_obligation_id,
).effect_id
if (existing_todo_id or existing_replan_obligation_id) and existing_effect_id:
if receipt_has_bound_identity:
# A fully settled Turn owns its immutable receipt regardless of a
# later explicit CLI choice. The live decision has already read
# the exact settlement and projected ``heartbeat_settled_skip``;
Expand All @@ -82,14 +102,30 @@ def reconcile_existing_heartbeat_receipt(
)
if not settled_replay:
requested_todo_id = normalize_todo_id(args.todo_id)
if requested_todo_id and requested_todo_id != existing_todo_id:
raise HeartbeatReceiptIdentityConflictError(
"heartbeat receipt settlement identity conflicts with the "
"current selected Todo: explicitly requested Todo differs"
)
requested_replan_obligation_id = normalize_todo_replan_obligation_id(
getattr(args, "replan_obligation_id", None)
)
if requested_todo_id and requested_replan_obligation_id:
raise ValueError(
"quota rollout cannot bind both todo_id and "
"replan_obligation_id"
)
if requested_todo_id:
if existing_todo_id and requested_todo_id != existing_todo_id:
raise HeartbeatReceiptIdentityConflictError(
"heartbeat receipt settlement identity conflicts with the "
"current selected Todo: explicitly requested Todo differs"
)
if existing_replan_obligation_id:
retained_todo_id = normalize_todo_id(
existing_details.get("pending_action_selection_todo_id")
)
if requested_todo_id != retained_todo_id:
raise HeartbeatReceiptIdentityConflictError(
"heartbeat receipt settlement identity conflicts with "
"the retained Todo selection: explicitly requested "
"Todo differs"
)
if (
requested_replan_obligation_id
and requested_replan_obligation_id
Expand All @@ -99,32 +135,47 @@ def reconcile_existing_heartbeat_receipt(
"heartbeat receipt settlement identity conflicts with the "
"explicitly requested autonomous replan obligation"
)
if (
existing_todo_id != rollout_todo_id
or existing_replan_obligation_id != rollout_replan_obligation_id
or existing_effect_id != expected_effect_id
):
if existing_effect_id != expected_effect_id:
raise HeartbeatReceiptIdentityConflictError(
"heartbeat receipt settlement identity conflicts with the "
"current settlement binding: receipt="
f"{existing_todo_id or existing_replan_obligation_id}, "
"current="
f"{rollout_todo_id or rollout_replan_obligation_id}"
"heartbeat receipt effect identity does not match its "
"persisted settlement binding"
)
rollout_details = quota_rollout_details(payload, args,
todo_id=rollout_todo_id, replan_obligation_id=rollout_replan_obligation_id)
rollout_details["settlement_effect_id"] = expected_effect_id
receipt, qualified = requalify_bound_heartbeat_receipt(
runtime_root, goal_id=args.goal_id, agent_id=args.agent_id,
turn_instance_id=turn_instance_id, todo_id=rollout_todo_id,
replan_obligation_id=rollout_replan_obligation_id,
status=str(payload.get("effective_action") or payload.get("decision") or "should-run"),
details=rollout_details,
registry_path=Path(str(payload["registry"])) if payload.get("registry") else None,
goal_ref=goal_ref,
replan_packet = (
payload.get("replan_action_packet")
if isinstance(payload.get("replan_action_packet"), Mapping)
else {}
)
current_replan_obligation_id = replan_obligation_id_from_packet(
replan_packet
)
if qualified:
receipt_status, receipt_appended = "upgraded", True
# A later frontier can rotate to a new replan identity after
# this Turn's historical ACK was accepted. That projection
# cannot requalify or replace the original receipt. Only the
# same open replan may append compatible review-source facts;
# a settlement-only packet already carries the exact evidence
# needed to close this immutable receipt.
if (
replan_packet.get("settlement_only") is not True
and (
not existing_replan_obligation_id
or current_replan_obligation_id
== existing_replan_obligation_id
)
):
receipt, qualified = requalify_bound_heartbeat_receipt(
runtime_root, goal_id=args.goal_id, agent_id=args.agent_id,
turn_instance_id=turn_instance_id, todo_id=rollout_todo_id,
replan_obligation_id=rollout_replan_obligation_id,
status=str(payload.get("effective_action") or payload.get("decision") or "should-run"),
details=rollout_details,
registry_path=Path(str(payload["registry"])) if payload.get("registry") else None,
goal_ref=goal_ref,
)
if qualified:
receipt_status, receipt_appended = "upgraded", True
else:
rollout_details = quota_rollout_details(
payload,
Expand Down Expand Up @@ -411,24 +462,51 @@ def quota_rollout_details(
replan_packet = payload.get("replan_action_packet")
obligation = payload.get("autonomous_replan_obligation")
if semantic_replan_obligation_id and isinstance(obligation, Mapping) and obligation.get("obligation_id") == semantic_replan_obligation_id:
from ..work_items.replan_semantics_codec import project_replan_semantics
from ...rollout_event_log import _safe_details
from ..work_items.replan_semantics_codec import project_replan_semantics

source = project_replan_semantics({"operation": "receipt_review_source",
"agent_id": getattr(args, "agent_id", None),
"obligation": {key: value for key, value in obligation.items() if key != "replan_context"}})
review = source["review_source"]
if isinstance(review, Mapping):
# Retain the original stop clause only when the existing public
# metadata serializer preserves it exactly. Unsafe/lossy sources
# keep legacy strict recovery; never truncate a governing clause.
# Retain a short public stop clause verbatim. A longer clause can
# still preserve its semantic identity through a digest, but only
# when the public metadata serializer accepts the entire source
# without private markers or whitespace normalization. Unsafe or
# otherwise lossy sources keep legacy strict recovery.
try:
safe = _safe_details({"semantic_replan_review_kind": review["kind"],
"semantic_replan_review_stop_condition": review["stop_condition"]})
except ValueError:
safe = {}
if safe.get("semantic_replan_review_stop_condition") == review["stop_condition"]:
stop_condition = review.get("stop_condition")
if safe.get("semantic_replan_review_stop_condition") == stop_condition:
details.update(safe)
elif (
safe.get("semantic_replan_review_kind") == review.get("kind")
and isinstance(stop_condition, str)
and len(stop_condition) > 240
and " ".join(stop_condition.split()) == stop_condition
):
stop_details = {
"semantic_replan_review_kind": safe["semantic_replan_review_kind"],
# Older readers require the scalar stop field. Keep them
# fail-closed on this path while a current reader verifies
# the full clause through its digest (and known contract,
# when available).
"semantic_replan_review_stop_condition": (
AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION
),
"semantic_replan_review_stop_condition_sha256": hashlib.sha256(
stop_condition.encode("utf-8")
).hexdigest(),
}
if stop_condition == AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION:
stop_details["semantic_replan_review_stop_contract_id"] = (
AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID
)
details.update(stop_details)
receipt = payload.get("heartbeat_receipt")
capability_guard = (replan_packet.get("capability_guard") if isinstance(replan_packet, Mapping) else None) or (
receipt.get("semantic_replan_capability_guard") if isinstance(receipt, Mapping) else None
Expand Down
Loading
Loading