diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index 57d8ae49ec..7a05c3f4fd 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -90,6 +90,28 @@ depending on the executor: ## Goal Review Cadence +Fresh autonomous replan work shares the Goal's compute window. Once +`spent_slots >= allowed_slots`, its extra allowance is **zero**: `quota should-run` +returns the existing typed `throttled_skip` action rather than admitting a +replan wakeup. A pending replan remains pending until rolling-window accounting +restores allowance or the owner increases the existing compute budget. This +also applies when a focus or external wait masks the exhausted window. Replan +still precedes monitor quiet and lane waits while compute remains available. +Recovery of a positively admitted replan keeps its original Goal, Agent, Turn +and obligation when the window later fills. Verified writeback still uses the +original settlement plan, including qualified no-debit closeouts. If the +spend owner rejects the debit because the window is full, retry that same +settlement when allowance returns. Owner Stop and zero compute pause +automatic execution. + +新的自主重规划与 Goal 共用算力窗口。`spent_slots >= allowed_slots` 时,额外额度为 +**零**;`quota should-run` 使用现有的 typed `throttled_skip`,不再为待处理的重规划 +唤醒模型。等待滚动窗口恢复额度,或 owner 提高已有算力预算后重新判断;focus 或 +外部等待不会豁免这一限制。有剩余额度时,重规划仍优先于 monitor quiet 和 lane wait。 +已有准入收据的重规划在额度用尽后仍按原 Goal、Agent、Turn 和义务恢复;已验证的 +写回沿原结算计划收尾,仍支持符合条件的免扣额收尾。扣额责任方因窗口已满拒绝扣额时, +等额度恢复后重试同一笔结算。Owner Stop 和零算力暂停自动执行。 + The product and benchmark runners default to review after **6 settled effective work Turns** in both standard and fine-grained modes. This changes the previous product threshold of five Turns and benchmark threshold of three Turns. Review diff --git a/loopx/control_plane/quota/decision_summary.py b/loopx/control_plane/quota/decision_summary.py index a6aa9afc71..d8294de7c2 100644 --- a/loopx/control_plane/quota/decision_summary.py +++ b/loopx/control_plane/quota/decision_summary.py @@ -265,6 +265,7 @@ def resolve_quota_run_decision( goal_frontier_projection: dict[str, Any] | None, task_orchestration_contract: dict[str, Any] | None, receipt_bound_replan_phase: ReceiptBoundReplayPhase | None = None, + receipt_bound_replan_execution_pending: bool = False, ) -> QuotaRunDecision: """Apply the ordered final guards for one quota run decision.""" @@ -289,6 +290,8 @@ def resolve_quota_run_decision( "self_repair_allowed": self_repair_allowed, "repair_effective_action": str(repair_action or ""), "state": state, "reason": reason, + "quota_allowed_slots": str(quota["allowed_slots"]) if quota.get("allowed_slots") is not None else None, + "quota_spent_slots": str(quota["spent_slots"]) if quota.get("spent_slots") is not None else None, "quota_focus_wait": bool(quota.get("focus_wait")), "capability_gate": _guard_strings(capability_gate, ("action", "reason")), "capability_monitor_fallback": bool(capability_monitor_fallback), @@ -297,6 +300,10 @@ def resolve_quota_run_decision( "automation_prompt_upgrade_required": automation_prompt_upgrade_required, "replan_required": replan_required, "replan_applies": bool(scope.get("applies")), + "replan_execution_pending": ( + receipt_bound_replan_execution_pending + and (replan_obligation or {}).get("selection_binding") == "heartbeat_receipt" + ), "replan_settlement_pending": ( receipt_bound_replan_phase is ReceiptBoundReplayPhase.SETTLEMENT_PENDING and (replan_obligation or {}).get("selection_binding") == "heartbeat_receipt" diff --git a/loopx/control_plane/quota/heartbeat_receipt_identity.ts b/loopx/control_plane/quota/heartbeat_receipt_identity.ts index 4eaa75d083..a7da9f7bb1 100644 --- a/loopx/control_plane/quota/heartbeat_receipt_identity.ts +++ b/loopx/control_plane/quota/heartbeat_receipt_identity.ts @@ -103,6 +103,16 @@ export function heartbeatReceiptFactFromEvent( }; } +/** Read positive autonomous replan admission from an effective guard receipt. */ +export function admitsAutonomousReplan(event: JsonObject, fact: HeartbeatReceiptFact): boolean { + const guard = heartbeatReceiptDetails(event); + const obligationId = normalizeHeartbeatReplanObligationId(guard.semantic_replan_obligation_id); + return fact.settlement_effect_id !== null && obligationId !== null + && (fact.todo_id !== null || obligationId === fact.replan_obligation_id) + && guard.interaction_mode === "autonomous_replan" && guard.ok === true && guard.should_run === true + && guard.must_attempt_work === true && guard.delivery_allowed === false && guard.quiet_noop_allowed === false; +} + /** * Resolve the settlement binding a persisted receipt declares. * diff --git a/loopx/control_plane/quota/live_decision.py b/loopx/control_plane/quota/live_decision.py index cfe569dcfe..632359ec20 100644 --- a/loopx/control_plane/quota/live_decision.py +++ b/loopx/control_plane/quota/live_decision.py @@ -56,10 +56,14 @@ def _receipt_bound_guard_fields( guard = getattr(readback, "semantic_replan_guard", None) receipt = getattr(readback, "heartbeat_receipt", None) or {} identity = readback.identity.value if readback is not None else None + guard_scoped = bool( + obligation_id and isinstance(guard, Mapping) and guard.get("scope") == "turn_guard" + and guard.get("selected_obligation_id") == obligation_id + ) return { - "receipt_bound_replan_guard_scoped": bool( - obligation_id and isinstance(guard, Mapping) and guard.get("scope") == "turn_guard" - and guard.get("selected_obligation_id") == obligation_id + "receipt_bound_replan_guard_scoped": guard_scoped, + "receipt_bound_replan_execution_pending": bool( + guard_scoped and readback and readback.replan_execution_pending ), "receipt_bound_guard_recorded_at": receipt.get("recorded_at"), "receipt_bound_guard_turn_instance_id": identity.turn_instance_id if identity is not None else None, diff --git a/loopx/control_plane/quota/prior_turn_closeout.ts b/loopx/control_plane/quota/prior_turn_closeout.ts index 67841d77f8..9f07b8416e 100644 --- a/loopx/control_plane/quota/prior_turn_closeout.ts +++ b/loopx/control_plane/quota/prior_turn_closeout.ts @@ -11,10 +11,9 @@ import type { JsonObject } from "../effect_program.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { jsonObject } from "../runtime_decode.ts"; import { + admitsAutonomousReplan, heartbeatReceiptBinding, - heartbeatReceiptDetails, heartbeatReceiptFactFromEvent, - normalizeHeartbeatReplanObligationId, selectEffectiveHeartbeatReceipt, type HeartbeatReceiptBinding, type HeartbeatReceiptFact, @@ -56,15 +55,6 @@ function candidate( }; } -function admitsAutonomousReplan(event: JsonObject, fact: HeartbeatReceiptFact): boolean { - const guard = heartbeatReceiptDetails(event); - const obligationId = normalizeHeartbeatReplanObligationId(guard.semantic_replan_obligation_id); - return fact.settlement_effect_id !== null && obligationId !== null - && (fact.todo_id !== null || obligationId === fact.replan_obligation_id) - && guard.interaction_mode === "autonomous_replan" && guard.ok === true && guard.should_run === true - && guard.must_attempt_work === true && guard.delivery_allowed === false && guard.quiet_noop_allowed === false; -} - /** * Select prior Turns eligible for closeout readback. A Todo-bound replan * carries the Todo settlement identity and a separate semantic obligation. diff --git a/loopx/control_plane/quota/run_decision.ts b/loopx/control_plane/quota/run_decision.ts index 91c2031556..09bf241aa3 100644 --- a/loopx/control_plane/quota/run_decision.ts +++ b/loopx/control_plane/quota/run_decision.ts @@ -11,6 +11,8 @@ interface RunFacts { state: string; reason: string; quota_focus_wait: boolean; + quota_allowed_slots: bigint | null; + quota_spent_slots: bigint | null; capability_gate: JsonObject | null; capability_monitor_fallback: boolean; workspace_guard: JsonObject | null; @@ -18,6 +20,7 @@ interface RunFacts { automation_prompt_upgrade_required: boolean; replan_required: boolean; replan_applies: boolean; + replan_execution_pending: boolean; replan_settlement_pending: boolean; goal_health_ok: boolean; inbox_reply_due: boolean; @@ -63,6 +66,8 @@ function decodeRunFacts(params: JsonObject): RunFacts { repair_effective_action: text(params.repair_effective_action, "repair_effective_action"), state: text(params.state, "state"), reason: text(params.reason, "reason"), quota_focus_wait: requireBoolean(params.quota_focus_wait, "quota_focus_wait"), + quota_allowed_slots: quotaCount(params.quota_allowed_slots, "quota_allowed_slots"), + quota_spent_slots: quotaCount(params.quota_spent_slots, "quota_spent_slots"), capability_gate: optionalRecord(params.capability_gate, "capability_gate"), capability_monitor_fallback: requireBoolean(params.capability_monitor_fallback, "capability_monitor_fallback"), workspace_guard: optionalRecord(params.workspace_guard, "workspace_guard"), @@ -70,6 +75,8 @@ function decodeRunFacts(params: JsonObject): RunFacts { automation_prompt_upgrade_required: requireBoolean(params.automation_prompt_upgrade_required, "automation_prompt_upgrade_required"), replan_required: requireBoolean(params.replan_required, "replan_required"), replan_applies: requireBoolean(params.replan_applies, "replan_applies"), + replan_execution_pending: params.replan_execution_pending === undefined ? false + : requireBoolean(params.replan_execution_pending, "replan_execution_pending"), replan_settlement_pending: params.replan_settlement_pending === undefined ? false : requireBoolean(params.replan_settlement_pending, "replan_settlement_pending"), goal_health_ok: requireBoolean(params.goal_health_ok, "goal_health_ok"), @@ -88,6 +95,14 @@ function nonNegativeCount(value: unknown, label: string): number { return Number(value); } +function quotaCount(value: unknown, label: string): bigint | null { + if (value === null || value === undefined) return null; + // Decimal transport preserves Python's integer precision without rounding quota boundaries. + if (typeof value !== "string" || !/^\d+$/.test(value)) + throw new EffectRuntimeRequestError(`${label} must be a non-negative integer string`); + return BigInt(value); +} + function guardReason(guard: JsonObject | null, fallback: string): string { return (guard ? text(guard.reason ?? "", "guard.reason") : "") || fallback; } @@ -139,8 +154,19 @@ function quotaEffectiveAction(facts: RunFacts, decision: RunDecision): string { function applyGoalOverrides(facts: RunFacts, decision: RunDecision): void { const inboxPriority = facts.inbox_reply_due || facts.inbox_material_review_due; - decision.replan_decision_allowed = !inboxPriority && facts.replan_required && facts.replan_applies + const replanSelected = !inboxPriority && facts.replan_required && facts.replan_applies && facts.goal_health_ok && !facts.workspace_guard && !facts.automation_prompt_upgrade_required; + const quotaExhausted = facts.state === "throttled" || (facts.quota_allowed_slots !== null + && facts.quota_spent_slots !== null && facts.quota_spent_slots >= facts.quota_allowed_slots); + const budgetAllowsReplan = !quotaExhausted || facts.replan_execution_pending || facts.replan_settlement_pending; + decision.replan_decision_allowed = replanSelected && budgetAllowsReplan; + if (replanSelected && !budgetAllowsReplan) { + clearExecutionLanes(decision); + decision.should_run = false; + decision.effective_action = EffectiveAction.THROTTLED_SKIP; + decision.reason = "compute window exhausted; fresh replan has zero extra allowance; " + + "wait until the window resets or the owner raises the compute budget"; + } if (decision.replan_decision_allowed) { if (facts.replan_settlement_pending) { // A covered frontier can stop new work before its original receipt has diff --git a/loopx/control_plane/quota/settlement.py b/loopx/control_plane/quota/settlement.py index f0563d3fe5..c5d282fd63 100644 --- a/loopx/control_plane/quota/settlement.py +++ b/loopx/control_plane/quota/settlement.py @@ -180,6 +180,7 @@ class QuotaSettlementReadback: native_child_admission: dict[str, Any] | None = None heartbeat_reentry_qualification: dict[str, Any] | None = None successor_replan_pending: bool = False + replan_execution_pending: bool = False def render_owed_host_command(argv: list[str]) -> str: @@ -547,6 +548,7 @@ def read_heartbeat_settlement( native_child_admission=_optional_readback_record(payload.get("native_child_admission")), heartbeat_reentry_qualification=_optional_readback_record(payload.get("heartbeat_reentry_qualification")), successor_replan_pending=payload.get("successor_replan_pending") is True, + replan_execution_pending=payload.get("replan_execution_pending") is True, spend_run=_optional_readback_record(payload.get("spend_run")), heartbeat_receipt=_optional_readback_record(payload.get("heartbeat_receipt")), writeback_event=_optional_readback_record(payload.get("writeback_event")), diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index 10bd891ae3..e0b3f977b5 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -52,6 +52,7 @@ import { type RefreshRetryRequest, } from "./refresh_recovery.ts"; import { + admitsAutonomousReplan, heartbeatReceiptDetails as details, heartbeatReceiptFactFromEvent, normalizeHeartbeatReplanObligationId as normalizeReplanObligationId, @@ -1430,6 +1431,8 @@ function readQuotaSettlementFromRequest( completion_event: includeRecords ? completionEvent : null, monitor_phase: monitorPhase, replay_phase: replayPhase, + replan_execution_pending: replayPhase === "open" && + admitsAutonomousReplan(heartbeatReceipt, heartbeatReceiptFactFromEvent(heartbeatReceipt)), successor_replan_pending: replayPhase === "open" && heartbeatReceipt.status === "successor_replan_required" && receiptDetails.should_run === true && receiptDetails.delivery_allowed === false, diff --git a/loopx/control_plane/quota/should_run.py b/loopx/control_plane/quota/should_run.py index 5635697ada..1f85af9df8 100644 --- a/loopx/control_plane/quota/should_run.py +++ b/loopx/control_plane/quota/should_run.py @@ -566,6 +566,7 @@ def build_quota_should_run( receipt_bound_terminal_phase: ReceiptBoundTerminalPhase | None = None, receipt_bound_replan_obligation_id: str | None = None, receipt_bound_replan_guard_scoped: bool = False, + receipt_bound_replan_execution_pending: bool = False, receipt_bound_successor_replan: bool = False, receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, @@ -663,6 +664,7 @@ def build_quota_should_run( receipt_bound_replay_phase=receipt_bound_replay_phase, receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id, receipt_bound_replan_guard_scoped=receipt_bound_replan_guard_scoped, + receipt_bound_replan_execution_pending=receipt_bound_replan_execution_pending, receipt_bound_successor_replan=receipt_bound_successor_replan, authoritative_fallback_todo_items=authoritative_fallback_todo_items, replan_explore_reader=tracked_replan_explore_reader, diff --git a/loopx/control_plane/quota/should_run_packet.py b/loopx/control_plane/quota/should_run_packet.py index 188a422a11..294d2fc2a4 100644 --- a/loopx/control_plane/quota/should_run_packet.py +++ b/loopx/control_plane/quota/should_run_packet.py @@ -935,6 +935,7 @@ def _resolve_quota_should_run_route( registered_agent_ids=prepared.registered_agent_ids, goal_frontier_projection=prepared.goal_frontier_projection, task_orchestration_contract=prepared.task_orchestration_contract, + receipt_bound_replan_execution_pending=prepared.receipt_bound_replan_execution_pending, receipt_bound_replan_phase=( prepared.receipt_bound_replay_phase if prepared.receipt_bound_todo_id is None diff --git a/loopx/control_plane/quota/should_run_prepare.py b/loopx/control_plane/quota/should_run_prepare.py index d22528a4d8..9ad6d45307 100644 --- a/loopx/control_plane/quota/should_run_prepare.py +++ b/loopx/control_plane/quota/should_run_prepare.py @@ -149,6 +149,7 @@ class _QuotaDecisionPreparation: action_selection_qualification: dict[str, Any] | None receipt_bound_monitor_phase: ReceiptBoundMonitorPhase | None receipt_bound_replay_phase: ReceiptBoundReplayPhase | None + receipt_bound_replan_execution_pending: bool user_todo_summary: dict[str, Any] | None agent_todo_summary: dict[str, Any] | None agent_todo_planning_source_items: list[dict[str, Any]] @@ -750,6 +751,7 @@ def _prepare_quota_should_run_item( receipt_bound_replay_phase: ReceiptBoundReplayPhase | None, receipt_bound_replan_obligation_id: str | None, receipt_bound_replan_guard_scoped: bool = False, + receipt_bound_replan_execution_pending: bool = False, receipt_bound_successor_replan: bool = False, authoritative_fallback_todo_items: FallbackTodoSource = None, replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None = None, @@ -1109,6 +1111,7 @@ def _prepare_quota_should_run_item( action_selection_qualification=None, receipt_bound_monitor_phase=receipt_bound_monitor_phase, receipt_bound_replay_phase=receipt_bound_replay_phase, + receipt_bound_replan_execution_pending=receipt_bound_replan_execution_pending, user_todo_summary=user_todo_summary, agent_todo_summary=agent_todo_summary, agent_todo_planning_source_items=agent_todo_planning_source_items, diff --git a/loopx/quota.py b/loopx/quota.py index 4dac35fb65..68f27bd509 100644 --- a/loopx/quota.py +++ b/loopx/quota.py @@ -1078,6 +1078,7 @@ def build_quota_should_run( receipt_bound_terminal_phase: ReceiptBoundTerminalPhase | None = None, receipt_bound_replan_obligation_id: str | None = None, receipt_bound_replan_guard_scoped: bool = False, + receipt_bound_replan_execution_pending: bool = False, receipt_bound_successor_replan: bool = False, receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, @@ -1122,6 +1123,7 @@ def read_explore_context(read_goal_id: str, read_agent_id: str | None) -> dict[s receipt_bound_terminal_phase=receipt_bound_terminal_phase, receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id, receipt_bound_replan_guard_scoped=receipt_bound_replan_guard_scoped, + receipt_bound_replan_execution_pending=receipt_bound_replan_execution_pending, receipt_bound_successor_replan=receipt_bound_successor_replan, receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, diff --git a/tests/control_plane/test_effect_turn_live_quota_decision.py b/tests/control_plane/test_effect_turn_live_quota_decision.py index 2870ba5f13..bc02deab96 100644 --- a/tests/control_plane/test_effect_turn_live_quota_decision.py +++ b/tests/control_plane/test_effect_turn_live_quota_decision.py @@ -33,15 +33,26 @@ GOAL_ID = "effect-interpreter-fixture" -@pytest.mark.parametrize("selected", ["replan-1111111111111111", "replan-2222222222222222"]) -def test_receipt_guard_fields_use_the_typed_identity_and_guard(selected: str) -> None: +@pytest.mark.parametrize( + ("guard_matches", "execution_pending", "expected_pending"), + [(True, True, True), (True, False, False), (False, True, False)], + ids=["matching-open", "matching-not-pending", "different-obligation"], +) +def test_receipt_guard_fields_use_the_typed_identity_and_guard( + guard_matches: bool, execution_pending: bool, expected_pending: bool, +) -> None: + obligation = "replan-1111111111111111" + selected = obligation if guard_matches else "replan-2222222222222222" fields = _receipt_bound_guard_fields(SimpleNamespace( semantic_replan_guard={"scope": "turn_guard", "selected_obligation_id": selected}, identity=SimpleNamespace(value=SimpleNamespace(turn_instance_id="original-turn")), heartbeat_receipt={"recorded_at": "2026-08-01T00:00:00Z", "run_id": "other-turn", - "details": {"semantic_replan_obligation_id": "replan-1111111111111111"}}, - successor_replan_pending=False), "replan-1111111111111111") - assert fields["receipt_bound_replan_guard_scoped"] is (selected == "replan-1111111111111111") + "details": {"semantic_replan_obligation_id": obligation}}, + successor_replan_pending=False, + replan_execution_pending=execution_pending, + ), obligation) + assert fields["receipt_bound_replan_guard_scoped"] is guard_matches + assert fields["receipt_bound_replan_execution_pending"] is expected_pending assert fields["receipt_bound_guard_turn_instance_id"] == "original-turn" assert fields["receipt_bound_guard_recorded_at"] == "2026-08-01T00:00:00Z" diff --git a/tests/control_plane/test_replan_quota_exhaustion.py b/tests/control_plane/test_replan_quota_exhaustion.py new file mode 100644 index 0000000000..b162c3cb64 --- /dev/null +++ b/tests/control_plane/test_replan_quota_exhaustion.py @@ -0,0 +1,231 @@ +"""Fresh replan work needs remaining compute; settlement retains its own owner.""" +from datetime import datetime, timezone +import json +import shlex +from pathlib import Path + +import pytest + +from loopx.control_plane.quota.live_decision import build_live_quota_should_run_decision +from loopx.control_plane.testing.quota_fixtures import quota_status_payload, quota_todo_item + + +GOAL = "quota-replan-fixture" +AGENT = "fixture-agent" + + +def _status(*, state="throttled", allowed=1, spent=1, compute=1): + return quota_status_payload( + goal_id=GOAL, status="active", recommended_action="Wait for the dependency.", + agent_todo_items=[quota_todo_item( + index=1, todo_id="todo_blocked_work", text="Wait for the dependency.", + status="open", resume_when="todo_done:todo_missing_dependency", + claimed_by=AGENT, task_class="advancement_task", + )], + quota_state=state, + quota_extra={"compute": compute, "allowed_slots": allowed, "spent_slots": spent}, + coordination={"agent_model": "peer_v1", "registered_agents": [AGENT]}, + latest_runs=[{ + "classification": "state_refreshed", "generated_at": "2026-07-04T00:05:00Z", + "agent_id": AGENT, "progress_scope": "agent_lane", + "delivery_outcome": "outcome_progress", + "vision_checkpoint": { + "schema_version": "vision_checkpoint_v0", "agent_id": AGENT, + "required": True, "satisfied": False, "decision": "missing_required", + "triggers": [{"kind": "material_delivery_outcome", "delivery_outcome": "outcome_progress"}], + "required_resolution": ["write_agent_vision_patch", "record_unchanged_reason"], + }, + }], + ) + + +def _read(status, tmp_path, **kwargs): + return build_live_quota_should_run_decision( + status, goal_id=GOAL, agent_id=AGENT, available_capabilities=["shell"], + include_scheduler_detail=False, codex_app_current_rrule=None, + registry_path=tmp_path / "registry.json", runtime_root=tmp_path / "runtime", + scheduler_execution_context={"host_surface": "generic_cli", + "scheduler_owner": "agent_cli_loop", "execution_mode": "interactive"}, + **kwargs, + ) + + +@pytest.mark.parametrize("state", ["throttled", "focus_wait", "waiting"]) +def test_exhausted_window_does_not_admit_fresh_replan(tmp_path: Path, state: str): + for _ in range(2): + packet = _read(_status(state=state), tmp_path) + assert packet["should_run"] is False + assert packet["effective_action"] == "throttled_skip" + assert "replan" in packet["reason"] and "zero" in packet["reason"] + assert packet["scheduler_hint"]["action"] != "run_now" + assert packet["interaction_contract"]["agent_channel"]["must_attempt"] is False + assert packet["interaction_contract"]["agent_channel"]["delivery_allowed"] is False + + +@pytest.mark.parametrize("allowed,spent", [(1, 0), (2, 1)]) +def test_window_reset_or_owner_increase_reopens_replan(tmp_path: Path, allowed: int, spent: int): + assert _read(_status(), tmp_path)["should_run"] is False + packet = _read(_status(state="eligible", allowed=allowed, spent=spent), tmp_path) + assert packet["should_run"] is True + assert packet["effective_action"] == "autonomous_replan_required" + assert packet["scheduler_hint"]["action"] == "run_now" + + +def test_zero_compute_remains_an_owner_pause(tmp_path: Path): + packet = _read(_status(state="paused", compute=0, allowed=0), tmp_path) + assert packet["should_run"] is False + assert packet["scheduler_hint"]["action"] == "stop_until_explicit_resume" + + +@pytest.mark.parametrize("spent,expected", [(0, True), (1, False)]) +def test_should_run_cli_uses_the_shared_admission( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture, + spent: int, expected: bool, +): + from loopx.cli import main + from loopx.cli_commands import quota + + status = _status(state="eligible" if expected else "throttled", spent=spent) + monkeypatch.setattr(quota, "collect_status", lambda **kwargs: status) + (tmp_path / "registry.json").write_text(json.dumps({"goals": [{ + "id": GOAL, "repo": str(tmp_path), "state_file": "fixture.md", + }]}), encoding="utf-8") + (tmp_path / "fixture.md").write_text("# Synthetic Goal\n", encoding="utf-8") + code = main([ + "--registry", str(tmp_path / "registry.json"), + "--runtime-root", str(tmp_path / "runtime"), "--format", "json", + "quota", "should-run", "--goal-id", GOAL, "--agent-id", AGENT, + "-H", "generic_cli", "-O", "agent_cli_loop", "-M", "interactive", + "--context-delivery", "off", + ]) + assert code == 0 + packet = json.loads(capsys.readouterr().out) + assert packet["should_run"] is expected + assert packet["effective_action"] == ( + "autonomous_replan_required" if expected else "throttled_skip" + ) + + +def test_exhaustion_preserves_exact_owed_turn_recovery(tmp_path: Path): + from canonical_authority_fixture import initialize_canonical_source_fixture + from loopx.rollout_event_log import build_rollout_event + + runtime = tmp_path / "runtime" + state = tmp_path / "fixture.md" + state.write_text( + "# Synthetic Goal\n\n## Agent Todo\n\n- [ ] Wait for the dependency.\n" + f" \n", + encoding="utf-8", + ) + (tmp_path / "registry.json").write_text(json.dumps({"goals": [{ + "id": GOAL, "repo": str(tmp_path), "state_file": str(state), + }]}), encoding="utf-8") + initialize_canonical_source_fixture(runtime, GOAL, state_path=state, provider="sqlite") + event = build_rollout_event( + goal_id=GOAL, event_kind="quota_should_run", agent_id=AGENT, + todo_id="todo_blocked_work", run_id="prior-turn", status="normal_run", + summary="Original Turn requires settlement.", details={ + "todo_id": "todo_blocked_work", "closeout_required": True, + "settlement_effect_id": f"{GOAL}:{AGENT}:todo_blocked_work:prior-turn", + }, + ) + log = runtime / "goals" / GOAL / "rollout-event-log.jsonl" + log.parent.mkdir(parents=True, exist_ok=True) + log.write_text(json.dumps(event) + "\n", encoding="utf-8") + packet = _read(_status(), tmp_path, turn_instance_id="current-turn") + assert packet["effective_action"] == "unsettled_host_turn_recovery" + assert packet["unsettled_host_turn_recovery"]["prior_turn_instance_id"] == "prior-turn" + assert packet["interaction_contract"]["agent_channel"]["delivery_allowed"] is False + assert packet["interaction_contract"]["cli_channel"]["spend_after_validation"] is False + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_exhausted_window_preserves_only_the_admitted_replan( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +): + from test_replan_successor_guard_reentry import ( + AGENT as CLI_AGENT, + GOAL as CLI_GOAL, + TURN, + _add, + _fixture, + _guard, + ) + + call, _, index = _fixture(tmp_path, monkeypatch, provider) + registry = tmp_path / "registry.json" + config = json.loads(registry.read_text()) + config["goals"][0]["quota"]["allowed_slots"] = 1 + registry.write_text(json.dumps(config)) + + original = _guard(call) + assert original["effective_action"] == "autonomous_replan_required" + identity = original["heartbeat_receipt"]["settlement_identity"] + assert original["quota"]["spent_slots"] == 0 + + # Another lane spends the remaining slot after the guard is committed. + # Seed an ordinary ledger entry and let the production CLI account for it. + timestamp = datetime.now(timezone.utc).isoformat() + spend = { + "classification": "quota_slot_spent", "generated_at": timestamp, + "goal_id": CLI_GOAL, "agent_id": "different-agent", + "quota_event": {"event_type": "quota_slot_spent", "slots": 1}, + } + with index.open("a", encoding="utf-8") as ledger: + ledger.write(json.dumps(spend) + "\n") + + fresh_turn = "turn-after-compute-exhaustion" + for _ in range(2): + fresh = _guard(call, fresh_turn) + assert (fresh["quota"]["allowed_slots"], fresh["quota"]["spent_slots"]) == (1, 1) + assert fresh["effective_action"] == "throttled_skip" + assert fresh["should_run"] is False + assert not fresh["interaction_contract"]["cli_channel"].get("settlement_plan") + + replay = _guard(call, TURN) + assert (replay["quota"]["allowed_slots"], replay["quota"]["spent_slots"]) == (1, 1) + assert replay["heartbeat_receipt"]["event_id"] == original["heartbeat_receipt"]["event_id"] + assert replay["effective_action"] == "autonomous_replan_required" + assert replay["interaction_contract"]["agent_channel"]["delivery_allowed"] is False + assert replay["interaction_contract"]["cli_channel"]["settlement_plan"]["identity"] == identity + + plan = call("turn", "plan", "--goal-id", CLI_GOAL, "--agent-id", CLI_AGENT, + "--turn-instance-id", TURN, "--host", "codex-cli") + assert plan["route"]["kind"] == "replan_required" + + config["goals"][0]["quota"]["compute"] = 0 + registry.write_text(json.dumps(config)) + paused = _guard(call, TURN) + assert paused["should_run"] is False + assert paused["scheduler_hint"]["action"] == "stop_until_explicit_resume" + config["goals"][0]["quota"]["compute"] = 1 + registry.write_text(json.dumps(config)) + + _add(call, identity["replan_obligation_id"]) + recovered = _guard(call, TURN) + assert recovered["replan_action_packet"]["settlement_only"] is True + actions = recovered["interaction_contract"]["cli_channel"]["next_cli_actions"] + refreshed = call(*shlex.split(actions[0])[1:], "--no-global-sync", "--suppress-external-sinks") + assert refreshed["settlement_progress"]["state"] == "spend_required" + + pending = _guard(call, TURN) + cli = pending["interaction_contract"]["cli_channel"] + assert cli["settlement_plan"]["identity"] == identity + assert [step["kind"] for step in cli["settlement_plan"]["ordered_steps"]] == ["quota_spend"] + assert cli["next_cli_actions"] == [actions[1]] + debit = shlex.split(actions[1])[1:] + denied = call(*debit, expected_code=1) + assert denied["appended"] is False + assert denied["quota_rejection_action"] == "throttled_skip" + + # The spend owner still enforces its existing policy. An owner increase + # restores the allowance, then the same owed debit can settle exactly once. + config["goals"][0]["quota"]["allowed_slots"] = 2 + registry.write_text(json.dumps(config)) + assert call(*debit)["appended"] is True + assert call(*debit)["appended"] is False + settled = _guard(call, TURN) + assert settled["effective_action"] == "heartbeat_settled_skip" + assert settled["heartbeat_receipt"]["settlement_identity"] == identity + assert settled["should_run"] is False diff --git a/tests/control_plane_ts/quota_run_decision.test.ts b/tests/control_plane_ts/quota_run_decision.test.ts index dc6ec5c00c..516c6049f5 100644 --- a/tests/control_plane_ts/quota_run_decision.test.ts +++ b/tests/control_plane_ts/quota_run_decision.test.ts @@ -15,11 +15,32 @@ for (const scenario of fixture.cases) { test("malformed admission facts cannot manufacture a runnable decision", () => { for (const patch of [{normal_delivery_allowed: "true"}, {replan_applies: null}, {workspace_guard: "not a guard"}, {quota_focus_wait: 1}, {reason: null}, - {task_orchestration_lane_count: -1}, {task_orchestration_lane_count: 1.5}]) { + {task_orchestration_lane_count: -1}, {task_orchestration_lane_count: 1.5}, + {quota_allowed_slots: "-1"}, {quota_spent_slots: "1.5"}, {quota_spent_slots: 1}]) { assert.throws(() => resolveQuotaRunDecision({...fixture.base_facts, ...patch} as JsonObject)); } }); +for (const state of ["throttled", "focus_wait", "waiting", "eligible"]) { + test(`fresh replan cannot exceed its compute window under ${state}`, () => { + const result = resolveQuotaRunDecision({...fixture.base_facts, state, + replan_required: true, replan_applies: true, + quota_allowed_slots: "1", quota_spent_slots: "1"}); + assert.equal(result.should_run, false); + assert.equal(result.replan_decision_allowed, false); + assert.equal(result.normal_delivery_allowed, false); + assert.equal(result.effective_action, "throttled_skip"); + }); +} + +test("quota boundaries retain integer precision and admit only remaining allowance", () => { + const facts = {...fixture.base_facts, replan_required: true, replan_applies: true, + quota_allowed_slots: "9007199254740993", quota_spent_slots: "9007199254740992"}; + assert.equal(resolveQuotaRunDecision(facts).replan_decision_allowed, true); + assert.equal(resolveQuotaRunDecision({...facts, + quota_spent_slots: "9007199254740993"}).should_run, false); +}); + for (const scenario of [ { name: "adaptive counts child lanes",