From 74bd2406ff0ac93ed10fcf71554968894f18dfa8 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:38:00 +0800 Subject: [PATCH] refactor(quota): modularize slot_accounting with zero Any and lazy index scan Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/control_plane/quota/slot_accounting.py | 1045 +++-------------- .../quota/slot_preview_settlement.py | 399 +++++++ .../quota/slot_preview_workspace.py | 520 ++++++++ .../test_slot_accounting_contract.py | 618 ++++++++++ 4 files changed, 1722 insertions(+), 860 deletions(-) create mode 100644 loopx/control_plane/quota/slot_preview_settlement.py create mode 100644 loopx/control_plane/quota/slot_preview_workspace.py create mode 100644 tests/control_plane/test_slot_accounting_contract.py diff --git a/loopx/control_plane/quota/slot_accounting.py b/loopx/control_plane/quota/slot_accounting.py index 016f245df1..817b89359f 100644 --- a/loopx/control_plane/quota/slot_accounting.py +++ b/loopx/control_plane/quota/slot_accounting.py @@ -1,368 +1,57 @@ -from __future__ import annotations +"""Quota slot preview accounting facade and settlement preview orchestration.""" -from typing import Any, cast -from .effective_action import EffectiveAction +from __future__ import annotations -import json from collections.abc import Callable, Mapping -from copy import deepcopy from pathlib import Path +from typing import cast -from ..agents.workspace_guard import ( - build_delivery_workspace_guard, - delivery_workspace_identity, +from ...paths import validate_goal_id_path_segment as _validate_goal_id_path_segment +from ..effect_program import ( + SettlementFailure, + settlement_result_payload, ) from ..todos.contract import ( normalize_todo_claimed_by, normalize_todo_id, normalize_todo_replan_obligation_id, ) -from ..work_items.delivery_outcome import ( - normalize_delivery_outcome, - qualifies_turn_scoped_settlement, -) -from .monitor_poll import QUOTA_MONITOR_POLL_CLASSIFICATION -from .scheduler_ack import QUOTA_SCHEDULER_ACK_CLASSIFICATION -from ...paths import validate_goal_id_path_segment as _validate_goal_id_path_segment -from ..effect_program import SettlementBindingKind -from .settlement import ( - SettlementFailure, - SettlementFailureKind, - SettlementIdentity, - SettlementResult, - SettlementStepKind, - read_heartbeat_settlement, - settlement_result_payload, +from .effective_action import EffectiveAction +from .ledger_readback import ( + QUOTA_SLOT_SPENT_CLASSIFICATION as QUOTA_SLOT_SPENT_CLASSIFICATION, + QUOTA_SLOT_VOIDED_CLASSIFICATION as QUOTA_SLOT_VOIDED_CLASSIFICATION, + _int_number, + load_quota_event_from_run as load_quota_event_from_run, + net_quota_slot_spend as net_quota_slot_spend, + quota_slot_contribution as quota_slot_contribution, ) -from .settlement_workspace_causality import ( - LEGACY_SETTLEMENT_RECEIPT_EVIDENCE_SCHEMA_VERSION, - completed_todo_workspace_causality, - missing_delivery_workspace_resolution, - resolve_settlement_workspace_requirement, +from .slot_preview_settlement import ( + DELIVERY_COMPLETION_SPEND_STATES, + TERMINAL_NO_FOLLOWUP_DECISION_STATE, + admits_delivery_completion_spend_state, + resolve_preview_settlement, + select_latest_unspent_turn_settlement_run, + todo_binding_error, + unbound_visible_goal_settlement_failure, ) -from .settlement_validation import completion_validation_spend_error -from .spend_sources import ( - DEFAULT_SLOT_SPEND_SOURCE, - TURN_SCOPED_SLOT_SPEND_SOURCES, - VISIBLE_GOAL_SLOT_SPEND_SOURCE, +from .slot_preview_workspace import ( + build_preview_success_payload, + evaluate_delivery_workspace_preview, + preview_failure_payload, ) from .spend_commit import ( build_quota_slot_spend_event as build_quota_slot_spend_event, record_quota_slot_spend_from_preview as record_quota_slot_spend_from_preview, ) +from .spend_sources import DEFAULT_SLOT_SPEND_SOURCE from .void_commit import ( build_quota_slot_void_event as build_quota_slot_void_event, build_quota_slot_void_preview_for_decision as build_quota_slot_void_preview_for_decision, record_quota_slot_void_from_preview as record_quota_slot_void_from_preview, ) -from .ledger_readback import ( - QUOTA_SLOT_SPENT_CLASSIFICATION as QUOTA_SLOT_SPENT_CLASSIFICATION, - QUOTA_SLOT_VOIDED_CLASSIFICATION as QUOTA_SLOT_VOIDED_CLASSIFICATION, - _int_number, - load_quota_event_from_run as load_quota_event_from_run, - net_quota_slot_spend as net_quota_slot_spend, - quota_slot_contribution as quota_slot_contribution, -) - -QuotaDecisionBuilder = Callable[[dict[str, Any]], dict[str, Any]] -QuotaStatusBuilder = Callable[..., dict[str, Any]] - - -def _todo_binding_error( - *, - source: str, - status_payload: dict[str, Any], - goal_id: str, - before: dict[str, Any], - requested_todo_id: str | None, - requested_replan_obligation_id: str | None, - agent_id: str | None, - settlement_identity: SettlementIdentity | None = None, - delivery_run: dict[str, Any] | None = None, -) -> str | None: - selected = ( - cast(dict[str, Any], before.get("selected_todo")) - if isinstance(before.get("selected_todo"), dict) - else {} - ) - if settlement_identity is not None: - if ( - requested_todo_id != settlement_identity.todo_id - or requested_replan_obligation_id - != settlement_identity.replan_obligation_id - ): - return ( - "quota spend binding does not match the original settlement " - f"identity: expected {settlement_identity.binding_kind}=" - f"{settlement_identity.binding_id}" - ) - return completion_validation_spend_error( - status_payload, - goal_id=goal_id, - todo_id=requested_todo_id, - agent_id=agent_id, - selected_todo=selected, - delivery_run=delivery_run, - ) - selected_todo_id = normalize_todo_id(selected.get("todo_id")) - if requested_todo_id and selected_todo_id and requested_todo_id != selected_todo_id: - return ( - f"quota spend todo binding mismatch: selected todo is " - f"{selected_todo_id} but --todo-id is {requested_todo_id}; " - "complete or update the selected todo first, or record a replan" - ) - if ( - source == DEFAULT_SLOT_SPEND_SOURCE - and before.get("normal_delivery_allowed") is True - and selected_todo_id - and not requested_todo_id - ): - return ( - f"quota spend requires --todo-id {selected_todo_id} for heartbeat " - "delivery so the accounted turn is bound to the selected todo" - ) - return completion_validation_spend_error( - status_payload, - goal_id=goal_id, - todo_id=requested_todo_id, - agent_id=agent_id, - selected_todo=selected, - delivery_run=None, - ) - - -def _receipt_committed( - result: SettlementResult[Any] | None, - step_kind: SettlementStepKind, -) -> bool: - """Report whether one settlement step already owns a committed receipt.""" - - if result is None or result.failure is not None: - return False - return any( - receipt.step_kind is step_kind and receipt.status == "committed" - for receipt in result.receipts - ) - - -def _resolve_preview_settlement( - *, - raw_runtime_root: Any, - source: str, - goal_id: str, - agent_id: str | None, - todo_id: str | None, - replan_obligation_id: str | None, - turn_instance_id: str | None, - registry_path: Path | None, - goal_ref: Mapping[str, Any] | None, -) -> dict[str, Any]: - if turn_instance_id and source not in TURN_SCOPED_SLOT_SPEND_SOURCES: - result: SettlementResult[Any] = SettlementResult.failed( - kind=SettlementFailureKind.INVALID_IDENTITY, - step_kind=SettlementStepKind.VALIDATION, - reason=( - "turn-scoped settlement is valid only for heartbeat or " - "visible-goal spend" - ), - ) - return {"reason": cast(SettlementFailure, result.failure).reason, "result": result} - if turn_instance_id and not raw_runtime_root: - return {"reason": "status payload does not include runtime_root"} - if source not in TURN_SCOPED_SLOT_SPEND_SOURCES or not raw_runtime_root: - return {} - runtime_root = Path(str(raw_runtime_root)).expanduser() - readback = read_heartbeat_settlement( - runtime_root, - goal_id=goal_id, - agent_id=agent_id, - todo_id=todo_id, - turn_instance_id=turn_instance_id, - replan_obligation_id=replan_obligation_id, - infer_turn_instance_id=not bool(turn_instance_id), - allow_unbound_binding=( - source == VISIBLE_GOAL_SLOT_SPEND_SOURCE - and not todo_id - and not replan_obligation_id - ), - registry_path=registry_path, - goal_ref=goal_ref, - ) - if readback is None: - return {} - if ( - isinstance(readback.progress, dict) - and readback.progress.get("closeout_kind") - in {"typed_blocked_writeback_no_spend", "capability_duty_retired_no_spend"} - ): - return { - "identity": readback.identity.value, - "result": readback.settlement, - "delivery_run": readback.writeback_run, - "reason": ( - "this exact capability duty was retired and must not consume a quota slot; reassess the current frontier in a new Turn" - if readback.progress.get("closeout_kind") == "capability_duty_retired_no_spend" else - "this Turn already closed with an exact typed blocked writeback " - "and must not consume a quota slot; retry the Todo only after " - "its external blocker changes or a bounded backoff" - ), - } - result = readback.identity - identity = result.value if result.failure is None else None - if identity is not None: - result = readback.delivery - return { - "identity": identity, - "result": result, - "delivery_run": result.value if result.failure is None else None, - "delivery_workspace_causality": readback.workspace_causality, - "reason": result.failure.reason if result.failure is not None else None, - "writeback_committed": _receipt_committed( - readback.writeback, SettlementStepKind.DURABLE_WRITEBACK - ), - "spend_committed": _receipt_committed( - readback.spend, SettlementStepKind.QUOTA_SPEND - ), - } - - -def _unbound_visible_goal_settlement_failure( - *, - source: str, - before: dict[str, Any], - requested_todo_id: str | None, - requested_replan_obligation_id: str | None, - turn_instance_id: str | None, -) -> SettlementResult[SettlementIdentity] | None: - if ( - source != VISIBLE_GOAL_SLOT_SPEND_SOURCE - or before.get("normal_delivery_allowed") is not True - ): - return None - selected = ( - cast(dict[str, Any], before.get("selected_todo")) - if isinstance(before.get("selected_todo"), dict) - else {} - ) - selected_todo_id = normalize_todo_id(selected.get("todo_id")) - if not selected_todo_id: - return None - if bool(requested_todo_id) == bool(requested_replan_obligation_id): - reason = ( - "visible Goal settlement requires exactly one todo_id or " - "replan_obligation_id binding" - ) - elif not turn_instance_id: - reason = ( - "visible Goal settlement for selected Todo " - f"{selected_todo_id} requires turn_instance_id from quota should-run; " - "rerun the guard with --begin-turn" - ) - else: - return None - return SettlementResult.failed( - kind=SettlementFailureKind.IDENTITY_MISMATCH, - step_kind=SettlementStepKind.VALIDATION, - reason=reason, - details={ - "source": source, - "selected_todo_id": selected_todo_id, - "requested_todo_id": requested_todo_id, - "requested_replan_obligation_id": requested_replan_obligation_id, - "turn_instance_id": turn_instance_id, - }, - ) - - -def _repair_settlement_workspace_causality( - status_payload: dict[str, Any], - *, - goal_id: str, - settlement_identity: SettlementIdentity | None, - causality: dict[str, Any] | None, -) -> dict[str, Any] | None: - requirement = str((causality or {}).get("requirement") or "") - if settlement_identity is None or requirement not in {"", "unknown"}: - return causality - repaired = completed_todo_workspace_causality( - status_payload, - goal_id=goal_id, - todo_id=settlement_identity.todo_id, - source=( - "current_todo_contract_repair" - if requirement == "unknown" - else "completed_todo_contract_fallback" - ), - ) - if str((repaired or {}).get("requirement") or "") == "unknown": - return causality - return repaired or causality - - -def _queue_item_for_goal(status_payload: dict[str, Any], *, goal_id: str) -> dict[str, Any]: - queue = cast(dict[str, Any], status_payload.get("attention_queue")) if isinstance(status_payload.get("attention_queue"), dict) else {} - queue_items = cast(list[Any], queue.get("items")) if isinstance(queue.get("items"), list) else [] - return next( - ( - item - for item in queue_items - if isinstance(item, dict) and str(item.get("goal_id") or "") == goal_id - ), - {}, - ) - - -def _set_quota_for_goal(status_payload: dict[str, Any], *, goal_id: str, quota: dict[str, Any]) -> None: - run_history = cast(dict[str, Any], status_payload.get("run_history")) if isinstance(status_payload.get("run_history"), dict) else {} - run_goals = cast(list[Any], run_history.get("goals")) if isinstance(run_history.get("goals"), list) else [] - for goal in run_goals: - if isinstance(goal, dict) and str(goal.get("id") or "") == goal_id: - goal["quota"] = dict(quota) - - queue = cast(dict[str, Any], status_payload.get("attention_queue")) if isinstance(status_payload.get("attention_queue"), dict) else {} - queue_items = cast(list[Any], queue.get("items")) if isinstance(queue.get("items"), list) else [] - for item in queue_items: - if isinstance(item, dict) and str(item.get("goal_id") or "") == goal_id: - item["quota"] = dict(quota) - project_asset = cast(dict[str, Any], item.get("project_asset")) if isinstance(item.get("project_asset"), dict) else {} - if project_asset: - project_asset["quota"] = dict(quota) - - -def _load_goal_run_index_records(runtime_root: Path, goal_id: str) -> list[dict[str, Any]]: - index_path = runtime_root / "goals" / goal_id / "runs" / "index.jsonl" - if not index_path.exists(): - return [] - records: list[dict[str, Any]] = [] - try: - lines = index_path.read_text(encoding="utf-8").split("\n") - except OSError: - return [] - for line in lines: - if not line.strip(): - continue - try: - record = json.loads(line) - except json.JSONDecodeError: - continue - if isinstance(record, dict): - records.append(record) - return records - - -def _is_quota_neutral_state_refresh(run: dict[str, Any]) -> bool: - """Recognize refresh-state provenance without relying on its classification.""" - - if str(run.get("delivery_outcome") or "").strip(): - return False - if str(run.get("classification") or "").strip() == "state_refreshed": - return True - return ( - isinstance(run.get("state"), dict) - and isinstance(run.get("runtime_projection_route"), dict) - and bool(str(run.get("recommended_action_source") or "").strip()) - ) +QuotaDecisionBuilder = Callable[[dict[str, object]], dict[str, object]] +QuotaStatusBuilder = Callable[..., dict[str, object]] def _latest_unspent_turn_settlement_run( @@ -370,8 +59,8 @@ def _latest_unspent_turn_settlement_run( goal_id: str, *, agent_id: str | None = None, - goal_ref: Mapping[str, Any] | None = None, -) -> dict[str, Any] | None: + goal_ref: Mapping[str, object] | None = None, +) -> dict[str, object] | None: """Return the latest same-agent Turn settlement that still needs accounting. Unchanged monitor polls, scheduler acknowledgements, and plain state @@ -381,214 +70,19 @@ def _latest_unspent_turn_settlement_run( fail closed. A typed blocked ``outcome_gap`` settles the Turn without being reclassified as delivery progress. """ - - safe_agent_id = normalize_todo_claimed_by(agent_id) - for run in reversed(_load_goal_run_index_records(runtime_root, goal_id)): - if goal_ref is None and "goal_ref" in run: - continue - if goal_ref is not None and run.get("goal_ref") != dict(goal_ref): - continue - run_agent_id = normalize_todo_claimed_by(run.get("agent_id")) - if safe_agent_id and run_agent_id and safe_agent_id != run_agent_id: - continue - classification = str(run.get("classification") or "").strip() - if classification == QUOTA_SLOT_VOIDED_CLASSIFICATION: - continue - if classification == QUOTA_SLOT_SPENT_CLASSIFICATION: - return None - if ( - classification == QUOTA_MONITOR_POLL_CLASSIFICATION - and run.get("material_change") is not True - ): - continue - if classification == QUOTA_SCHEDULER_ACK_CLASSIFICATION: - continue - if _is_quota_neutral_state_refresh(run): - continue - delivery_outcome = normalize_delivery_outcome(run.get("delivery_outcome")) - if qualifies_turn_scoped_settlement( - delivery_outcome, - cast(dict[str, Any], run.get("progress_observation")) - if isinstance(run.get("progress_observation"), dict) - else None, - work_item_id=normalize_todo_id(run.get("todo_id")), - replan_obligation_id=normalize_todo_replan_obligation_id( - run.get("replan_obligation_id") - ), - ): - return run - return None - return None - - -def _settlement_workspace_requirement( - delivery_workspace_causality: dict[str, Any] | None, - settlement_identity: SettlementIdentity | None, - settlement_result: SettlementResult[dict[str, Any]] | None, - delivery_completion_run: dict[str, Any] | None, -) -> dict[str, str] | None: - if settlement_identity is None: - return None - return resolve_settlement_workspace_requirement( - delivery_workspace_causality, - settlement_binding_kind=settlement_identity.binding_kind.value, - legacy_settlement_evidence=( - { - "schema_version": ( - LEGACY_SETTLEMENT_RECEIPT_EVIDENCE_SCHEMA_VERSION - ), - "settlement_effect_id": settlement_identity.effect_id, - "delivery_workspace_present": bool( - isinstance(delivery_completion_run, dict) - and delivery_completion_run.get("delivery_workspace") is not None - ), - "receipts": [ - { - "step_kind": receipt.step_kind.value, - "status": receipt.status, - "effect_id": receipt.effect_id, - } - for receipt in settlement_result.receipts - ], - } - if settlement_result is not None - and settlement_result.failure is None - else None - ), - ) - - -def _workspace_requirement_value( - settlement_workspace_requirement: dict[str, Any] | None, - delivery_workspace_causality: dict[str, Any] | None, -) -> str: - return str( - (settlement_workspace_requirement or {}).get("requirement") - or (delivery_workspace_causality or {}).get("requirement") - or "" - ) - - -def _missing_delivery_workspace_preview( - *, - delivery_workspace_causality: dict[str, Any] | None, - settlement_workspace_requirement: dict[str, Any] | None, - delivery_workspace: dict[str, Any] | None, - goal_id: str, - slots: int, - agent_id: str | None, - before: dict[str, Any], -) -> dict[str, Any] | None: - if delivery_workspace_identity(delivery_workspace): - return None - requirement = _workspace_requirement_value( - settlement_workspace_requirement, delivery_workspace_causality - ) - if not requirement or requirement == "not_required": - return None - resolution = missing_delivery_workspace_resolution( - delivery_workspace_causality - ) - if resolution is not None and resolution["decision"] == "omit_snapshot": - return None - reason = ( - "quota spend requires a valid delivery workspace snapshot for " - f"settlement causality requirement {requirement}" - if resolution is not None - and resolution["decision"] == "require_snapshot" - else ( - "quota spend requires an explicit Todo delivery contract; declare " - "repository/write requirements or mark the Todo as explicit " - "non-delivery, then retry the same settlement" - ) - ) - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": goal_id, - "slots": slots, - "agent_id": agent_id, - "appended": False, - "registry_mutated": False, - "reason": reason, - "delivery_workspace": delivery_workspace, - "delivery_workspace_causality": delivery_workspace_causality, - "settlement_workspace_requirement": settlement_workspace_requirement, - "delivery_workspace_resolution": resolution, - "delivery_workspace_validated": False, - "before": before, - "after": None, - } - - -DELIVERY_COMPLETION_SPEND_STATES = frozenset( - {"waiting", "focus_wait", "operator_gate", "eligible"} -) -TERMINAL_NO_FOLLOWUP_DECISION_STATE = "terminal_no_followup" - - -def _admits_delivery_completion_spend_state( - *, - before: Mapping[str, Any], - identity: SettlementIdentity | None, - settlement: Mapping[str, Any], -) -> bool: - """Admit the decision states one delivery-completion spend may settle from. - - ``terminal_no_followup`` is admitted only for the autonomous-replan - settlement whose own durable writeback derived that frontier and which has - not yet recorded its spend. The terminal guard therefore stays strict for - every new, unrelated, or already-accounted spend, while the remaining step - of the settlement that produced the terminal frontier is no longer - stranded. See the ``terminal_settlement_ordering_gap`` repair pattern. - """ - - state = str(before.get("state") or "") - if state in DELIVERY_COMPLETION_SPEND_STATES: - return True - if state != TERMINAL_NO_FOLLOWUP_DECISION_STATE: - return False - return ( - identity is not None - and identity.binding_kind is SettlementBindingKind.AUTONOMOUS_REPLAN - and settlement.get("writeback_committed") is True - and settlement.get("spend_committed") is not True - ) - - -def _workspace_repair_blocks_spend( - before: Mapping[str, Any], - *, - delivery_workspace_validated: bool, - delivery_run: Mapping[str, Any] | None, - settlement_identity: SettlementIdentity | None, - workspace_requirement: str, -) -> bool: - """Keep the current workspace guard separate from an original settlement. - - The existing typed requirement owner decides whether that settlement needs - a workspace. This adapter only applies the recovered result to the guard; - an unbound or unwritten settlement cannot waive it. - """ - settlement_does_not_require_workspace = ( - delivery_run is not None - and settlement_identity is not None - and workspace_requirement == "not_required" - ) - return ( - before.get("effective_action") == EffectiveAction.AGENT_WORKSPACE_REPAIR.value - and before.get("workspace_repair_allowed") is True - and not delivery_workspace_validated - and not settlement_does_not_require_workspace + return select_latest_unspent_turn_settlement_run( + runtime_root, + goal_id, + agent_id=agent_id, + goal_ref=goal_ref, ) def build_quota_slot_preview_for_decision( - status_payload: dict[str, Any], + status_payload: Mapping[str, object], *, goal_id: str, - before: dict[str, Any], + before: Mapping[str, object], after_decision: QuotaDecisionBuilder, quota_status_builder: QuotaStatusBuilder, self_repair_spend_actions: set[str] | frozenset[str], @@ -600,8 +94,9 @@ def build_quota_slot_preview_for_decision( turn_instance_id: str | None = None, source: str = DEFAULT_SLOT_SPEND_SOURCE, registry_path: Path | None = None, - goal_ref: Mapping[str, Any] | None = None, -) -> dict[str, Any]: + goal_ref: Mapping[str, object] | None = None, +) -> dict[str, object]: + """Validate settlement admission and preview a quota spend state transition.""" safe_goal_id = _validate_goal_id_path_segment(str(goal_id or "")) safe_slots = max(1, _int_number(slots, default=1)) safe_requested_agent_id = normalize_todo_claimed_by(agent_id) @@ -609,7 +104,7 @@ def build_quota_slot_preview_for_decision( normalized_replan_obligation_id = normalize_todo_replan_obligation_id( replan_obligation_id ) - unbound_visible_goal_failure = _unbound_visible_goal_settlement_failure( + unbound_visible_goal_failure = unbound_visible_goal_settlement_failure( source=source, before=before, requested_todo_id=normalized_todo_id, @@ -617,31 +112,23 @@ def build_quota_slot_preview_for_decision( turn_instance_id=turn_instance_id, ) if unbound_visible_goal_failure is not None: - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "reason": cast(SettlementFailure, unbound_visible_goal_failure.failure).reason, - "settlement_result": settlement_result_payload( - unbound_visible_goal_failure - ), - "delivery_workspace": None, - "delivery_workspace_causality": None, - "delivery_workspace_validated": False, - "before": before, - "after": None, - } + return preview_failure_payload( + goal_id=safe_goal_id, + slots=safe_slots, + agent_id=safe_requested_agent_id, + reason=cast(SettlementFailure, unbound_visible_goal_failure.failure).reason, + before=before, + extra={ + "settlement_result": settlement_result_payload( + unbound_visible_goal_failure + ), + "delivery_workspace": None, + "delivery_workspace_causality": None, + "delivery_workspace_validated": False, + }, + ) raw_runtime_root = status_payload.get("runtime_root") - settlement_identity = None - settlement_result = None - delivery_completion_run = None - delivery_workspace_causality = None - settlement = _resolve_preview_settlement( + settlement = resolve_preview_settlement( raw_runtime_root=raw_runtime_root, source=source, goal_id=safe_goal_id, @@ -652,32 +139,24 @@ def build_quota_slot_preview_for_decision( registry_path=registry_path, goal_ref=goal_ref, ) - settlement_identity = settlement.get("identity") - settlement_result = settlement.get("result") - delivery_completion_run = settlement.get("delivery_run") - delivery_workspace_causality = settlement.get( - "delivery_workspace_causality" - ) - if settlement.get("reason"): - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "reason": settlement["reason"], - "settlement_result": ( - settlement_result_payload(settlement_result) - if settlement_result is not None - else None - ), - "before": before, - "after": None, - } - binding_error = _todo_binding_error( + settlement_identity = settlement.identity + settlement_result = settlement.result + if settlement.reason: + return preview_failure_payload( + goal_id=safe_goal_id, + slots=safe_slots, + agent_id=safe_requested_agent_id, + reason=settlement.reason, + before=before, + extra={ + "settlement_result": ( + settlement_result_payload(settlement_result) + if settlement_result is not None + else None + ) + }, + ) + binding_error = todo_binding_error( source=source, status_payload=status_payload, goal_id=safe_goal_id, @@ -687,37 +166,28 @@ def build_quota_slot_preview_for_decision( agent_id=safe_requested_agent_id, settlement_identity=settlement_identity, delivery_run=( - delivery_completion_run if settlement_identity is not None else None + settlement.delivery_run if settlement_identity is not None else None ), ) if binding_error: - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "reason": binding_error, - "before": before, - "after": None, - } - safe_bypass_requested = ( - ( - before.get("state") == "operator_gate" - or before.get("recovery_delivery_allowed") is True - or before.get("effective_action") == EffectiveAction.OUTCOME_FLOOR_RECOVERY.value + return preview_failure_payload( + goal_id=safe_goal_id, + slots=safe_slots, + agent_id=safe_requested_agent_id, + reason=binding_error, + before=before, ) - and before.get("safe_bypass_allowed") is True - ) + safe_bypass_requested = ( + before.get("state") == "operator_gate" + or before.get("recovery_delivery_allowed") is True + or before.get("effective_action") == EffectiveAction.OUTCOME_FLOOR_RECOVERY.value + ) and before.get("safe_bypass_allowed") is True self_repair_spend = before.get("effective_action") in self_repair_spend_actions capability_repair_spend = ( before.get("effective_action") == EffectiveAction.CAPABILITY_BRIDGE_REPAIR.value and before.get("capability_repair_allowed") is True ) - delivery_completion_run = delivery_completion_run or ( + delivery_completion_run = settlement.delivery_run or ( _latest_unspent_turn_settlement_run( Path(str(raw_runtime_root)).expanduser(), safe_goal_id, @@ -727,137 +197,41 @@ def build_quota_slot_preview_for_decision( if raw_runtime_root else None ) - delivery_workspace_causality = _repair_settlement_workspace_causality( + workspace_state = evaluate_delivery_workspace_preview( status_payload, goal_id=safe_goal_id, - settlement_identity=settlement_identity, - causality=delivery_workspace_causality, - ) - settlement_workspace_requirement = _settlement_workspace_requirement( - delivery_workspace_causality, - settlement_identity, - settlement_result, - delivery_completion_run, - ) - safe_bypass_without_delivery = ( - safe_bypass_requested and delivery_completion_run is None - ) - if safe_bypass_without_delivery: - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "reason": ( - "safe-bypass quota spend requires a latest " - "unspent Turn settlement writeback" - ), - "before": before, - "after": None, - } - safe_bypass_spend = safe_bypass_requested - raw_delivery_workspace = ( - cast(dict[str, Any], delivery_completion_run.get("delivery_workspace")) - if isinstance(delivery_completion_run, dict) - and isinstance(delivery_completion_run.get("delivery_workspace"), dict) - else None - ) - missing_delivery_workspace_preview = _missing_delivery_workspace_preview( - delivery_workspace_causality=delivery_workspace_causality, - settlement_workspace_requirement=settlement_workspace_requirement, - delivery_workspace=raw_delivery_workspace, - goal_id=safe_goal_id, slots=safe_slots, agent_id=safe_requested_agent_id, + workspace_path=workspace_path, before=before, - ) - if missing_delivery_workspace_preview: - return missing_delivery_workspace_preview - workspace_requirement = _workspace_requirement_value( - settlement_workspace_requirement, delivery_workspace_causality - ) - raw_delivery_workspace_identity = delivery_workspace_identity( - raw_delivery_workspace - ) - delivery_workspace = ( - raw_delivery_workspace - if raw_delivery_workspace_identity - and workspace_requirement != "not_required" - else None - ) - delivery_workspace_guard = ( - build_delivery_workspace_guard( - delivery_completion_run, - agent_id=safe_requested_agent_id, - current_path=workspace_path, - ) - if delivery_completion_run and delivery_workspace - else None - ) - if delivery_workspace_guard: - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "reason": delivery_workspace_guard["reason"], - "workspace_guard": delivery_workspace_guard, - "delivery_workspace": delivery_workspace, - "delivery_workspace_causality": delivery_workspace_causality, - "delivery_workspace_validated": False, - "before": before, - "after": None, - } - delivery_workspace_validated = bool(delivery_workspace) - if _workspace_repair_blocks_spend( - before, - delivery_workspace_validated=delivery_workspace_validated, - delivery_run=delivery_completion_run, settlement_identity=settlement_identity, - workspace_requirement=workspace_requirement, - ): - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "delivery_workspace": delivery_workspace, - "delivery_workspace_causality": delivery_workspace_causality, - "delivery_workspace_validated": False, - "reason": ( - "agent workspace guard requires moving to an independent " - "worktree and rerunning quota should-run before quota spend" - ), - "before": before, - "after": None, - } + settlement_result=settlement_result, + causality=settlement.delivery_workspace_causality, + delivery_completion_run=delivery_completion_run, + safe_bypass_requested=safe_bypass_requested, + ) + if workspace_state.failure_preview is not None: + return workspace_state.failure_preview + + safe_bypass_spend = safe_bypass_requested delivery_completion_spend = ( delivery_completion_run is not None - and before.get("ok") + and bool(before.get("ok")) and ( settlement_identity is not None or not before.get("should_run") - or before.get("effective_action") == EffectiveAction.EXTERNAL_EVIDENCE_OBSERVE.value + or before.get("effective_action") + == EffectiveAction.EXTERNAL_EVIDENCE_OBSERVE.value or ( - before.get("effective_action") == EffectiveAction.AGENT_WORKSPACE_REPAIR.value - and delivery_workspace_validated + before.get("effective_action") + == EffectiveAction.AGENT_WORKSPACE_REPAIR.value + and workspace_state.delivery_workspace_validated ) ) - and before.get("effective_action") != EffectiveAction.AUTOMATION_PROMPT_UPGRADE_REQUIRED.value + and before.get("effective_action") + != EffectiveAction.AUTOMATION_PROMPT_UPGRADE_REQUIRED.value and not safe_bypass_spend - and _admits_delivery_completion_spend_state( + and admits_delivery_completion_spend_state( before=before, identity=settlement_identity, settlement=settlement, @@ -871,128 +245,79 @@ def build_quota_slot_preview_for_decision( and not capability_repair_spend and not delivery_completion_spend ): - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "reason": before.get("reason") or "goal is not eligible for quota accounting preview", - # Transport the actual rejecting action, not an incidental quota - # snapshot on an earlier validation/workspace refusal. TS owns the - # mapping to settlement failure kinds; prose carries no such rule. - "quota_rejection_action": before.get("effective_action") if before.get("ok") is True else None, - "before": before, - "after": None, - } - before_quota = cast(dict[str, Any], before.get("quota")) if isinstance(before.get("quota"), dict) else {} - if not before_quota: - return { - "ok": False, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "reason": "goal has no quota payload to preview", - "before": before, - "after": None, - } - - queue_item = _queue_item_for_goal(status_payload, goal_id=safe_goal_id) - after_status = deepcopy(status_payload) - after_goal = { - "quota": { - **before_quota, - "spent_slots": _int_number(before_quota.get("spent_slots"), default=0) + safe_slots, - } - } - after_quota = quota_status_builder( - after_goal, - waiting_on=str(before.get("waiting_on") or ""), - severity=str(queue_item.get("severity") or ""), - lifecycle_phase=before.get("lifecycle_phase") or queue_item.get("lifecycle_phase"), - lifecycle_flags=before.get("lifecycle_flags") or queue_item.get("lifecycle_flags"), - status=before.get("status") or queue_item.get("status"), + return preview_failure_payload( + goal_id=safe_goal_id, + slots=safe_slots, + agent_id=safe_requested_agent_id, + reason=( + before.get("reason") + or "goal is not eligible for quota accounting preview" + ), + before=before, + extra={ + # Transport the actual rejecting action, not an incidental quota + # snapshot on an earlier validation/workspace refusal. TS owns the + # mapping to settlement failure kinds; prose carries no such rule. + "quota_rejection_action": ( + before.get("effective_action") + if before.get("ok") is True + else None + ), + }, + ) + raw_before_quota = before.get("quota") + before_quota = ( + cast(dict[str, object], raw_before_quota) + if isinstance(raw_before_quota, dict) + else {} ) - _set_quota_for_goal(after_status, goal_id=safe_goal_id, quota=after_quota) - after = after_decision(after_status) - - return { - "ok": True, - "mode": "spend-slot", - "dry_run": True, - "goal_id": safe_goal_id, - "slots": safe_slots, - "agent_id": safe_requested_agent_id, - "appended": False, - "registry_mutated": False, - "before": before, - "after": after, - "would_throttle": after.get("state") == "throttled", - "reason": ( - f"dry-run preview: spending {safe_slots} slot(s) accounts for latest " - f"validated delivery {delivery_completion_run.get('classification')} " - f"after current {before.get('state')} guard" - if delivery_completion_spend and delivery_completion_run - else ( - f"dry-run preview: spending {safe_slots} slot(s) would move " - f"{safe_goal_id} from {before.get('state')} to {after.get('state')}" - ) - ), - "accounting_projection": { - "schema_version": "quota_slot_accounting_projection_v0", - "settlement_event_semantics": "append_only", - "spent_slots_semantics": "rolling_window_aggregate", - "before_after_semantics": "same_status_payload_projection", - "window_hours": _int_number(before_quota.get("window_hours"), default=0), - }, - "rolling_window_note": ( - "before -> after is a same-status-payload projection. Later quota status " - "recomputes spent_slots from quota_slot_spent events still inside window_hours, " - "so the visible total can stay flat or decrease as older spends expire; that " - "does not replay or undo the appended settlement event." - ), - "todo_id": normalized_todo_id, - "replan_obligation_id": normalized_replan_obligation_id, - "turn_instance_id": ( - settlement_identity.turn_instance_id - if settlement_identity is not None - else None - ), - "settlement_identity": ( - settlement_identity.as_dict() - if settlement_identity is not None - else None - ), - "settlement_result": ( - settlement_result_payload(settlement_result) - if settlement_result is not None - else None - ), - "safe_bypass_spend": safe_bypass_spend, - "self_repair_spend": self_repair_spend, - "capability_repair_spend": capability_repair_spend, - "delivery_completion_spend": delivery_completion_spend, - "delivery_run_generated_at": delivery_completion_run.get("generated_at") - if delivery_completion_run - else None, - "delivery_run_classification": delivery_completion_run.get("classification") - if delivery_completion_run - else None, - "delivery_run_agent_id": normalize_todo_claimed_by(delivery_completion_run.get("agent_id")) - if delivery_completion_run - else None, - "delivery_run_recommended_action": delivery_completion_run.get("recommended_action") - if delivery_completion_run - else None, - "delivery_workspace": delivery_workspace, - "delivery_workspace_causality": delivery_workspace_causality, - "settlement_workspace_requirement": settlement_workspace_requirement, - "delivery_workspace_validated": delivery_workspace_validated, - } + if not before_quota: + return preview_failure_payload( + goal_id=safe_goal_id, + slots=safe_slots, + agent_id=safe_requested_agent_id, + reason="goal has no quota payload to preview", + before=before, + ) + return build_preview_success_payload( + status_payload, + goal_id=safe_goal_id, + slots=safe_slots, + agent_id=safe_requested_agent_id, + before=before, + before_quota=before_quota, + after_decision=after_decision, + quota_status_builder=quota_status_builder, + todo_id=normalized_todo_id, + replan_obligation_id=normalized_replan_obligation_id, + settlement_identity=settlement_identity, + settlement_result=settlement_result, + delivery_completion_run=delivery_completion_run, + workspace_state=workspace_state, + safe_bypass_spend=safe_bypass_spend, + self_repair_spend=self_repair_spend, + capability_repair_spend=capability_repair_spend, + delivery_completion_spend=delivery_completion_spend, + ) + + +__all__ = [ + "DELIVERY_COMPLETION_SPEND_STATES", + "QUOTA_SLOT_SPENT_CLASSIFICATION", + "QUOTA_SLOT_VOIDED_CLASSIFICATION", + "QuotaDecisionBuilder", + "QuotaStatusBuilder", + "TERMINAL_NO_FOLLOWUP_DECISION_STATE", + "_int_number", + "_latest_unspent_turn_settlement_run", + "_validate_goal_id_path_segment", + "build_quota_slot_preview_for_decision", + "build_quota_slot_spend_event", + "build_quota_slot_void_event", + "build_quota_slot_void_preview_for_decision", + "load_quota_event_from_run", + "net_quota_slot_spend", + "quota_slot_contribution", + "record_quota_slot_spend_from_preview", + "record_quota_slot_void_from_preview", +] diff --git a/loopx/control_plane/quota/slot_preview_settlement.py b/loopx/control_plane/quota/slot_preview_settlement.py new file mode 100644 index 0000000000..5bae7852f2 --- /dev/null +++ b/loopx/control_plane/quota/slot_preview_settlement.py @@ -0,0 +1,399 @@ +"""Settlement lookup, binding validation, and run-index helpers for slot previews.""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from dataclasses import dataclass +import json +from pathlib import Path +from typing import TypeAlias, TypeVar, cast + +from ..effect_program import ( + SettlementFailure, + SettlementFailureKind, + SettlementIdentity, + SettlementResult, + SettlementStepKind, +) +from ..todos.contract import ( + normalize_todo_claimed_by, + normalize_todo_id, + normalize_todo_replan_obligation_id, +) +from ..work_items.delivery_outcome import ( + normalize_delivery_outcome, + qualifies_turn_scoped_settlement, +) +from .ledger_readback import ( + QUOTA_SLOT_SPENT_CLASSIFICATION, + QUOTA_SLOT_VOIDED_CLASSIFICATION, +) +from .monitor_poll import QUOTA_MONITOR_POLL_CLASSIFICATION +from .scheduler_ack import QUOTA_SCHEDULER_ACK_CLASSIFICATION +from .settlement import read_heartbeat_settlement +from .settlement_validation import completion_validation_spend_error +from .spend_sources import ( + DEFAULT_SLOT_SPEND_SOURCE, + TURN_SCOPED_SLOT_SPEND_SOURCES, + VISIBLE_GOAL_SLOT_SPEND_SOURCE, +) + +_T = TypeVar("_T") + +PreviewSettlementResult: TypeAlias = ( + SettlementResult[SettlementIdentity] | SettlementResult[dict[str, object]] +) + +DELIVERY_COMPLETION_SPEND_STATES = frozenset( + {"waiting", "focus_wait", "operator_gate", "eligible"} +) +TERMINAL_NO_FOLLOWUP_DECISION_STATE = "terminal_no_followup" + + +@dataclass(frozen=True, slots=True) +class PreviewSettlementResolution: + """Typed settlement readback projection carried across preview admission.""" + + identity: SettlementIdentity | None = None + result: PreviewSettlementResult | None = None + delivery_run: dict[str, object] | None = None + delivery_workspace_causality: dict[str, str] | None = None + reason: str | None = None + writeback_committed: bool = False + spend_committed: bool = False + + +def receipt_committed( + result: SettlementResult[_T] | None, + step_kind: SettlementStepKind, +) -> bool: + """Report whether one settlement step already owns a committed receipt.""" + if result is None or result.failure is not None: + return False + return any( + receipt.step_kind is step_kind and receipt.status == "committed" + for receipt in result.receipts + ) + + +def _dict_or_empty(value: object) -> dict[str, object]: + return cast(dict[str, object], value) if isinstance(value, dict) else {} + + +def todo_binding_error( + *, + source: str, + status_payload: Mapping[str, object], + goal_id: str, + before: Mapping[str, object], + requested_todo_id: str | None, + requested_replan_obligation_id: str | None, + agent_id: str | None, + settlement_identity: SettlementIdentity | None = None, + delivery_run: dict[str, object] | None = None, +) -> str | None: + """Validate that a preview spend stays bound to its Todo or replan identity.""" + selected = _dict_or_empty(before.get("selected_todo")) + status_dict = ( + cast(dict[str, object], status_payload) + if isinstance(status_payload, dict) + else dict(status_payload) + ) + if settlement_identity is not None: + if ( + requested_todo_id != settlement_identity.todo_id + or requested_replan_obligation_id + != settlement_identity.replan_obligation_id + ): + return ( + "quota spend binding does not match the original settlement " + f"identity: expected {settlement_identity.binding_kind}=" + f"{settlement_identity.binding_id}" + ) + return completion_validation_spend_error( + status_dict, + goal_id=goal_id, + todo_id=requested_todo_id, + agent_id=agent_id, + selected_todo=selected, + delivery_run=delivery_run, + ) + selected_todo_id = normalize_todo_id(selected.get("todo_id")) + if requested_todo_id and selected_todo_id and requested_todo_id != selected_todo_id: + return ( + f"quota spend todo binding mismatch: selected todo is " + f"{selected_todo_id} but --todo-id is {requested_todo_id}; " + "complete or update the selected todo first, or record a replan" + ) + if ( + source == DEFAULT_SLOT_SPEND_SOURCE + and before.get("normal_delivery_allowed") is True + and selected_todo_id + and not requested_todo_id + ): + return ( + f"quota spend requires --todo-id {selected_todo_id} for heartbeat " + "delivery so the accounted turn is bound to the selected todo" + ) + return completion_validation_spend_error( + status_dict, + goal_id=goal_id, + todo_id=requested_todo_id, + agent_id=agent_id, + selected_todo=selected, + delivery_run=None, + ) + + +def resolve_preview_settlement( + *, + raw_runtime_root: object, + source: str, + goal_id: str, + agent_id: str | None, + todo_id: str | None, + replan_obligation_id: str | None, + turn_instance_id: str | None, + registry_path: Path | None, + goal_ref: Mapping[str, object] | None, +) -> PreviewSettlementResolution: + """Resolve persisted Turn settlement state for turn-scoped preview spends.""" + if turn_instance_id and source not in TURN_SCOPED_SLOT_SPEND_SOURCES: + failed_result: SettlementResult[SettlementIdentity] = SettlementResult.failed( + kind=SettlementFailureKind.INVALID_IDENTITY, + step_kind=SettlementStepKind.VALIDATION, + reason=( + "turn-scoped settlement is valid only for heartbeat or " + "visible-goal spend" + ), + ) + return PreviewSettlementResolution( + result=failed_result, + reason=cast(SettlementFailure, failed_result.failure).reason, + ) + if turn_instance_id and not raw_runtime_root: + return PreviewSettlementResolution( + reason="status payload does not include runtime_root" + ) + if source not in TURN_SCOPED_SLOT_SPEND_SOURCES or not raw_runtime_root: + return PreviewSettlementResolution() + + runtime_root = Path(str(raw_runtime_root)).expanduser() + readback = read_heartbeat_settlement( + runtime_root, + goal_id=goal_id, + agent_id=agent_id, + todo_id=todo_id, + turn_instance_id=turn_instance_id, + replan_obligation_id=replan_obligation_id, + infer_turn_instance_id=not bool(turn_instance_id), + allow_unbound_binding=( + source == VISIBLE_GOAL_SLOT_SPEND_SOURCE + and not todo_id + and not replan_obligation_id + ), + registry_path=registry_path, + goal_ref=goal_ref, + ) + if readback is None: + return PreviewSettlementResolution() + if ( + isinstance(readback.progress, dict) + and readback.progress.get("closeout_kind") + in {"typed_blocked_writeback_no_spend", "capability_duty_retired_no_spend"} + ): + return PreviewSettlementResolution( + identity=readback.identity.value, + result=readback.settlement, + delivery_run=readback.writeback_run, + reason=( + "this exact capability duty was retired and must not consume a quota slot; " + "reassess the current frontier in a new Turn" + if readback.progress.get("closeout_kind") + == "capability_duty_retired_no_spend" + else "this Turn already closed with an exact typed blocked writeback " + "and must not consume a quota slot; retry the Todo only after " + "its external blocker changes or a bounded backoff" + ), + ) + identity_result = readback.identity + identity = identity_result.value if identity_result.failure is None else None + result: PreviewSettlementResult = ( + readback.delivery if identity is not None else identity_result + ) + return PreviewSettlementResolution( + identity=identity, + result=result, + delivery_run=result.value if result.failure is None and isinstance(result.value, dict) else None, + delivery_workspace_causality=readback.workspace_causality, + reason=result.failure.reason if result.failure is not None else None, + writeback_committed=receipt_committed( + readback.writeback, SettlementStepKind.DURABLE_WRITEBACK + ), + spend_committed=receipt_committed( + readback.spend, SettlementStepKind.QUOTA_SPEND + ), + ) + + +def unbound_visible_goal_settlement_failure( + *, + source: str, + before: Mapping[str, object], + requested_todo_id: str | None, + requested_replan_obligation_id: str | None, + turn_instance_id: str | None, +) -> SettlementResult[SettlementIdentity] | None: + """Reject unbound visible-goal previews when a selected Todo requires binding.""" + if ( + source != VISIBLE_GOAL_SLOT_SPEND_SOURCE + or before.get("normal_delivery_allowed") is not True + ): + return None + selected = _dict_or_empty(before.get("selected_todo")) + selected_todo_id = normalize_todo_id(selected.get("todo_id")) + if not selected_todo_id: + return None + if bool(requested_todo_id) == bool(requested_replan_obligation_id): + reason = ( + "visible Goal settlement requires exactly one todo_id or " + "replan_obligation_id binding" + ) + elif not turn_instance_id: + reason = ( + "visible Goal settlement for selected Todo " + f"{selected_todo_id} requires turn_instance_id from quota should-run; " + "rerun the guard with --begin-turn" + ) + else: + return None + return SettlementResult.failed( + kind=SettlementFailureKind.IDENTITY_MISMATCH, + step_kind=SettlementStepKind.VALIDATION, + reason=reason, + details={ + "source": source, + "selected_todo_id": selected_todo_id, + "requested_todo_id": requested_todo_id, + "requested_replan_obligation_id": requested_replan_obligation_id, + "turn_instance_id": turn_instance_id, + }, + ) + + +def iter_reversed_goal_run_index_records( + runtime_root: Path, + goal_id: str, +) -> Iterator[dict[str, object]]: + """Yield parsed dictionary records from ``runs/index.jsonl`` newest first.""" + index_path = runtime_root / "goals" / goal_id / "runs" / "index.jsonl" + if not index_path.exists(): + return + try: + lines = index_path.read_text(encoding="utf-8").split("\n") + except OSError: + return + for line in reversed(lines): + if not line.strip(): + continue + try: + record: object = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(record, dict): + yield cast(dict[str, object], record) + + +def load_goal_run_index_records( + runtime_root: Path, + goal_id: str, +) -> list[dict[str, object]]: + """Load parsed dictionary records from ``runs/index.jsonl`` in chronological order.""" + return list(reversed(list(iter_reversed_goal_run_index_records(runtime_root, goal_id)))) + + +def is_quota_neutral_state_refresh(run: Mapping[str, object]) -> bool: + """Recognize refresh-state provenance without relying on its classification.""" + if str(run.get("delivery_outcome") or "").strip(): + return False + if str(run.get("classification") or "").strip() == "state_refreshed": + return True + return ( + isinstance(run.get("state"), dict) + and isinstance(run.get("runtime_projection_route"), dict) + and bool(str(run.get("recommended_action_source") or "").strip()) + ) + + +def select_latest_unspent_turn_settlement_run( + runtime_root: Path, + goal_id: str, + *, + agent_id: str | None = None, + goal_ref: Mapping[str, object] | None = None, +) -> dict[str, object] | None: + """Return the latest same-agent Turn settlement that still needs accounting.""" + safe_agent_id = normalize_todo_claimed_by(agent_id) + expected_goal_ref = dict(goal_ref) if goal_ref is not None else None + for run in iter_reversed_goal_run_index_records(runtime_root, goal_id): + if expected_goal_ref is None and "goal_ref" in run: + continue + if expected_goal_ref is not None and run.get("goal_ref") != expected_goal_ref: + continue + run_agent_id = normalize_todo_claimed_by(run.get("agent_id")) + if safe_agent_id and run_agent_id and safe_agent_id != run_agent_id: + continue + classification = str(run.get("classification") or "").strip() + if classification == QUOTA_SLOT_VOIDED_CLASSIFICATION: + continue + if classification == QUOTA_SLOT_SPENT_CLASSIFICATION: + return None + if ( + classification == QUOTA_MONITOR_POLL_CLASSIFICATION + and run.get("material_change") is not True + ): + continue + if classification == QUOTA_SCHEDULER_ACK_CLASSIFICATION: + continue + if is_quota_neutral_state_refresh(run): + continue + delivery_outcome = normalize_delivery_outcome(run.get("delivery_outcome")) + raw_progress = run.get("progress_observation") + progress_observation = ( + cast(dict[str, object], raw_progress) + if isinstance(raw_progress, dict) + else None + ) + if qualifies_turn_scoped_settlement( + delivery_outcome, + progress_observation, + work_item_id=normalize_todo_id(run.get("todo_id")), + replan_obligation_id=normalize_todo_replan_obligation_id( + run.get("replan_obligation_id") + ), + ): + return run + return None + return None + + +def admits_delivery_completion_spend_state( + *, + before: Mapping[str, object], + identity: SettlementIdentity | None, + settlement: PreviewSettlementResolution, +) -> bool: + """Admit the decision states one delivery-completion spend may settle from.""" + from ..effect_program import SettlementBindingKind + + state = str(before.get("state") or "") + if state in DELIVERY_COMPLETION_SPEND_STATES: + return True + if state != TERMINAL_NO_FOLLOWUP_DECISION_STATE: + return False + return ( + identity is not None + and identity.binding_kind is SettlementBindingKind.AUTONOMOUS_REPLAN + and settlement.writeback_committed is True + and settlement.spend_committed is not True + ) diff --git a/loopx/control_plane/quota/slot_preview_workspace.py b/loopx/control_plane/quota/slot_preview_workspace.py new file mode 100644 index 0000000000..26a607163a --- /dev/null +++ b/loopx/control_plane/quota/slot_preview_workspace.py @@ -0,0 +1,520 @@ +"""Workspace gating, status projection, and preview payloads for slot accounting.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from copy import deepcopy +from dataclasses import dataclass +from pathlib import Path +from typing import Protocol, cast + +from ..agents.workspace_guard import ( + build_delivery_workspace_guard, + delivery_workspace_identity, +) +from ..effect_program import ( + SettlementFailure, + SettlementIdentity, + SettlementReceipt, + settlement_result_payload, +) +from ..todos.contract import normalize_todo_claimed_by +from .effective_action import EffectiveAction +from .ledger_readback import _int_number +from .settlement_workspace_causality import ( + LEGACY_SETTLEMENT_RECEIPT_EVIDENCE_SCHEMA_VERSION, + completed_todo_workspace_causality, + missing_delivery_workspace_resolution, + resolve_settlement_workspace_requirement, +) +from .slot_preview_settlement import PreviewSettlementResult + + +class _SettlementReceiptCarrier(Protocol): + @property + def failure(self) -> SettlementFailure | None: ... + + @property + def receipts(self) -> tuple[SettlementReceipt, ...]: ... + + +@dataclass(frozen=True, slots=True) +class DeliveryWorkspacePreviewState: + """Evaluated workspace gating and causality metadata for one preview.""" + + delivery_workspace: dict[str, object] | None = None + delivery_workspace_causality: dict[str, str] | None = None + settlement_workspace_requirement: dict[str, str] | None = None + delivery_workspace_validated: bool = False + failure_preview: dict[str, object] | None = None + + +def preview_failure_payload( + *, + goal_id: str, + slots: int, + agent_id: str | None, + reason: object, + before: Mapping[str, object], + extra: Mapping[str, object] | None = None, +) -> dict[str, object]: + """Construct one normalized dry-run spend failure preview payload.""" + payload: dict[str, object] = { + "ok": False, + "mode": "spend-slot", + "dry_run": True, + "goal_id": goal_id, + "slots": slots, + "agent_id": agent_id, + "appended": False, + "registry_mutated": False, + "reason": reason, + "before": before, + "after": None, + } + if extra: + payload.update(extra) + return payload + + +def repair_settlement_workspace_causality( + status_payload: Mapping[str, object], + *, + goal_id: str, + settlement_identity: SettlementIdentity | None, + causality: dict[str, str] | None, +) -> dict[str, str] | None: + """Recover workspace causality from a completed Todo contract when unknown.""" + requirement = str((causality or {}).get("requirement") or "") + if settlement_identity is None or requirement not in {"", "unknown"}: + return causality + repaired = completed_todo_workspace_causality( + status_payload, + goal_id=goal_id, + todo_id=settlement_identity.todo_id, + source=( + "current_todo_contract_repair" + if requirement == "unknown" + else "completed_todo_contract_fallback" + ), + ) + if str((repaired or {}).get("requirement") or "") == "unknown": + return causality + return repaired or causality + + +def settlement_workspace_requirement( + delivery_workspace_causality: dict[str, str] | None, + settlement_identity: SettlementIdentity | None, + settlement_result: _SettlementReceiptCarrier | None, + delivery_completion_run: Mapping[str, object] | None, +) -> dict[str, str] | None: + """Resolve the TypeScript-owned workspace requirement for a settled turn.""" + if settlement_identity is None: + return None + legacy_evidence: dict[str, object] | None = ( + { + "schema_version": LEGACY_SETTLEMENT_RECEIPT_EVIDENCE_SCHEMA_VERSION, + "settlement_effect_id": settlement_identity.effect_id, + "delivery_workspace_present": bool( + isinstance(delivery_completion_run, Mapping) + and delivery_completion_run.get("delivery_workspace") is not None + ), + "receipts": [ + { + "step_kind": receipt.step_kind.value, + "status": receipt.status, + "effect_id": receipt.effect_id, + } + for receipt in settlement_result.receipts + ], + } + if settlement_result is not None and settlement_result.failure is None + else None + ) + return resolve_settlement_workspace_requirement( + delivery_workspace_causality, + settlement_binding_kind=settlement_identity.binding_kind.value, + legacy_settlement_evidence=legacy_evidence, + ) + + +def workspace_requirement_value( + requirement_payload: Mapping[str, object] | None, + delivery_workspace_causality: Mapping[str, object] | None, +) -> str: + """Extract the effective requirement string from workspace causality payloads.""" + return str( + (requirement_payload or {}).get("requirement") + or (delivery_workspace_causality or {}).get("requirement") + or "" + ) + + +def missing_delivery_workspace_preview( + *, + delivery_workspace_causality: dict[str, str] | None, + requirement_payload: dict[str, str] | None, + delivery_workspace: dict[str, object] | None, + goal_id: str, + slots: int, + agent_id: str | None, + before: Mapping[str, object], +) -> dict[str, object] | None: + """Return a failure preview when a required delivery workspace snapshot is missing.""" + if delivery_workspace_identity(delivery_workspace): + return None + requirement = workspace_requirement_value( + requirement_payload, delivery_workspace_causality + ) + if not requirement or requirement == "not_required": + return None + resolution = missing_delivery_workspace_resolution(delivery_workspace_causality) + if resolution is not None and resolution["decision"] == "omit_snapshot": + return None + reason = ( + "quota spend requires a valid delivery workspace snapshot for " + f"settlement causality requirement {requirement}" + if resolution is not None and resolution["decision"] == "require_snapshot" + else ( + "quota spend requires an explicit Todo delivery contract; declare " + "repository/write requirements or mark the Todo as explicit " + "non-delivery, then retry the same settlement" + ) + ) + return preview_failure_payload( + goal_id=goal_id, + slots=slots, + agent_id=agent_id, + reason=reason, + before=before, + extra={ + "delivery_workspace": delivery_workspace, + "delivery_workspace_causality": delivery_workspace_causality, + "settlement_workspace_requirement": requirement_payload, + "delivery_workspace_resolution": resolution, + "delivery_workspace_validated": False, + }, + ) + + +def workspace_repair_blocks_spend( + before: Mapping[str, object], + *, + delivery_workspace_validated: bool, + delivery_run: Mapping[str, object] | None, + settlement_identity: SettlementIdentity | None, + workspace_requirement: str, +) -> bool: + """Keep the current workspace guard separate from an original settlement.""" + settlement_does_not_require_workspace = ( + delivery_run is not None + and settlement_identity is not None + and workspace_requirement == "not_required" + ) + return ( + before.get("effective_action") == EffectiveAction.AGENT_WORKSPACE_REPAIR.value + and before.get("workspace_repair_allowed") is True + and not delivery_workspace_validated + and not settlement_does_not_require_workspace + ) + + +def evaluate_delivery_workspace_preview( + status_payload: Mapping[str, object], + *, + goal_id: str, + slots: int, + agent_id: str | None, + workspace_path: Path | None, + before: Mapping[str, object], + settlement_identity: SettlementIdentity | None, + settlement_result: _SettlementReceiptCarrier | None, + causality: dict[str, str] | None, + delivery_completion_run: dict[str, object] | None, + safe_bypass_requested: bool, +) -> DeliveryWorkspacePreviewState: + """Evaluate workspace causality, snapshot sufficiency, and workspace guards.""" + delivery_workspace_causality = repair_settlement_workspace_causality( + status_payload, + goal_id=goal_id, + settlement_identity=settlement_identity, + causality=causality, + ) + requirement_payload = settlement_workspace_requirement( + delivery_workspace_causality, + settlement_identity, + settlement_result, + delivery_completion_run, + ) + if safe_bypass_requested and delivery_completion_run is None: + return DeliveryWorkspacePreviewState( + failure_preview=preview_failure_payload( + goal_id=goal_id, + slots=slots, + agent_id=agent_id, + reason=( + "safe-bypass quota spend requires a latest " + "unspent Turn settlement writeback" + ), + before=before, + ) + ) + raw_workspace_obj = ( + delivery_completion_run.get("delivery_workspace") + if isinstance(delivery_completion_run, dict) + else None + ) + raw_delivery_workspace = ( + cast(dict[str, object], raw_workspace_obj) + if isinstance(raw_workspace_obj, dict) + else None + ) + missing_preview = missing_delivery_workspace_preview( + delivery_workspace_causality=delivery_workspace_causality, + requirement_payload=requirement_payload, + delivery_workspace=raw_delivery_workspace, + goal_id=goal_id, + slots=slots, + agent_id=agent_id, + before=before, + ) + if missing_preview: + return DeliveryWorkspacePreviewState(failure_preview=missing_preview) + requirement_value = workspace_requirement_value( + requirement_payload, delivery_workspace_causality + ) + delivery_workspace = ( + raw_delivery_workspace + if delivery_workspace_identity(raw_delivery_workspace) + and requirement_value != "not_required" + else None + ) + delivery_workspace_guard = ( + build_delivery_workspace_guard( + delivery_completion_run, + agent_id=agent_id, + current_path=workspace_path, + ) + if delivery_completion_run and delivery_workspace + else None + ) + if delivery_workspace_guard: + return DeliveryWorkspacePreviewState( + failure_preview=preview_failure_payload( + goal_id=goal_id, + slots=slots, + agent_id=agent_id, + reason=delivery_workspace_guard["reason"], + before=before, + extra={ + "workspace_guard": delivery_workspace_guard, + "delivery_workspace": delivery_workspace, + "delivery_workspace_causality": delivery_workspace_causality, + "delivery_workspace_validated": False, + }, + ) + ) + delivery_workspace_validated = bool(delivery_workspace) + if workspace_repair_blocks_spend( + before, + delivery_workspace_validated=delivery_workspace_validated, + delivery_run=delivery_completion_run, + settlement_identity=settlement_identity, + workspace_requirement=requirement_value, + ): + return DeliveryWorkspacePreviewState( + failure_preview=preview_failure_payload( + goal_id=goal_id, + slots=slots, + agent_id=agent_id, + reason=( + "agent workspace guard requires moving to an independent " + "worktree and rerunning quota should-run before quota spend" + ), + before=before, + extra={ + "delivery_workspace": delivery_workspace, + "delivery_workspace_causality": delivery_workspace_causality, + "delivery_workspace_validated": False, + }, + ) + ) + return DeliveryWorkspacePreviewState( + delivery_workspace=delivery_workspace, + delivery_workspace_causality=delivery_workspace_causality, + settlement_workspace_requirement=requirement_payload, + delivery_workspace_validated=delivery_workspace_validated, + ) + + +def queue_item_for_goal( + status_payload: Mapping[str, object], + *, + goal_id: str, +) -> dict[str, object]: + """Return the attention-queue item matching ``goal_id``, or an empty dict.""" + queue = status_payload.get("attention_queue") + if not isinstance(queue, dict): + return {} + queue_items = queue.get("items") + if not isinstance(queue_items, list): + return {} + for item in queue_items: + if isinstance(item, dict) and str(item.get("goal_id") or "") == goal_id: + return cast(dict[str, object], item) + return {} + + +def set_quota_for_goal( + status_payload: dict[str, object], + *, + goal_id: str, + quota: Mapping[str, object], +) -> None: + """Overwrite a Goal's projected quota snapshot in both history and queue entries.""" + run_history = status_payload.get("run_history") + if isinstance(run_history, dict): + run_goals = run_history.get("goals") + if isinstance(run_goals, list): + for goal in run_goals: + if isinstance(goal, dict) and str(goal.get("id") or "") == goal_id: + goal["quota"] = dict(quota) + + queue = status_payload.get("attention_queue") + if isinstance(queue, dict): + queue_items = queue.get("items") + if isinstance(queue_items, list): + for item in queue_items: + if isinstance(item, dict) and str(item.get("goal_id") or "") == goal_id: + item["quota"] = dict(quota) + project_asset = item.get("project_asset") + if isinstance(project_asset, dict) and project_asset: + project_asset["quota"] = dict(quota) + + +def build_preview_success_payload( + status_payload: Mapping[str, object], + *, + goal_id: str, + slots: int, + agent_id: str | None, + before: Mapping[str, object], + before_quota: Mapping[str, object], + after_decision: Callable[[dict[str, object]], dict[str, object]], + quota_status_builder: Callable[..., dict[str, object]], + todo_id: str | None, + replan_obligation_id: str | None, + settlement_identity: SettlementIdentity | None, + settlement_result: PreviewSettlementResult | None, + delivery_completion_run: Mapping[str, object] | None, + workspace_state: DeliveryWorkspacePreviewState, + safe_bypass_spend: bool, + self_repair_spend: bool, + capability_repair_spend: bool, + delivery_completion_spend: bool, +) -> dict[str, object]: + """Project before -> after quota status and build the admitted spend preview.""" + queue_item = queue_item_for_goal(status_payload, goal_id=goal_id) + after_status = deepcopy(dict(status_payload)) + after_goal: dict[str, object] = { + "quota": { + **before_quota, + "spent_slots": _int_number(before_quota.get("spent_slots"), default=0) + + slots, + } + } + after_quota = quota_status_builder( + after_goal, + waiting_on=str(before.get("waiting_on") or ""), + severity=str(queue_item.get("severity") or ""), + lifecycle_phase=before.get("lifecycle_phase") or queue_item.get("lifecycle_phase"), + lifecycle_flags=before.get("lifecycle_flags") or queue_item.get("lifecycle_flags"), + status=before.get("status") or queue_item.get("status"), + ) + set_quota_for_goal(after_status, goal_id=goal_id, quota=after_quota) + after = after_decision(after_status) + + return { + "ok": True, + "mode": "spend-slot", + "dry_run": True, + "goal_id": goal_id, + "slots": slots, + "agent_id": agent_id, + "appended": False, + "registry_mutated": False, + "before": before, + "after": after, + "would_throttle": after.get("state") == "throttled", + "reason": ( + f"dry-run preview: spending {slots} slot(s) accounts for latest " + f"validated delivery {delivery_completion_run.get('classification')} " + f"after current {before.get('state')} guard" + if delivery_completion_spend and delivery_completion_run + else ( + f"dry-run preview: spending {slots} slot(s) would move " + f"{goal_id} from {before.get('state')} to {after.get('state')}" + ) + ), + "accounting_projection": { + "schema_version": "quota_slot_accounting_projection_v0", + "settlement_event_semantics": "append_only", + "spent_slots_semantics": "rolling_window_aggregate", + "before_after_semantics": "same_status_payload_projection", + "window_hours": _int_number(before_quota.get("window_hours"), default=0), + }, + "rolling_window_note": ( + "before -> after is a same-status-payload projection. Later quota status " + "recomputes spent_slots from quota_slot_spent events still inside window_hours, " + "so the visible total can stay flat or decrease as older spends expire; that " + "does not replay or undo the appended settlement event." + ), + "todo_id": todo_id, + "replan_obligation_id": replan_obligation_id, + "turn_instance_id": ( + settlement_identity.turn_instance_id + if settlement_identity is not None + else None + ), + "settlement_identity": ( + settlement_identity.as_dict() + if settlement_identity is not None + else None + ), + "settlement_result": ( + settlement_result_payload(settlement_result) + if settlement_result is not None + else None + ), + "safe_bypass_spend": safe_bypass_spend, + "self_repair_spend": self_repair_spend, + "capability_repair_spend": capability_repair_spend, + "delivery_completion_spend": delivery_completion_spend, + "delivery_run_generated_at": ( + delivery_completion_run.get("generated_at") + if delivery_completion_run + else None + ), + "delivery_run_classification": ( + delivery_completion_run.get("classification") + if delivery_completion_run + else None + ), + "delivery_run_agent_id": ( + normalize_todo_claimed_by(delivery_completion_run.get("agent_id")) + if delivery_completion_run + else None + ), + "delivery_run_recommended_action": ( + delivery_completion_run.get("recommended_action") + if delivery_completion_run + else None + ), + "delivery_workspace": workspace_state.delivery_workspace, + "delivery_workspace_causality": workspace_state.delivery_workspace_causality, + "settlement_workspace_requirement": ( + workspace_state.settlement_workspace_requirement + ), + "delivery_workspace_validated": workspace_state.delivery_workspace_validated, + } diff --git a/tests/control_plane/test_slot_accounting_contract.py b/tests/control_plane/test_slot_accounting_contract.py new file mode 100644 index 0000000000..07663daeb6 --- /dev/null +++ b/tests/control_plane/test_slot_accounting_contract.py @@ -0,0 +1,618 @@ +"""Contract, edge-case, and boundary tests for slot accounting modularization.""" + +from __future__ import annotations + +import ast +import io +import json +from pathlib import Path +import tokenize + +import pytest + +from loopx import paths +from loopx.canary.maintainability_ratchet import ( + DECISION_POINT_LIMIT, + DECISION_STATEMENT_LIMIT, + _FunctionMetrics, + _iter_functions, +) +from loopx.control_plane.effect_program import ( + SettlementIdentity, + SettlementReceipt, + SettlementResult, + SettlementStepKind, +) +from loopx.control_plane.quota import ( + ledger_readback, + slot_accounting, + slot_preview_settlement, + slot_preview_workspace, + spend_commit, + void_commit, +) +from loopx.control_plane.quota.settlement import QuotaSettlementReadback + +REPO_ROOT = Path(__file__).resolve().parents[2] +GOAL_ID = "slot-accounting-contract-fixture" +AGENT_ID = "codex-peer-a" + +COMMON_FAILURE_KEYS = { + "ok", + "mode", + "dry_run", + "goal_id", + "slots", + "agent_id", + "appended", + "registry_mutated", + "reason", + "before", + "after", +} + + +def _comment_ignore_or_noqa_count(source: str) -> int: + tokens = tokenize.generate_tokens(io.StringIO(source).readline) + return sum( + 1 + for tok in tokens + if tok.type == tokenize.COMMENT + and ("type: ignore" in tok.string or "noqa" in tok.string) + ) + + +def _ast_any_count(source: str) -> int: + tree = ast.parse(source) + return sum( + 1 + for node in ast.walk(tree) + if (isinstance(node, ast.Name) and node.id == "Any") + or (isinstance(node, ast.Attribute) and node.attr == "Any") + or ( + isinstance(node, ast.ImportFrom) + and any(alias.name == "Any" for alias in node.names) + ) + ) + + +def _quota_block(*, spent_slots: int = 0) -> dict[str, object]: + return { + "compute": 1.0, + "window_hours": 24, + "slot_minutes": 1, + "spent_slots": spent_slots, + "allowed_slots": 100, + } + + +def _before_decision( + *, + ok: bool = True, + should_run: bool = False, + state: str = "eligible", + effective_action: str = "monitor_quiet_skip", + selected_todo_id: str | None = None, + normal_delivery_allowed: bool = False, + safe_bypass_allowed: bool = False, + workspace_repair_allowed: bool = False, + quota: dict[str, object] | None = None, + reason: str = "contract fixture", +) -> dict[str, object]: + payload: dict[str, object] = { + "ok": ok, + "goal_id": GOAL_ID, + "should_run": should_run, + "state": state, + "effective_action": effective_action, + "normal_delivery_allowed": normal_delivery_allowed, + "safe_bypass_allowed": safe_bypass_allowed, + "workspace_repair_allowed": workspace_repair_allowed, + "reason": reason, + "quota": _quota_block() if quota is None else quota, + } + if selected_todo_id is not None: + payload["selected_todo"] = {"todo_id": selected_todo_id} + return payload + + +def _make_readback( + *, + identity: SettlementIdentity, + closeout_kind: str | None = None, + writeback_committed: bool = True, + spend_committed: bool = False, + workspace_causality: dict[str, str] | None = None, + delivery_run: dict[str, object] | None = None, +) -> QuotaSettlementReadback: + writeback_receipts = ( + ( + SettlementReceipt( + step_kind=SettlementStepKind.DURABLE_WRITEBACK, + status="committed", + effect_id=identity.effect_id, + ), + ) + if writeback_committed + else () + ) + spend_receipts = ( + ( + SettlementReceipt( + step_kind=SettlementStepKind.QUOTA_SPEND, + status="committed", + effect_id=identity.effect_id, + ), + ) + if spend_committed + else () + ) + run_payload: dict[str, object] = delivery_run or { + "generated_at": "2026-01-01T00:01:00+00:00", + "classification": "validated_delivery_fixture", + "delivery_outcome": "outcome_progress", + "agent_id": AGENT_ID, + "recommended_action": "continue", + } + empty_dict: dict[str, object] = {} + return QuotaSettlementReadback( + identity=SettlementResult.pure(identity), + writeback=SettlementResult.pure(empty_dict, receipts=writeback_receipts), + spend=SettlementResult.pure(empty_dict, receipts=spend_receipts), + delivery=SettlementResult.pure(run_payload, receipts=writeback_receipts), + settlement=SettlementResult.pure(empty_dict), + terminal_closeout=SettlementResult.pure(empty_dict), + terminal_settlement=SettlementResult.pure(empty_dict), + workspace_causality=workspace_causality, + semantic_replan_guard=None, + writeback_run=run_payload, + spend_run=None, + heartbeat_receipt=None, + writeback_event=None, + spend_event=None, + completion_event=None, + monitor_phase=None, + replay_phase=None, + progress={"closeout_kind": closeout_kind} if closeout_kind else None, + ) + + +def test_slot_accounting_modules_meet_zero_any_size_and_identity_contracts() -> None: + prod_paths = ( + REPO_ROOT / "loopx" / "control_plane" / "quota" / "slot_accounting.py", + REPO_ROOT / "loopx" / "control_plane" / "quota" / "slot_preview_settlement.py", + REPO_ROOT / "loopx" / "control_plane" / "quota" / "slot_preview_workspace.py", + ) + for path in (*prod_paths, Path(__file__)): + source = path.read_text(encoding="utf-8") + assert _ast_any_count(source) == 0, path + assert _comment_ignore_or_noqa_count(source) == 0, path + assert len(prod_paths[0].read_text(encoding="utf-8").splitlines()) <= 600 + for path in prod_paths[1:]: + assert len(path.read_text(encoding="utf-8").splitlines()) < 750 + for path in prod_paths: + tree = ast.parse(path.read_text(encoding="utf-8")) + for qname, fn in _iter_functions(tree.body): + metrics = _FunctionMetrics(fn) + metrics.visit(fn) + assert metrics.statement_count <= DECISION_STATEMENT_LIMIT, (path, qname) + assert metrics.decision_points <= DECISION_POINT_LIMIT, (path, qname) + + assert slot_accounting._validate_goal_id_path_segment is paths.validate_goal_id_path_segment + for name in ( + "QUOTA_SLOT_SPENT_CLASSIFICATION", + "QUOTA_SLOT_VOIDED_CLASSIFICATION", + "load_quota_event_from_run", + "net_quota_slot_spend", + "quota_slot_contribution", + ): + assert getattr(slot_accounting, name) is getattr(ledger_readback, name), name + for name in ("build_quota_slot_spend_event", "record_quota_slot_spend_from_preview"): + assert getattr(slot_accounting, name) is getattr(spend_commit, name), name + for name in ( + "build_quota_slot_void_event", + "build_quota_slot_void_preview_for_decision", + "record_quota_slot_void_from_preview", + ): + assert getattr(slot_accounting, name) is getattr(void_commit, name), name + + +@pytest.mark.parametrize("bad_goal_id", ["", "../escape", "nested/goal", "."]) +def test_invalid_goal_id_fails_closed_before_preview_work(bad_goal_id: str) -> None: + def fail_after(_: dict[str, object]) -> dict[str, object]: + pytest.fail("after_decision must not execute for invalid goal_id") + + def fail_quota(*_args: object, **_kwargs: object) -> dict[str, object]: + pytest.fail("quota_status_builder must not execute for invalid goal_id") + + with pytest.raises(ValueError, match="goal id"): + slot_accounting.build_quota_slot_preview_for_decision( + {}, + goal_id=bad_goal_id, + before=_before_decision(), + after_decision=fail_after, + quota_status_builder=fail_quota, + self_repair_spend_actions=frozenset(), + ) + + +def test_refusal_branches_preserve_exact_key_presence_vs_none( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail_after(_: dict[str, object]) -> dict[str, object]: + pytest.fail("after_decision must not run on refusal") + + def fail_quota(*_args: object, **_kwargs: object) -> dict[str, object]: + pytest.fail("quota_status_builder must not run on refusal") + + # 1. Unbound visible goal refusal includes settlement_result & workspace=None. + unbound = slot_accounting.build_quota_slot_preview_for_decision( + {}, + goal_id=GOAL_ID, + source="visible-goal", + before=_before_decision(normal_delivery_allowed=True, selected_todo_id="todo_alpha"), + after_decision=fail_after, + quota_status_builder=fail_quota, + self_repair_spend_actions=frozenset(), + agent_id=AGENT_ID, + ) + assert set(unbound) == COMMON_FAILURE_KEYS | { + "settlement_result", "delivery_workspace", "delivery_workspace_causality", "delivery_workspace_validated", + } + assert "quota_rejection_action" not in unbound + + # 2. Settlement reason refusal from non-turn-scoped turn_instance_id. + bad_source_turn = slot_accounting.build_quota_slot_preview_for_decision( + {}, goal_id=GOAL_ID, source="adapter", turn_instance_id="turn-1", + before=_before_decision(), after_decision=fail_after, + quota_status_builder=fail_quota, self_repair_spend_actions=frozenset(), + ) + assert set(bad_source_turn) == COMMON_FAILURE_KEYS | {"settlement_result"} + assert bad_source_turn["settlement_result"] is not None + + # 3. Settlement reason refusal when runtime_root is omitted for turn_instance_id. + missing_root = slot_accounting.build_quota_slot_preview_for_decision( + {}, goal_id=GOAL_ID, source="heartbeat", turn_instance_id="turn-1", + before=_before_decision(), after_decision=fail_after, + quota_status_builder=fail_quota, self_repair_spend_actions=frozenset(), + ) + assert set(missing_root) == COMMON_FAILURE_KEYS | {"settlement_result"} + assert missing_root["settlement_result"] is None + + # 4. Binding refusal has exact 11 keys (no settlement_result or quota_rejection_action). + binding_refusal = slot_accounting.build_quota_slot_preview_for_decision( + {}, goal_id=GOAL_ID, source="adapter", todo_id="todo_req", + before=_before_decision(selected_todo_id="todo_other"), + after_decision=fail_after, quota_status_builder=fail_quota, self_repair_spend_actions=frozenset(), + ) + assert set(binding_refusal) == COMMON_FAILURE_KEYS + + # 5. Safe-bypass without unspent turn settlement writeback has exact 11 keys. + safe_bypass_missing = slot_accounting.build_quota_slot_preview_for_decision( + {"runtime_root": str(tmp_path)}, goal_id=GOAL_ID, source="adapter", + before=_before_decision(state="operator_gate", safe_bypass_allowed=True), + after_decision=fail_after, quota_status_builder=fail_quota, self_repair_spend_actions=frozenset(), + ) + assert set(safe_bypass_missing) == COMMON_FAILURE_KEYS + + # 6. Admission refusal sets quota_rejection_action=None if before.ok is False. + not_ok_refusal = slot_accounting.build_quota_slot_preview_for_decision( + {}, goal_id=GOAL_ID, source="adapter", + before=_before_decision(ok=False, effective_action="throttled_skip"), + after_decision=fail_after, quota_status_builder=fail_quota, self_repair_spend_actions=frozenset(), + ) + assert set(not_ok_refusal) == COMMON_FAILURE_KEYS | {"quota_rejection_action"} + assert not_ok_refusal["quota_rejection_action"] is None + + # 7. Admission refusal transports effective_action when before.ok is True. + throttled_refusal = slot_accounting.build_quota_slot_preview_for_decision( + {}, goal_id=GOAL_ID, source="adapter", + before=_before_decision(ok=True, should_run=False, effective_action="throttled_skip"), + after_decision=fail_after, quota_status_builder=fail_quota, self_repair_spend_actions=frozenset(), + ) + assert set(throttled_refusal) == COMMON_FAILURE_KEYS | {"quota_rejection_action"} + assert throttled_refusal["quota_rejection_action"] == "throttled_skip" + + # 8. Empty quota payload refusal has exact 11 keys. + no_quota = slot_accounting.build_quota_slot_preview_for_decision( + {}, goal_id=GOAL_ID, source="adapter", + before=_before_decision(should_run=True, quota={}), + after_decision=fail_after, quota_status_builder=fail_quota, self_repair_spend_actions=frozenset(), + ) + assert set(no_quota) == COMMON_FAILURE_KEYS + assert no_quota["reason"] == "goal has no quota payload to preview" + + # 9. Closeout no-spend readback refusals return exact reason strings. + identity = SettlementIdentity( + goal_id=GOAL_ID, agent_id=AGENT_ID, todo_id=None, + replan_obligation_id="replan-0123456789abcdef", turn_instance_id="turn-closeout", + ) + monkeypatch.setattr( + slot_preview_settlement, + "read_heartbeat_settlement", + lambda *_args, **_kwargs: _make_readback( + identity=identity, closeout_kind="capability_duty_retired_no_spend" + ), + ) + retired = slot_accounting.build_quota_slot_preview_for_decision( + {"runtime_root": str(tmp_path)}, goal_id=GOAL_ID, + before=_before_decision(), after_decision=fail_after, + quota_status_builder=fail_quota, self_repair_spend_actions=frozenset(), + agent_id=AGENT_ID, replan_obligation_id="replan-0123456789abcdef", turn_instance_id="turn-closeout", + ) + assert set(retired) == COMMON_FAILURE_KEYS | {"settlement_result"} + assert "capability duty was retired" in str(retired["reason"]) + + +def test_terminal_no_followup_and_workspace_repair_gating( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + replan_id = SettlementIdentity( + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=None, + replan_obligation_id="replan-0123456789abcdef", + turn_instance_id="turn-terminal-replan", + ) + causality = { + "schema_version": "delivery_workspace_causality_v0", + "todo_id": "", + "requirement": "not_required", + "source": "replan_contract", + "reason": "explicit_replan", + } + monkeypatch.setattr( + slot_preview_settlement, + "read_heartbeat_settlement", + lambda *_a, **_k: _make_readback(identity=replan_id, workspace_causality=causality), + ) + before = _before_decision( + state="terminal_no_followup", + effective_action="agent_workspace_repair", + workspace_repair_allowed=True, + ) + preview = slot_accounting.build_quota_slot_preview_for_decision( + {"runtime_root": str(tmp_path)}, + goal_id=GOAL_ID, + before=before, + after_decision=lambda _s: {**before, "quota": _quota_block(spent_slots=1)}, + quota_status_builder=lambda goal, **_k: dict(goal["quota"]), + self_repair_spend_actions=frozenset(), + agent_id=AGENT_ID, + replan_obligation_id="replan-0123456789abcdef", + turn_instance_id="turn-terminal-replan", + ) + assert preview["ok"] is True + assert preview["delivery_completion_spend"] is True + + monkeypatch.setattr( + slot_preview_settlement, + "read_heartbeat_settlement", + lambda *_a, **_k: _make_readback( + identity=replan_id, spend_committed=True, workspace_causality=causality + ), + ) + blocked_spent = slot_accounting.build_quota_slot_preview_for_decision( + {"runtime_root": str(tmp_path)}, + goal_id=GOAL_ID, + before=before, + after_decision=lambda _s: before, + quota_status_builder=lambda goal, **_k: dict(goal["quota"]), + self_repair_spend_actions=frozenset(), + agent_id=AGENT_ID, + replan_obligation_id="replan-0123456789abcdef", + turn_instance_id="turn-terminal-replan", + ) + assert blocked_spent["ok"] is False + assert blocked_spent["quota_rejection_action"] == "agent_workspace_repair" + + todo_id = SettlementIdentity( + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id="todo_ws", + replan_obligation_id=None, + turn_instance_id="turn-ws", + ) + ws_readback = _make_readback( + identity=todo_id, + workspace_causality={**causality, "todo_id": "todo_ws", "source": "todo_contract"}, + ) + repair_before = {"effective_action": "agent_workspace_repair", "workspace_repair_allowed": True} + assert ( + slot_preview_workspace.workspace_repair_blocks_spend( + repair_before, + delivery_workspace_validated=False, + delivery_run=None, + settlement_identity=None, + workspace_requirement="", + ) + is True + ) + assert ( + slot_preview_workspace.workspace_repair_blocks_spend( + repair_before, + delivery_workspace_validated=False, + delivery_run=ws_readback.writeback_run, + settlement_identity=todo_id, + workspace_requirement="not_required", + ) + is False + ) + + +def test_run_index_malformed_lines_isolation_and_lazy_tail_scan( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + runtime = tmp_path / "runtime" + assert slot_accounting._latest_unspent_turn_settlement_run(runtime, GOAL_ID) is None + + index_path = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl" + index_path.parent.mkdir(parents=True, exist_ok=True) + # Historical corrupted/non-dict rows sit at the head; tail contains spend + valid delivery. + older_corrupt = ['"{not-json', "[]", "123", "null", " "] * 20 + delivery = { + "generated_at": "2026-01-01T00:05:00+00:00", + "classification": "validated_delivery_fixture", + "delivery_outcome": "outcome_progress", + "agent_id": AGENT_ID, + } + neutral_rows = [ + {"classification": "quota_slot_voided", "agent_id": AGENT_ID}, + {"classification": "quota_monitor_poll", "material_change": False, "agent_id": AGENT_ID}, + {"classification": "quota_scheduler_ack", "agent_id": AGENT_ID}, + { + "classification": "custom_refresh", + "recommended_action_source": "explicit", + "runtime_projection_route": {}, + "state": {}, + "agent_id": AGENT_ID, + }, + # Scoped goal_ref mismatch must be skipped cleanly. + { + "classification": "quota_slot_spent", + "agent_id": AGENT_ID, + "goal_ref": {"goal_id": GOAL_ID, "goal_instance_id": "inst-other"}, + }, + ] + index_path.write_text( + "\n".join( + [ + *older_corrupt, + json.dumps(delivery), + *[json.dumps(row) for row in neutral_rows], + ] + ) + + "\n", + encoding="utf-8", + ) + + real_loads = json.loads + parse_calls = 0 + + def counting_loads(payload: str) -> object: + nonlocal parse_calls + parse_calls += 1 + return real_loads(payload) + + monkeypatch.setattr(json, "loads", counting_loads) + found = slot_accounting._latest_unspent_turn_settlement_run( + runtime, GOAL_ID, agent_id=AGENT_ID + ) + assert found == delivery + # Tail-first iteration stops at the delivery record without parsing older corrupt prefix rows. + assert parse_calls == len(neutral_rows) + 1 + + # Full chronological loader preserves invalid-line skipping and ordering semantics. + loaded = slot_preview_settlement.load_goal_run_index_records(runtime, GOAL_ID) + assert loaded == [delivery, *neutral_rows] + + # goal_ref exact-instance matching finds only matching goal_ref rows. + assert ( + slot_accounting._latest_unspent_turn_settlement_run( + runtime, + GOAL_ID, + agent_id=AGENT_ID, + goal_ref={"goal_id": GOAL_ID, "goal_instance_id": "inst-other"}, + ) + is None + ) + + # OSError during read fails closed safely. + def raise_oserror(*_args: object, **_kwargs: object) -> str: + raise OSError("unreadable index") + + monkeypatch.setattr(Path, "read_text", raise_oserror) + assert slot_accounting._latest_unspent_turn_settlement_run(runtime, GOAL_ID) is None + + +def test_latest_run_monkeypatch_seam_and_status_mutation_isolation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatched_run = { + "generated_at": "2026-01-01T00:09:00+00:00", + "classification": "monkeypatched_delivery", + "delivery_outcome": "outcome_progress", + "agent_id": AGENT_ID, + "recommended_action": "advance", + } + monkeypatch.setattr( + slot_accounting, + "_latest_unspent_turn_settlement_run", + lambda *_args, **_kwargs: monkeypatched_run, + ) + status_payload: dict[str, object] = { + "runtime_root": str(tmp_path), + "run_history": {"goals": [{"id": GOAL_ID, "quota": _quota_block(spent_slots=1)}]}, + "attention_queue": { + "items": [ + { + "goal_id": GOAL_ID, + "severity": "low", + "status": "active", + "quota": _quota_block(spent_slots=1), + "project_asset": {"quota": _quota_block(spent_slots=1)}, + } + ] + }, + } + captured_after_status: list[dict[str, object]] = [] + before = _before_decision(should_run=True, quota=_quota_block(spent_slots=1)) + + def record_after(mutated_status: dict[str, object]) -> dict[str, object]: + captured_after_status.append(mutated_status) + return {**before, "quota": _quota_block(spent_slots=3), "state": "throttled"} + + def build_after_quota( + goal: dict[str, object], **_kwargs: object + ) -> dict[str, object]: + quota_obj = goal.get("quota") + assert isinstance(quota_obj, dict) + return dict(quota_obj) + + preview = slot_accounting.build_quota_slot_preview_for_decision( + status_payload, + goal_id=GOAL_ID, + slots=2, + before=before, + after_decision=record_after, + quota_status_builder=build_after_quota, + self_repair_spend_actions=frozenset(), + agent_id=AGENT_ID, + source="adapter", + ) + + assert preview["ok"] is True + assert preview["would_throttle"] is True + assert preview["delivery_run_classification"] == "monkeypatched_delivery" + assert preview["delivery_run_recommended_action"] == "advance" + + def _expect_dict(container: dict[str, object], key: str) -> dict[str, object]: + value = container[key] + assert isinstance(value, dict) + return value + + def _expect_first(container: dict[str, object], key: str) -> dict[str, object]: + items = container[key] + assert isinstance(items, list) and isinstance(items[0], dict) + return items[0] + + # Caller's original status_payload must remain untouched. + orig_history_goal = _expect_first(_expect_dict(status_payload, "run_history"), "goals") + assert _expect_dict(orig_history_goal, "quota")["spent_slots"] == 1 + orig_queue_item = _expect_first(_expect_dict(status_payload, "attention_queue"), "items") + orig_asset = _expect_dict(orig_queue_item, "project_asset") + assert _expect_dict(orig_asset, "quota")["spent_slots"] == 1 + + # Deep-copied after_status carries incremented quota across all projections. + assert len(captured_after_status) == 1 + mutated = captured_after_status[0] + mutated_history_goal = _expect_first(_expect_dict(mutated, "run_history"), "goals") + assert _expect_dict(mutated_history_goal, "quota")["spent_slots"] == 3 + mutated_queue_item = _expect_first(_expect_dict(mutated, "attention_queue"), "items") + assert _expect_dict(mutated_queue_item, "quota")["spent_slots"] == 3 + mutated_asset = _expect_dict(mutated_queue_item, "project_asset") + assert _expect_dict(mutated_asset, "quota")["spent_slots"] == 3