Skip to content
33 changes: 33 additions & 0 deletions docs/quota-allocation.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,39 @@ caller appends the refresh receipt and rereads the chain; it must not offer a
spend command before that point. Older guards without a persisted spend source
retain the existing heartbeat default.

A rejected `refresh-state`, or an Agent's state-only maintenance update, also
returns `settlement_recovery` when a persisted Turn still owes closeout. Its
identity and progress come from the same typed receipt reader as guard recovery.
If the caller omits the Turn ID, the refresh can discover an autonomous replan
whose guard positively admitted work and recorded the original obligation and
effect. Later Turn admission still follows the guard's explicit closeout marker.
The TS `pending_closeout` read selects the candidate, validates the original
binding and evaluates receipts under one admitted owner and immutable snapshot;
Python only adapts CLI input and renders the returned recovery. This read mode
cannot be combined with settlement admission or latest-Run inference.
`ok: true` on a state update describes that update only; it does not settle the
nested original Turn. Follow `settlement_recovery.next_cli_actions`: before a
verified writeback this reenters the original bound guard; afterwards it offers
only the remaining spend. A stale replan basis still requires reading the
returned `replan_transition.context_recovery` and correcting the evidence-linked
packet before retry. No recovery read creates a Turn or debits quota. Missing
or conflicting receipt authority is reported as `settlement_recovery_error`,
never inferred as successful settlement. Setup with no admitted Turn, other
Agents' Turns, and already settled work do not produce pending recovery.

`refresh-state` 被拒绝,或 Agent 只更新升级/维护状态时,若已有 Turn 尚欠结算,
响应会返回 `settlement_recovery`,身份与进度沿用 guard 恢复的 typed receipt reader。
即使调用者漏传 Turn ID,只要原 guard 已明确准入自主重规划并记录义务和 effect,
刷新也能找回原轮次。后续 Turn 的准入仍依据 guard 明确记录的 closeout 标记。
TS `pending_closeout` 在同一准入 owner、同一不可变快照下完成候选选择、原绑定校验
及收据判断;Python 只适配 CLI 参数和展示,不再分两次读取决定恢复对象。这个只读
模式不能与结算准入或最新 Run 推断混用。
状态更新的 `ok: true` 只表示该更新成功,不代表嵌套的原 Turn 已结清。执行其中的
`next_cli_actions`:写回验证前回到原绑定 guard,验证后只补剩余扣账。重规划依据
过期仍须读取 `replan_transition.context_recovery`,修正证据关联的 packet 后再试。
恢复读取不新建 Turn、不扣额;收据不可读或身份冲突会显示 `settlement_recovery_error`,
不能视为已结算。没有已准入 Turn 的设置工作、其它 Agent 和已结清工作不产生待恢复项。

## Minimal Contract

The compact status shape can start with a small object:
Expand Down
8 changes: 8 additions & 0 deletions loopx/cli_commands/project_lifecycle_refresh_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
)
from ..control_plane.quota.cli_projection import compact_refresh_state_cli_payload
from .refresh_settlement import settle_requested_refresh
from .refresh_recovery import attach_refresh_settlement_recovery


