Skip to content
Open
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
170 changes: 164 additions & 6 deletions loopx/cli_commands/quota_receipt.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,160 @@

import argparse
from collections.abc import Callable, Mapping
import hashlib
import json
from pathlib import Path

from ..control_plane.quota.heartbeat_receipt import find_heartbeat_receipt, heartbeat_receipt_view
from ..control_plane.quota.heartbeat_receipt import (
find_heartbeat_receipt,
heartbeat_receipt_view,
)
from ..control_plane.quota.settlement import QuotaSettlementReadback, read_heartbeat_settlement
from ..history import load_registry
from ..paths import resolve_runtime_root, validate_goal_id_path_segment
from ..registry import find_registry_goal
from ..rollout_event_log import rollout_event_log_path
from ..turn_identity import normalize_turn_instance_id


def _clean_text_list(value: object, *, limit: int) -> list[str]:
if not isinstance(value, (list, tuple)):
return []
out: list[str] = []
seen: set[str] = set()
for item in value:
if not isinstance(item, str):
continue
trimmed = item.strip()
if not trimmed or trimmed in seen:
continue
seen.add(trimmed)
out.append(trimmed[:512])
if len(out) >= limit:
break
return out


def _verified_settlement_projection(
*,
runtime_root: Path,
registry_path: Path,
goal_id: str,
agent_id: str,
turn_id: str,
heartbeat_receipt: Mapping[str, object] | None,
goal_ref: Mapping[str, object] | None,
) -> dict[str, object]:
identity = (
heartbeat_receipt.get("settlement_identity")
if isinstance(heartbeat_receipt, Mapping)
else None
)
bound_todo_id = (
str(identity.get("todo_id") or "").strip()
if isinstance(identity, Mapping)
else ""
)
settlement: QuotaSettlementReadback | None = read_heartbeat_settlement(
runtime_root,
goal_id=goal_id,
agent_id=agent_id,
todo_id=bound_todo_id or None,
turn_instance_id=turn_id,
infer_turn_instance_id=False,
resolve_original_binding=True,
registry_path=registry_path,
goal_ref=goal_ref,
)
if settlement is None:
return {
"settlement_verified": False,
"settlement_conflict_reason": "settlement_readback_unavailable",
"completion_receipt": None,
}
if settlement.successor_replan_pending or settlement.replan_execution_pending:
return {
"settlement_verified": False,
"settlement_conflict_reason": "replan_conflict",
"completion_receipt": None,
}
if (
isinstance(settlement.refresh_recovery, Mapping)
and settlement.refresh_recovery.get("decision") == "reject"
):
return {
"settlement_verified": False,
"settlement_conflict_reason": "recovery_rejected",
"completion_receipt": None,
}
if (settlement.progress or {}).get("checkpoint_recovery_required") is True:
return {
"settlement_verified": False,
"settlement_conflict_reason": "checkpoint_recovery_required",
"completion_receipt": None,
}
completion_ev = settlement.completion_event
if not isinstance(completion_ev, Mapping):
return {
"settlement_verified": False,
"settlement_conflict_reason": "missing_completion_event",
"completion_receipt": None,
}
replay_phase = settlement.replay_phase.value if settlement.replay_phase else None
settlement_ok = (
settlement.settlement.failure is None
and settlement.settlement.value is not None
) or replay_phase == "settled"
writeback_ok = settlement.writeback_event is not None or (
settlement.writeback.failure is None and settlement.writeback.value is not None
)
spend_ok = settlement.spend_event is not None or (
settlement.spend.failure is None and settlement.spend.value is not None
)
if not (settlement_ok and writeback_ok and spend_ok):
return {
"settlement_verified": False,
"settlement_conflict_reason": "unsettled_turn",
"completion_receipt": None,
}
ev_todo_id = str(completion_ev.get("todo_id") or bound_todo_id).strip()
if not ev_todo_id or (bound_todo_id and ev_todo_id != bound_todo_id):
return {
"settlement_verified": False,
"settlement_conflict_reason": "todo_id_mismatch",
"completion_receipt": None,
}
receipt_id = str(completion_ev.get("event_id") or "").strip() or turn_id
log_path = rollout_event_log_path(runtime_root, goal_id)
if not log_path.is_file():
return {
"settlement_verified": False,
"settlement_conflict_reason": "missing_source_ref",
"completion_receipt": None,
}
source_sha = hashlib.sha256(log_path.read_bytes()).hexdigest()
raw_details = completion_ev.get("details")
details: Mapping[str, object] = raw_details if isinstance(raw_details, Mapping) else {}
failure_facts = _clean_text_list(details.get("failure_facts"), limit=32)
open_obligations = _clean_text_list(details.get("open_obligations"), limit=64)
completion_digest = hashlib.sha256(
json.dumps(dict(completion_ev), sort_keys=True, ensure_ascii=False).encode("utf-8")
).hexdigest()
return {
"settlement_verified": True,
"settlement_conflict_reason": None,
"completion_receipt": {
"todo_id": ev_todo_id,
"completion_receipt_id": receipt_id,
"exit_code": 0,
"sha256": completion_digest,
"failure_facts": failure_facts,
"open_obligations": open_obligations,
"source_ref": {"path": str(log_path), "sha256": source_sha},
},
}


