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
1 change: 1 addition & 0 deletions loopx/control_plane/quota/live_decision.py
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,7 @@ def build_live_quota_should_run_decision(
)
if (
receipt_bound_guard_fields["receipt_bound_replan_guard_scoped"]
and receipt_bound_replay_phase is ReceiptBoundReplayPhase.OPEN
and receipt_bound_replan_obligation_id
and agent_id
):
Expand Down
15 changes: 12 additions & 3 deletions loopx/control_plane/quota/should_run_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,11 @@ def _prepare_quota_replan_context(
replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None,
) -> tuple[dict[str, Any], dict[str, Any] | None]:
"""Project the current frontier and contextualize its receipt-bound review."""
# Once the settlement owner verifies writeback, an old review's sources
# cannot be prerequisites for spending its receipt (or replaying it).
reconstruct_review = receipt_bound_replay_phase not in (
ReceiptBoundReplayPhase.SETTLEMENT_PENDING, ReceiptBoundReplayPhase.SETTLED,
)
goal_frontier_context = build_goal_frontier_projection_context_from_status(
replan_explore_reader=replan_explore_reader,
goal_id=safe_goal_id,
Expand All @@ -277,19 +282,23 @@ def _prepare_quota_replan_context(
registered_agent_ids=registered_agent_ids,
goal_status=str(registry_goal.get("status") or ""),
agent_profile=_quota_agent_profile(agent_identity),
receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id,
receipt_bound_replan_obligation_id=(
receipt_bound_replan_obligation_id if reconstruct_review else None
),
receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at,
)
replan_obligation = (
None
if receipt_bound_replay_phase is ReceiptBoundReplayPhase.SETTLED
else _preserve_receipt_bound_replan_obligation(
goal_frontier_context.get("replan_obligation"),
goal_frontier_context.get("replan_obligation") if reconstruct_review else None,
receipt_bound_replan_obligation_id,
guard_scoped=receipt_bound_replan_guard_scoped,
agent_id=agent_frontier_id,
replay_phase=receipt_bound_replay_phase,
transition_candidates=goal_frontier_context.get("replan_transition_candidates"),
transition_candidates=(
goal_frontier_context.get("replan_transition_candidates") if reconstruct_review else None
),
stride_strategy=goal_frontier_context["stride_strategy"],
receipt_review=receipt_bound_replan_review,
goal_id=safe_goal_id,
Expand Down
5 changes: 3 additions & 2 deletions loopx/control_plane/work_items/replan_semantics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,12 +276,14 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject {
![null, "open", "settlement_pending"].includes(request.replay_phase as string | null)) {
throw new EffectRuntimeRequestError("receipt-bound replan facts are malformed");
}
const writebackCommitted = request.replay_phase === "settlement_pending";
let original: JsonObject | null = null;
let openVisionReview: JsonObject | null = null;
let recoveredLifecycle: JsonObject | null = null;
let delta: JsonObject | null = null;
let historicalAckRecorded = false;
for (const value of request.transition_candidates) {
const candidates = writebackCommitted ? [] : request.transition_candidates;
for (const value of candidates) {
const candidate = object(value);
const obligation = object(candidate.obligation);
if (request.guard_scoped && object(candidate.source_obligation).resolution_mode === "todo_lifecycle_settlement") {
Expand Down Expand Up @@ -319,7 +321,6 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject {
break;
}
}
const writebackCommitted = request.replay_phase === "settlement_pending";
if (delta !== null || writebackCommitted) {
const reason = writebackCommitted
? "The original Turn writeback is verified. Settle its existing quota receipt once; do not repeat work or select its successor."
Expand Down
60 changes: 55 additions & 5 deletions tests/control_plane/test_declared_terminal_settlement_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,13 @@ def test_original_lease_and_failed_validator_remain_required_before_accounting(
@pytest.mark.parametrize("closeout_source", ["turn", "lifecycle"])
def test_no_followup_transition_recovers_bound_review_through_writeback_and_single_debit(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, historical_terminals: int,
closeout_source: str,
closeout_source: str, capsys: pytest.CaptureFixture[str],
) -> None:
project, _, runtime, _, run, lease, marker, _, _ = _fixture(
from loopx.control_plane.effect_runtime import EffectRuntimeRejected
from loopx.control_plane.work_items import lifecycle_recovery
from loopx.entrypoint import main as cli_main

_, workspace, runtime, registry, run, lease, marker, _, _ = _fixture(
tmp_path, monkeypatch, provider, historical_terminals=historical_terminals,
)
def call(*args: str, expected: int = 0):
Expand All @@ -303,6 +307,25 @@ def call(*args: str, expected: int = 0):
turn = "turn-original-lifecycle-review"
guard = ("quota", "should-run", "--runtime-profile", "generic_cli", "--goal-id", cli.GOAL_ID,
"--agent-id", cli.AGENT_ID, "--turn-instance-id", turn, *capabilities)
exercise_source_failure = historical_terminals == 0 and closeout_source == "lifecycle"

def reenter_with_unavailable_source(expected: int = 0):
project_semantics = lifecycle_recovery.project_replan_semantics

def read_semantics(params):
if params.get("operation") == "lifecycle_source":
raise EffectRuntimeRejected("Original lifecycle review source is unavailable")
return project_semantics(params)

with monkeypatch.context() as patch:
patch.chdir(workspace)
patch.setattr(lifecycle_recovery, "project_replan_semantics", read_semantics)
code = cli_main(["--format", "json", "--registry", str(registry), "--runtime-root", str(runtime),
*guard, "--context-delivery", "off"])
payload = json.loads(capsys.readouterr().out)
assert code == expected, payload
return payload

admitted = call(*guard)
identity = admitted["heartbeat_receipt"]["settlement_identity"]
assert admitted["autonomous_replan_obligation"]["triggers"][0]["todo_id"] == cli.TODO_ID
Expand All @@ -319,6 +342,10 @@ def call(*args: str, expected: int = 0):
assert recovered.get("selected_todo") is None
assert recovered["replan_action_packet"]["settlement_only"] is True
assert recovered["replan_action_packet"]["writeback_contract"]["preferred_input"] == "evidence_linked_vision_path"
if exercise_source_failure:
rejected = reenter_with_unavailable_source(expected=1)
assert "Original lifecycle review source is unavailable" in str(rejected)
assert "settlement_owed" not in rejected
replan_binding = ("--agent-id", cli.AGENT_ID, "--replan-obligation-id", identity["replan_obligation_id"],
"--turn-instance-id", turn)
spend = ("quota", "spend-slot", "--goal-id", cli.GOAL_ID, *replan_binding,
Expand All @@ -343,10 +370,33 @@ def call(*args: str, expected: int = 0):
assert refreshed["settlement_progress"]["state"] == "spend_required"
pending = call(*guard)
assert pending["heartbeat_receipt"]["settlement_identity"] == identity
assert pending["settlement_progress"]["state"] == "spend_required"
assert call(*spend)["appended"] is True
assert call(*spend)["appended"] is False
assert pending["settlement_progress"] == refreshed["settlement_progress"]
assert pending["replan_action_packet"]["required_outcome"] == "quota_spend_receipt"
assert pending["normal_delivery_allowed"] is False
assert pending.get("selected_todo") is None
if exercise_source_failure:
recovered_debit = reenter_with_unavailable_source()
assert recovered_debit["heartbeat_receipt"]["settlement_identity"] == identity
assert recovered_debit["settlement_owed"] == pending["settlement_owed"]
assert recovered_debit.get("selected_todo") is None
pending = recovered_debit
owed = pending["settlement_owed"]
assert owed["effect_id"] == identity["effect_id"]
assert owed["kind"] == "quota_spend"
assert cli._spend_run_count(runtime) == 1
projected_spend = cli._projected_cli_args(owed["command"], turn_instance_id=turn)
if exercise_source_failure:
foreign_spend = tuple("turn-without-original-writeback" if token == turn else token
for token in projected_spend)
assert call(*foreign_spend, expected=1).get("appended") is not True
assert cli._spend_run_count(runtime) == 1
assert call(*projected_spend)["appended"] is True
assert call(*projected_spend)["appended"] is False
assert call(*guard)["effective_action"] == "heartbeat_settled_skip"
if exercise_source_failure:
replayed = reenter_with_unavailable_source()
assert replayed["effective_action"] == "heartbeat_settled_skip"
assert "settlement_owed" not in replayed
after = call("todo", "list", "--goal-id", cli.GOAL_ID, "--todo-id", cli.TODO_ID)["todo"]
for field in ("completed_at", "completion_turn_key", "completion_validation_sha256"):
assert before[field] == after[field]
Expand Down
16 changes: 16 additions & 0 deletions tests/control_plane_ts/replan_semantics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,13 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", (
assert.deepEqual(packet.semantic_delta, delta);
assert.equal((packet.writeback_contract as JsonObject).preferred_input, "exact_historical_ack");

const pending = projectReplanSemantics({operation: "receipt_bound_obligation", ...request,
current_obligation: null, replay_phase: "settlement_pending"}).obligation as JsonObject;
const remaining = pending.settlement_action_packet as JsonObject;
assert.equal(remaining.required_outcome, "quota_spend_receipt");
assert.equal(remaining.semantic_delta, null);
assert.equal(remaining.successor_todo_id, null);

for (const missingGuard of [{guard_scoped: false}, {goal_id: null}, {agent_id: null},
{guard_recorded_at: null}, {guard_turn_instance_id: null}]) {
const unbound = {...request, ...missingGuard};
Expand Down Expand Up @@ -794,6 +801,15 @@ test(`${recovery} restores only its exact admitted review and still owes Vision`
assert.equal(Object.hasOwn(writeback.vision_authoring as JsonObject, "continuation_review"), false);
assert.equal(projectReplanSemantics({operation: "qualify", obligation: result}).accepted, false);
assert.equal(projectReplanSemantics({operation: "qualify", obligation: result, agent_vision: vision}).accepted, true);
// The same lifecycle evidence still exists after writeback. Reentry follows
// the verified settlement phase while leaving the next frontier unselected.
const pending = projectReplanSemantics({...request, replay_phase: "settlement_pending",
current_obligation: {obligation_id: "replan-2222222222222222"}}).obligation as JsonObject;
assert.equal(pending.obligation_id, id);
assert.deepEqual(pending.todo_actions, []);
const remaining = pending.settlement_action_packet as JsonObject;
assert.equal(remaining.decision, "settlement_pending");
assert.equal(remaining.required_outcome, "quota_spend_receipt");
const historical = {...row, todo_id: "todo_historical", completion_turn_key: "historical-completion",
completed_at: "2026-07-31T23:59:00Z", updated_at: "2026-07-31T23:59:01Z"};
for (const items of [[historical, row], [row, historical]]) {
Expand Down
Loading