def register_refresh_state_command(
Expand Down Expand Up @@ -668,6 +669,7 @@ def handle_refresh_state_command(
"error": str(exc),
**({"error_code": exc.code, **getattr(exc, "payload", {})} if isinstance(getattr(exc, "code", None), str) else {}),
}
attach_refresh_settlement_recovery(payload, args, registry_path, goal_ref)
if isinstance(exc, ReplanWritebackRejected):
transition = project_replan_writeback_rejection(
exc,
Expand All @@ -686,6 +688,10 @@ def handle_refresh_state_command(
"current_context_id": recovery["replan_context"]["context_id"],
"instruction": recovery["instruction"], **reference,
}
settlement_recovery = payload.get("settlement_recovery")
if isinstance(settlement_recovery, dict) and transition["host_action"] == "write_typed_semantic_delta":
transition["host_action"] = "read_current_replan_context"
transition["next_cli_actions"] = settlement_recovery["next_cli_actions"]
payload["replan_transition"] = transition
if transition["next_cli_actions"]:
payload["error"] += " Required transition: " + "; ".join(
Expand Down Expand Up @@ -884,6 +890,7 @@ def handle_refresh_state_command(
)
if not material_refresh_ready:
settle_requested_refresh(payload, args, registry_path, goal_ref)
attach_refresh_settlement_recovery(payload, args, registry_path, goal_ref)
print_payload(compact_refresh_state_cli_payload(payload) if fmt == "json" else payload, fmt, render_state_refresh_markdown)
return 0 if payload.get("ok") else 1
if payload.get("explore_result") is not None:
Expand Down Expand Up @@ -974,5 +981,6 @@ def handle_refresh_state_command(
),
)
settle_requested_refresh(payload, args, registry_path, goal_ref)
attach_refresh_settlement_recovery(payload, args, registry_path, goal_ref)
print_payload(compact_refresh_state_cli_payload(payload) if fmt == "json" else payload, fmt, render_state_refresh_markdown)
return 0 if payload.get("ok") else 1
71 changes: 71 additions & 0 deletions loopx/cli_commands/refresh_recovery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Keep a rejected write or maintenance refresh attached to its owed Turn.

The shared TS closeout reader selects persisted debt; this adapter only exposes
its exact readback and CLI continuation. It never admits or settles a Turn.
"""
from __future__ import annotations

import argparse
from collections.abc import Mapping
from pathlib import Path
from typing import Any

from ..control_plane.quota.settlement import attach_settlement_progress, read_heartbeat_settlement
from ..command_invocation import loopx_cli_argv
from ..install_contract import render_host_cli_command
from ..history import load_registry
from ..paths import resolve_runtime_root


def attach_refresh_settlement_recovery(
payload: dict[str, Any], args: argparse.Namespace, registry_path: Path,
goal_ref: Mapping[str, Any] | None,
) -> None:
"""Expose existing debt without turning a state update into a write receipt."""
if (args.dry_run or not args.agent_id or isinstance(payload.get("settlement_progress"), dict)
or "settlement_recovery" in payload or "settlement_recovery_error" in payload):
return
try:
runtime_root = resolve_runtime_root(load_registry(registry_path), args.runtime_root,
registry_path=registry_path)
# TS selects persisted debt and validates every caller-supplied binding
# against one immutable snapshot; Python supplies no latest-Run guess.
readback = read_heartbeat_settlement(runtime_root, goal_id=args.goal_id,
agent_id=args.agent_id, todo_id=args.todo_id,
replan_obligation_id=args.replan_obligation_id, turn_instance_id=args.turn_instance_id,
pending_closeout=True, include_record_bodies=False,
registry_path=registry_path, goal_ref=goal_ref)
if readback is None:
return
if readback.identity.failure is not None:
raise ValueError(readback.identity.failure.reason)
identity = readback.identity.value
if identity is None:
raise RuntimeError("original Turn settlement identity is unavailable")
recovery: dict[str, Any] = {"ok": True}
attach_settlement_progress(recovery, readback, registry_path=registry_path,
runtime_root=runtime_root, goal_ref=goal_ref)
recovery.pop("ok")
owed = recovery.get("settlement_owed")
# Select the complete CLI consumer explicitly: an unprofiled guard can
# return legacy unbound refresh templates. Replan guards recover their
# obligation from the Turn receipt (that flag is spend-only on quota).
command = render_host_cli_command([
*loopx_cli_argv(), "--registry", str(registry_path), "--runtime-root", str(runtime_root),
"--format", "json", "quota", "should-run",
"--complete-turn", "--runtime-profile", "generic_cli",
"--goal-id", identity.goal_id, "--agent-id", identity.agent_id,
"--turn-instance-id", identity.turn_instance_id,
*(["--todo-id", identity.todo_id] if identity.todo_id else []),
*(["--goal-instance-id", str(goal_ref["goal_instance_id"])] if goal_ref is not None else []),
*[word for capability in args.available_capabilities or [] for word in ("--available-capability", capability)],
])
recovery.update(required=True, settlement_identity=identity.as_dict(),
next_cli_actions=[owed["command"] if isinstance(owed, dict) else command],
instruction="This response does not settle the original Turn. Follow its recovery with the same identity; "
"state-only updates and installation maintenance cannot replace accountable writeback.")
payload["settlement_recovery"] = recovery
except (OSError, RuntimeError, ValueError) as error:
# Preserve the original write result, including an already committed
# state update. An unavailable read is not evidence of no pending debt.
payload["settlement_recovery_error"] = str(error)
36 changes: 22 additions & 14 deletions loopx/control_plane/quota/prior_turn_closeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts";
import { jsonObject } from "../runtime_decode.ts";
import {
heartbeatReceiptBinding,
heartbeatReceiptDetails,
heartbeatReceiptFactFromEvent,
selectEffectiveHeartbeatReceipt,
type HeartbeatReceiptBinding,
Expand Down Expand Up @@ -45,8 +46,18 @@ function candidate(
};
}

function admitsAutonomousReplan(event: JsonObject, fact: HeartbeatReceiptFact): boolean {
if (fact.replan_obligation_id === null || fact.settlement_effect_id === null) return false;
const guard = heartbeatReceiptDetails(event);
return guard.semantic_replan_obligation_id === fact.replan_obligation_id
&& guard.interaction_mode === "autonomous_replan" && guard.ok === true && guard.should_run === true
&& guard.must_attempt_work === true && guard.delivery_allowed === false && guard.quiet_noop_allowed === false;
}

/**
* Select the prior must-attempt Turns that still require a host closeout.
* Select prior Turns eligible for closeout readback. Guard preflight requires
* an explicit closeout marker. Refresh recovery can also discover an admitted
* replan-only binding without making it a later Turn's admission prerequisite.
*
* Every prior Turn is identity-validated, so a conflicting receipt fails the
* read instead of being hidden behind a newer Turn. Results are newest first
Expand All @@ -63,8 +74,9 @@ export function selectCloseoutCandidates(
goalId: string,
agentId: string,
excludeTurnInstanceId: string | null,
{ includeAdmittedReplans } = { includeAdmittedReplans: false },
): { candidates: PriorHostTurnCloseoutCandidate[]; turnsValidated: number } {
const perTurn = new Map<string, HeartbeatReceiptFact[]>();
const perTurn = new Map<string, { fact: HeartbeatReceiptFact; value: JsonObject }[]>();
const firstRecorded = new Map<string, number>();
for (const event of receipts) {
const fact = heartbeatReceiptFactFromEvent(event);
Expand All @@ -74,16 +86,17 @@ export function selectCloseoutCandidates(
firstRecorded.set(turnInstanceId, firstRecorded.size);
}
if (turnInstanceId === excludeTurnInstanceId) continue;
const entry = { fact, value: event };
const existing = perTurn.get(turnInstanceId);
if (existing) {
existing.push(fact);
existing.push(entry);
// Map insertion order is the append-order recency index. Moving an
// existing Turn to the tail avoids an O(T) indexOf/splice for every
// receipt while preserving "last receipt wins recency" exactly.
perTurn.delete(turnInstanceId);
perTurn.set(turnInstanceId, existing);
} else {
perTurn.set(turnInstanceId, [fact]);
perTurn.set(turnInstanceId, [entry]);
}
}

Expand All @@ -92,22 +105,17 @@ export function selectCloseoutCandidates(
? undefined : firstRecorded.get(excludeTurnInstanceId);
let validated = 0;
for (const turnInstanceId of [...perTurn.keys()].reverse()) {
const entries = (perTurn.get(turnInstanceId) ?? []).map((fact) => ({
fact,
value: fact,
}));
const effective = selectEffectiveHeartbeatReceipt(goalId, agentId, entries);
const effective = selectEffectiveHeartbeatReceipt(goalId, agentId, perTurn.get(turnInstanceId)!);
validated += 1;
if (effective === null) continue;
// Validate identities even outside the causal candidate set: filtering
// must not conceal a conflicting persisted settlement binding.
if (currentPosition !== undefined && firstRecorded.get(turnInstanceId)! >= currentPosition) continue;
// Closeout is opt-in on the persisted receipt, so older receipts from
// before this contract cannot become new recovery obligations.
if (!effective.closeout_required) continue;
const binding = heartbeatReceiptBinding(goalId, agentId, effective);
const fact = heartbeatReceiptFactFromEvent(effective);
if (!fact.closeout_required && !(includeAdmittedReplans && admitsAutonomousReplan(effective, fact))) continue;
const binding = heartbeatReceiptBinding(goalId, agentId, fact);
if (binding === null) continue;
candidates.push(candidate(binding, turnInstanceId, effective));
candidates.push(candidate(binding, turnInstanceId, fact));
}
return {candidates, turnsValidated: validated};
}
Expand Down
13 changes: 12 additions & 1 deletion loopx/control_plane/quota/settlement.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,13 +233,22 @@ def attach_settlement_progress(
}
# PowerShell quoting applies to every argument, even with an unquoted launcher.
# Keep the argv for the composed CLI so it does not have to parse shell text.
if os.name == "nt":
if os.name == "nt" or route[0].lower().endswith(".ps1"):
argv = shlex.split(command)
owed.update(command=render_owed_host_command(argv), command_argv=argv)
payload["settlement_owed"] = owed


def render_settlement_progress_markdown(payload: dict[str, Any]) -> list[str]:
recovery = payload.get("settlement_recovery")
if isinstance(recovery, dict):
identity = recovery["settlement_identity"]
lines = [f"- Pending settlement: `{identity['turn_instance_id']}`", recovery["instruction"]]
for command in recovery["next_cli_actions"]:
lines.extend(["", "```sh", command, "```"])
return lines
if payload.get("settlement_recovery_error"):
return [f"- Settlement recovery could not be read: {payload['settlement_recovery_error']}"]
progress = payload.get("settlement_progress")
if not isinstance(progress, dict):
return []
Expand Down Expand Up @@ -457,6 +466,7 @@ def read_heartbeat_settlement(
infer_turn_instance_id: bool = False,
allow_unbound_binding: bool = False,
resolve_original_binding: bool = False,
pending_closeout: bool = False,
refresh_retry: dict[str, Any] | None = None,
registry_path: Path | None = None,
goal_ref: Mapping[str, Any] | None = None,
Expand All @@ -483,6 +493,7 @@ def read_heartbeat_settlement(
else {}
),
**({"resolve_original_binding": True} if resolve_original_binding else {}),
**({"pending_closeout": True} if pending_closeout else {}),
**({"refresh_retry": refresh_retry} if refresh_retry is not None else {}),
**({"borrow_source_admission": True} if borrow_source_admission else {}),
**(
Expand Down
Loading
Loading