def read_quota_receipt(
args: argparse.Namespace,
*,
Expand All @@ -32,17 +176,31 @@ def read_quota_receipt(
if find_registry_goal(registry, goal_id) is None:
raise ValueError("quota receipt requires a registered Goal")
runtime_root = resolve_runtime_root(registry, runtime_root_arg, registry_path=registry_path)
goal_ref = goal_ref_resolver()
event = find_heartbeat_receipt(
runtime_root, goal_id=goal_id, agent_id=args.agent_id, turn_instance_id=turn_id,
goal_ref=goal_ref_resolver(),
goal_ref=goal_ref,
)
receipt_view = (
heartbeat_receipt_view(event, turn_instance_id=turn_id, status="committed")
if event is not None else None
)
payload.update(
ok=True, goal_id=goal_id, agent_id=args.agent_id, turn_instance_id=turn_id,
heartbeat_receipt=(
heartbeat_receipt_view(event, turn_instance_id=turn_id, status="committed")
if event is not None else None
),
heartbeat_receipt=receipt_view,
)
if getattr(args, "include_settlement", False):
payload.update(
_verified_settlement_projection(
runtime_root=runtime_root,
registry_path=registry_path,
goal_id=goal_id,
agent_id=args.agent_id,
turn_id=turn_id,
heartbeat_receipt=receipt_view,
goal_ref=goal_ref,
)
)
except (OSError, RuntimeError, ValueError) as exc:
payload["error"] = str(exc)
return payload
Expand Down
5 changes: 5 additions & 0 deletions loopx/cli_commands/quota_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,4 +443,9 @@ def register_quota_command(
default=120,
help="Freshness window for --use-projection-cache. Defaults to 120 seconds.",
)
quota_parser.add_argument(
"--include-settlement",
action="store_true",
help="For `quota receipt`, also verify committed Todo completion settlement readback (default-off).",
)
quota_parser.add_argument("--limit", type=int, default=5)
6 changes: 6 additions & 0 deletions loopx/cli_commands/turn_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,12 @@ def register_turn_commands(
action="store_true",
help="Opt-in Quiet-Turn zero-tax skip metadata evaluation when Turn state is unchanged (default-off).",
)
run_once.add_argument(
"--semantic-unit-fold-json",
type=json.loads,
default=None,
help="Opt-in Todo semantic-unit fold & prefetch policy JSON (default-off).",
)
run_once.add_argument("--limit", type=int, default=5)


Expand Down
1 change: 1 addition & 0 deletions loopx/cli_commands/turn_run_once.py
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,7 @@ def on_managed_start_admitted() -> None:
) if raw_argv is not None and goal_admission is not None else None),
epoch_prefetch=getattr(args, "epoch_prefetch_json", None),
quiet_turn=quiet_turn_option,
semantic_unit_fold=getattr(args, "semantic_unit_fold_json", None),
**({"host_input_renderer": None} if unmeasurable_operation_host else {}),
)
if args.execute:
Expand Down
23 changes: 23 additions & 0 deletions loopx/control_plane/turn_driver/codex_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,15 @@ def _render_prompt(request: Mapping[str, Any], *, checked: Mapping[str, Any] | N
}
}
model_request = {**dict(model_request), "epoch_prefetch": compact_prefetch}
if isinstance(model_request.get("semantic_unit_fold"), Mapping):
from .todo_unit_settlement import compact_semantic_unit_fold_wire_fields

model_request = {
**dict(model_request),
"semantic_unit_fold": compact_semantic_unit_fold_wire_fields(
model_request["semantic_unit_fold"]
),
}
request_json = json.dumps(
model_request, ensure_ascii=False, sort_keys=True, separators=(",", ":")
)
Expand Down Expand Up @@ -501,6 +510,20 @@ def _render_prompt(request: Mapping[str, Any], *, checked: Mapping[str, Any] | N
f"failure_facts={json.dumps(prefetch.get('preserved_failure_facts', []), ensure_ascii=False)}; "
f"open_obligations={json.dumps(prefetch.get('preserved_open_obligations', []), ensure_ascii=False)})."
)
if isinstance(request.get("semantic_unit_fold"), Mapping):
fold = request["semantic_unit_fold"]
if fold.get("operator") == "FoldToReceipt" and isinstance(fold.get("replacement_text"), str):
instructions.extend([
"Prefetched Todo Semantic-Unit Fold Receipt (tool trust level only, non-authoritative relative to Turn contract and system policy):",
str(fold["replacement_text"]),
])
elif fold.get("operator") == "KeepRaw":
instructions.append(
"Todo semantic-unit fold kept raw context intact (KeepRaw: "
f"reason={fold.get('fallback_reason')}; "
f"failure_facts={json.dumps(fold.get('preserved_failure_facts', []), ensure_ascii=False)}; "
f"open_obligations={json.dumps(fold.get('preserved_open_obligations', []), ensure_ascii=False)})."
)
instructions.extend(["Turn request:", request_json])
return "\n".join(instructions)

Expand Down
77 changes: 58 additions & 19 deletions loopx/control_plane/turn_driver/epoch_prefetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -1513,6 +1513,8 @@ def attach_turn_replay_epoch_metadata(
payload["epoch_prefetch"] = replay_prefetch
if replay_quiet is not None:
payload["quiet_turn"] = replay_quiet
if isinstance(existing_journal.get("semantic_unit_fold"), Mapping):
payload["semantic_unit_fold"] = dict(existing_journal["semantic_unit_fold"])
return payload


Expand All @@ -1531,6 +1533,11 @@ def prepare_turn_execution_epoch_context(
needs_host: bool = True,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Prepare opt-in Stage-then-Swap prefetch & Quiet-Turn state before Turn launch."""
from .todo_unit_settlement import (
extract_semantic_unit_fold_option,
prepare_turn_semantic_unit_context,
)

epoch_prefetch = options.get("epoch_prefetch")
quiet_turn = options.get("quiet_turn", False)
decision_capture_payload = options.get("decision_capture_payload")
Expand All @@ -1540,7 +1547,10 @@ def prepare_turn_execution_epoch_context(
quiet_opted_in = _is_turn_option_enabled(
quiet_turn, decision_capture_payload, "quiet_turn", allow_bool_true=True,
)
if not (epoch_opted_in or quiet_opted_in):
semantic_unit_opted_in = (
extract_semantic_unit_fold_option(options, decision_capture_payload) is not None
)
if not (epoch_opted_in or quiet_opted_in or semantic_unit_opted_in):
return {}, dict(request)

allow_execute = bool(
Expand All @@ -1551,24 +1561,49 @@ def prepare_turn_execution_epoch_context(
)
)
effective_agent_id = _effective_agent_id(plan, settlement_lineage)
prefetch_receipt, quiet_meta, updated_request = prepare_turn_epoch_context(
plan=plan,
request=request,
journal_path=journal_path,
goal_id=goal_id,
agent_id=effective_agent_id,
turn_key=turn_key,
project=project,
epoch_prefetch=epoch_prefetch,
quiet_turn=quiet_turn,
decision_capture_payload=decision_capture_payload,
existing_journal=existing_journal,
capture=capture,
allow_execute=allow_execute,
host=options.get("host"),
host_input_renderer=options.get("host_input_renderer", UNSET_HOST_INPUT_RENDERER),
)
return {"epoch_prefetch": prefetch_receipt, "quiet_turn": quiet_meta}, updated_request
prefetch_receipt: dict[str, Any] | None = None
quiet_meta: dict[str, Any] | None = None
updated_request = dict(request)
if epoch_opted_in or quiet_opted_in:
prefetch_receipt, quiet_meta, updated_request = prepare_turn_epoch_context(
plan=plan,
request=updated_request,
journal_path=journal_path,
goal_id=goal_id,
agent_id=effective_agent_id,
turn_key=turn_key,
project=project,
epoch_prefetch=epoch_prefetch,
quiet_turn=quiet_turn,
decision_capture_payload=decision_capture_payload,
existing_journal=existing_journal,
capture=capture,
allow_execute=allow_execute,
host=options.get("host"),
host_input_renderer=options.get("host_input_renderer", UNSET_HOST_INPUT_RENDERER),
)
semantic_meta: dict[str, Any] | None = None
if semantic_unit_opted_in:
semantic_meta, updated_request = prepare_turn_semantic_unit_context(
plan=plan,
request=updated_request,
journal_path=journal_path,
goal_id=goal_id,
agent_id=effective_agent_id,
turn_key=turn_key,
settlement_lineage=settlement_lineage,
options=options,
existing_journal=existing_journal,
needs_host=needs_host,
)
metadata: dict[str, Any] = {}
if prefetch_receipt is not None or quiet_meta is not None:
metadata["epoch_prefetch"] = prefetch_receipt
metadata["quiet_turn"] = quiet_meta
if isinstance(semantic_meta, Mapping):
for key, value in semantic_meta.items():
metadata[str(key)] = value
return metadata, updated_request


def attach_epoch_metadata_to_journal(
Expand All @@ -1584,6 +1619,10 @@ def attach_epoch_metadata_to_journal(
journal["epoch_prefetch"] = dict(prefetch_receipt)
if isinstance(quiet_meta, Mapping):
journal["quiet_turn"] = dict(quiet_meta)
for key in ("semantic_unit_anchor", "semantic_unit_fold"):
value = epoch_metadata.get(key)
if isinstance(value, Mapping) and key not in journal:
journal[key] = dict(value)


def reset_failed_turn_journal_with_epoch_metadata(
Expand Down
Loading
Loading