Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 74 additions & 4 deletions loopx/cli_commands/quota_should_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@
heartbeat_receipt_view,
)
from ..file_lock import LockAcquireTimeoutError
from ..rollout_event_log import RolloutAppendPreconditionChanged
from ..rollout_event_log import (
RolloutAppendPreconditionChanged,
iter_rollout_events,
rollout_event_log_path,
)
from .quota_presentation import is_undeclared_json_quota_caller

if TYPE_CHECKING:
Expand Down Expand Up @@ -182,6 +186,42 @@ def _can_upgrade_recovery_wait(
return True


def _check_vision_baseline_admission(
log_path: Path,
*,
goal_id: str,
goal_ref: Mapping[str, object] | None,
agent_id: str,
) -> None:
"""Serialize the once-only admission against the actual committed receipt."""
from ..control_plane.goals.source_session_registry_state import exact_goal_ref

expected_ref = (
exact_goal_ref(str(goal_ref["goal_id"]), str(goal_ref["goal_instance_id"]))
if goal_ref is not None else None
)
for event in iter_rollout_events(log_path, committed_only=True):
if (
event.get("event_kind") != "quota_should_run"
or event.get("goal_id") != goal_id
or event.get("agent_id") != agent_id
or event.get("status") != EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED.value
or not isinstance(event.get("run_id"), str)
or not event["run_id"].strip()
or (event.get("goal_ref") != expected_ref if expected_ref is not None else "goal_ref" in event)
):
continue
details = event.get("details")
if (
isinstance(details, Mapping)
and details.get("should_run") is True
and details.get("vision_baseline_initialization") is True
):
raise RolloutAppendPreconditionChanged(
"The scoped Vision baseline admission was already committed."
)


def _append_quota_heartbeat_receipt(
payload: dict[str, object],
args: argparse.Namespace,
Expand Down Expand Up @@ -224,6 +264,24 @@ def _append_quota_heartbeat_receipt(
),
}
)
baseline_admission = (
payload.get("vision_baseline_initialization") is True
and payload.get("ok") is True
and payload.get("should_run") is True
and payload.get("effective_action") == EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED.value
and rollout_replan_obligation_id is not None
)
if baseline_admission:
rollout_details["vision_baseline_initialization"] = True

def check_baseline_commit() -> None:
_check_vision_baseline_admission(
rollout_event_log_path(runtime_root, args.goal_id),
goal_id=args.goal_id,
goal_ref=goal_ref,
agent_id=args.agent_id,
)

try:
with recovery_admission_append_precondition(
payload,
Expand All @@ -233,7 +291,8 @@ def _append_quota_heartbeat_receipt(
agent_id=args.agent_id,
turn_instance_id=turn_instance_id,
goal_ref=goal_ref,
) as precondition:
) as recovery_precondition:
precondition = check_baseline_commit if baseline_admission else recovery_precondition
append_cli_rollout_event(
payload,
registry_path=registry_path,
Expand Down Expand Up @@ -296,14 +355,25 @@ def _append_quota_heartbeat_receipt(
)
return payload
if (
precondition is not None
recovery_precondition is not None
and receipt.get("status")
!= EffectiveAction.UNSETTLED_HOST_TURN_RECOVERY.value
):
raise RolloutAppendPreconditionChanged(
"A different guard was recorded for this Turn."
)

receipt_details = receipt.get("details")
if baseline_admission and not (
isinstance(receipt_details, Mapping)
and receipt_details.get("vision_baseline_initialization") is True
and receipt_details.get("should_run") is True
and receipt.get("status") == EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED.value
):
raise RolloutAppendPreconditionChanged(
"A different guard was committed for this Vision initialization Turn."
)

rollout_event = payload.get("rollout_event")
status = "replayed"
if isinstance(rollout_event, Mapping) and rollout_event.get("appended"):
Expand Down Expand Up @@ -603,6 +673,6 @@ def record_should_run_heartbeat_receipt(
payload,
turn_instance_id=heartbeat_turn_id,
stall_observation=heartbeat_stall_observation,
reason="recovery admission changed repeatedly before append; retry the same Turn",
reason="heartbeat admission changed repeatedly before append; retry the same Turn",
)
return payload, False
2 changes: 1 addition & 1 deletion loopx/control_plane/effect_runtime_handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ export function createEffectRuntimeHandlers(
lazyHandler(() => import("./quota/unsettled_host_turn_recovery.ts"), ({reduceUnsettledHostTurnRecovery}) => reduceUnsettledHostTurnRecovery),
],
["quota.turn_envelope.evaluate", lazyHandler(() => import("./quota/turn_envelope.ts"), ({evaluateTurnEnvelope}) => evaluateTurnEnvelope)],
["quota.run_decision", lazyHandler(() => import("./quota/run_decision.ts"), ({resolveQuotaRunDecision}) => resolveQuotaRunDecision)],
["quota.run_decision", lazyHandler(() => import("./quota/run_decision.ts"), ({admitQuotaRunDecision}) => admitQuotaRunDecision)],
["quota.scoped_override.project", lazyHandler(() => import("./quota/scoped_override.ts"), ({projectScopedOverride}) => projectScopedOverride)],
["task_lease.acquire.native", lazyHandler(() => import("./work_items/task_lease_acquire.ts"), ({executeTaskLeaseAcquire}) => executeTaskLeaseAcquire)],
["task_lease.inspect.native", lazyHandler(() => import("./work_items/task_lease_inspection.ts"), ({inspectTaskLease}) => inspectTaskLease)],
Expand Down
4 changes: 4 additions & 0 deletions loopx/control_plane/quota/decision_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ class QuotaRunDecision:
quota: dict[str, Any]
replan_decision_allowed: bool
goal_route_hint_override: dict[str, Any] | None = None
agent_scope_frontier: dict[str, Any] | None = None
vision_baseline_initialization: bool = False


def refine_quota_recommended_action(
Expand Down Expand Up @@ -266,6 +268,7 @@ def resolve_quota_run_decision(
task_orchestration_contract: dict[str, Any] | None,
receipt_bound_replan_phase: ReceiptBoundReplayPhase | None = None,
receipt_bound_replan_execution_pending: bool = False,
vision_initialization_context: dict[str, Any] | None = None,
) -> QuotaRunDecision:
"""Apply the ordered final guards for one quota run decision."""

Expand Down Expand Up @@ -311,6 +314,7 @@ def resolve_quota_run_decision(
and settlement_packet.get("settlement_only") is True
and settlement_packet.get("decision") == receipt_bound_replan_phase.value
),
"vision_initialization_context": vision_initialization_context,
"goal_health_ok": goal_health_ok,
"inbox_reply_due": inbox_reply_due,
"inbox_material_review_due": inbox_material_review_due,
Expand Down
5 changes: 4 additions & 1 deletion loopx/control_plane/quota/heartbeat_receipt.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from ...rollout_event_log import (
_append_rollout_event_line,
build_rollout_event,
iter_rollout_events,
load_rollout_events,
rollout_event_log_path,
)
Expand Down Expand Up @@ -195,7 +196,9 @@ def find_heartbeat_receipt(
turn_instance_id: str,
goal_ref: Mapping[str, object] | None = None,
) -> dict[str, object] | None:
events = load_rollout_events(rollout_event_log_path(runtime_root, goal_id))
events = list(iter_rollout_events(
rollout_event_log_path(runtime_root, goal_id), committed_only=True,
))
event, _ = _effective_heartbeat_receipt(
_heartbeat_receipt_events(
events,
Expand Down
9 changes: 9 additions & 0 deletions loopx/control_plane/quota/run_decision.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {JsonObject} from "../effect_program.ts";
import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts";
import {requireBoolean, requireJsonObject} from "../runtime_decode.ts";
import {EffectiveAction} from "./effective_action.generated.ts";
import {boundVisionBaselineAdmission} from "./vision_baseline_admission.ts";

interface RunFacts {
normal_delivery_allowed: boolean;
Expand Down Expand Up @@ -43,6 +44,8 @@ interface RunDecision extends JsonObject {
quota_patch: JsonObject;
replan_decision_allowed: boolean;
goal_route_hint_override: JsonObject | null;
agent_scope_frontier: JsonObject | null;
vision_baseline_initialization: boolean;
}

function text(value: unknown, label: string): string {
Expand Down Expand Up @@ -252,6 +255,8 @@ export function resolveQuotaRunDecision(params: JsonObject): JsonObject {
should_run: false, effective_action: EffectiveAction.QUOTA_SKIP,
reason: facts.reason, state: facts.state, quota_patch: {}, replan_decision_allowed: false,
goal_route_hint_override: null,
agent_scope_frontier: null,
vision_baseline_initialization: false,
};
applyDeliveryGuards(facts, decision);
decision.effective_action = quotaEffectiveAction(facts, decision);
Expand All @@ -262,3 +267,7 @@ export function resolveQuotaRunDecision(params: JsonObject): JsonObject {
facts.task_orchestration_contract, facts.task_orchestration_lane_count);
return decision;
}

export async function admitQuotaRunDecision(params: JsonObject): Promise<JsonObject> {
return boundVisionBaselineAdmission(params, resolveQuotaRunDecision(params));
}
10 changes: 10 additions & 0 deletions loopx/control_plane/quota/settlement_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from collections.abc import Mapping
from pathlib import Path

from ..agents.agent_scope_frontier import AgentScopeFrontierAction
from ..scheduler.execution_context import SchedulerExecutionContextResolution
from ..todos.contract import (
normalize_todo_id,
Expand Down Expand Up @@ -310,6 +311,15 @@ def quota_rollout_settlement_binding(
# reentry bind the next independent action without rewriting history.
return None, None

if (
args.quota_command == "should-run"
and payload.get("effective_action") == AgentScopeFrontierAction.AGENT_SCOPE_WAIT.value
and payload.get("should_run") is False
):
# A scoped wait can retain a missing Vision obligation for diagnosis.
# Its receipt grants no replan or Todo settlement identity on replay.
return None, None

explicit_todo_id = normalize_todo_id(getattr(args, "todo_id", None))
explicit_replan_obligation_id = normalize_todo_replan_obligation_id(
getattr(args, "replan_obligation_id", None)
Expand Down
11 changes: 11 additions & 0 deletions loopx/control_plane/quota/should_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,17 @@ def build_quota_should_run(
receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id,
receipt_bound_replan_review=receipt_bound_replan_review,
)
if runtime_root is not None and turn_instance_id and prepared.agent_frontier_id:
prepared.vision_initialization_context = {
"runtime_root": str(runtime_root), "goal_id": safe_goal_id,
"agent_id": prepared.agent_frontier_id, "turn_instance_id": turn_instance_id,
"goal_ref": dict(goal_ref) if goal_ref is not None else None,
"receipt_bound": bool(receipt_bound_todo_id or receipt_bound_replan_obligation_id),
Comment thread
huangruiteng marked this conversation as resolved.
Resolved
"todo_summary": prepared.agent_todo_summary,
"todo_items": prepared.agent_todo_planning_source_items,
"replan_obligation": prepared.replan_obligation,
"acceptance_gaps": prepared.goal_frontier_projection.get("acceptance_gaps"),
}
route = _resolve_quota_should_run_route(prepared)
route = _apply_selected_todo_guards(
prepared,
Expand Down
9 changes: 8 additions & 1 deletion loopx/control_plane/quota/should_run_packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,7 @@ class _QuotaDecisionRoute:
next_action_warning: dict[str, Any] | None
goal_route_hint: dict[str, Any] | None
payload_work_lane_contract: dict[str, Any] | None
vision_baseline_initialization: bool = False


def _planning_projections(
Expand Down Expand Up @@ -943,6 +944,7 @@ def _resolve_quota_should_run_route(
if prepared.receipt_bound_todo_id is None
else None
),
vision_initialization_context=prepared.vision_initialization_context,
)
if prepared.receipt_bound_replay_phase is ReceiptBoundReplayPhase.SETTLED:
fields = settled_replay_fields()
Expand Down Expand Up @@ -1187,7 +1189,8 @@ def _resolve_quota_should_run_route(
agent_lane_next_action=agent_lane_next_action,
)
agent_scope_frontier = (
_selected_deferred_replan_frontier(prepared)
run_decision.agent_scope_frontier
or _selected_deferred_replan_frontier(prepared)
or _agent_scope_no_candidate_frontier(
agent_identity=prepared.agent_identity,
agent_todo_summary=prepared.agent_todo_summary,
Expand Down Expand Up @@ -1331,6 +1334,9 @@ def _resolve_quota_should_run_route(
next_action_warning=next_action_warning,
goal_route_hint=goal_route_hint,
payload_work_lane_contract=payload_work_lane_contract,
vision_baseline_initialization=(
run_decision.vision_baseline_initialization and replan_decision_allowed and should_run
),
)


Expand Down Expand Up @@ -1437,6 +1443,7 @@ def _build_active_quota_payload(
)
payload = {
**_quota_payload_context(prepared, route),
**({"vision_baseline_initialization": True} if route.vision_baseline_initialization else {}),
"decision": AUTONOMOUS_REPLAN_REQUIRED_MODE
if route.replan_decision_allowed
else "run"
Expand Down
1 change: 1 addition & 0 deletions loopx/control_plane/quota/should_run_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ class _QuotaDecisionPreparation:
resolved_scheduler_context: SchedulerExecutionContextResolution
delivery_continuity_anchor: dict[str, Any] | None
delivery_continuity_todo: dict[str, Any] | None
vision_initialization_context: dict[str, Any] | None = None

@property
def inbox_priority_due(self) -> bool:
Expand Down
75 changes: 75 additions & 0 deletions loopx/control_plane/quota/vision_baseline_admission.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type {JsonObject} from "../effect_program.ts";
import {jsonObject, requireJsonObject, requireNonEmptyString} from "../runtime_decode.ts";
import {AgentScopeFrontierAction} from "../agents/agent_scope_frontier.generated.ts";
import {parseWireExactGoalRef} from "../goals/acceptance_lifecycle.ts";
import {
committedGoalHeartbeatReceiptsFromSnapshot,
readGoalRolloutEventSnapshot,
receiptMatchesGoalRef,
} from "../rollout_receipt_log.ts";
import {readAgent, readExcludedAgents} from "../todos/read_codec.ts";
import {EffectiveAction} from "./effective_action.generated.ts";
import {admitsAutonomousReplan, heartbeatReceiptFactFromEvent} from "./heartbeat_receipt_identity.ts";

/** One initialization Turn per runtime/Goal/Agent; missing checkpoints cannot rearm it. */
export async function boundVisionBaselineAdmission(params: JsonObject, decision: JsonObject): Promise<JsonObject> {
const context = params.vision_initialization_context == null ? null
: requireJsonObject(params.vision_initialization_context, "vision_initialization_context");
if (!context || decision.replan_decision_allowed !== true || decision.should_run !== true ||
decision.effective_action !== EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED || context.receipt_bound === true ||
decision.self_repair_allowed === true || decision.capability_repair_allowed === true ||
decision.workspace_repair_allowed === true) return decision;
const agent = requireNonEmptyString(context.agent_id, "agent_id");
const summary = requireJsonObject(context.todo_summary, "todo_summary");
const counts = jsonObject(summary.work_counts);
// Unknown or incomplete projections cannot prove that all real work is blocked.
if (counts?.complete !== true || counts.agent_id !== agent || counts.advancement !== 0 ||
summary.monitor_due_count !== 0 || Number(summary.monitor_schedule_gap_count ?? 0) > 0) return decision;
const rows = context.todo_items;
if (!Array.isArray(rows)) throw new TypeError("todo_items must be an array");
const blocked = rows.map(row => requireJsonObject(row, "Todo")).filter(row =>
row.status === "blocked" && row.done !== true && row.resume_ready !== true &&
(row.task_class === "advancement_task" || row.task_class === "blocker") &&
(!readAgent(row.claimed_by) || readAgent(row.claimed_by) === agent) &&
!readExcludedAgents(row.excluded_agents).includes(agent));
if (!blocked.length) return decision;
const obligation = requireJsonObject(context.replan_obligation, "replan_obligation");
const triggers = obligation.triggers;
const gaps = context.acceptance_gaps;
if (!Array.isArray(triggers) || !triggers.length || !Array.isArray(gaps) || !gaps.length ||
!triggers.every(raw => jsonObject(raw)?.kind === "vision_checkpoint_missing") ||
!gaps.every(raw => {
const gap = jsonObject(raw);
return gap?.kind === "vision_checkpoint_missing" && gap.missing_baseline === true && gap.agent_id === agent;
})) return decision;
const root = requireNonEmptyString(context.runtime_root, "runtime_root");
const goal = requireNonEmptyString(context.goal_id, "goal_id");
const turn = requireNonEmptyString(context.turn_instance_id, "turn_instance_id");
const goalRef = context.goal_ref == null ? null : parseWireExactGoalRef(context.goal_ref, "Goal reference");
const snapshot = await readGoalRolloutEventSnapshot(root, goal);
const receipts = committedGoalHeartbeatReceiptsFromSnapshot(snapshot, goal, agent) ?? [];
const previous = receipts.find(receipt =>
receiptMatchesGoalRef(receipt, goalRef) &&
receipt.status === EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED &&
jsonObject(receipt.details)?.vision_baseline_initialization === true &&
admitsAutonomousReplan(receipt, heartbeatReceiptFactFromEvent(receipt)));
if (!previous) return {...decision, vision_baseline_initialization: true};
const admittedTurn = requireNonEmptyString(previous.run_id, "admitted Turn");
if (admittedTurn === turn) return decision;

const reason = "Vision baseline initialization was already admitted; the scoped frontier remains blocked";
const frontier = {schema_version: "agent_scope_frontier_v1", agent_id: agent,
action: AgentScopeFrontierAction.AGENT_SCOPE_WAIT, blocks_delivery: true,
quiet_noop_allowed: true, spend_policy: "no quota spend while waiting for runnable work or an owner change",
reason, recommended_action: "Wait for executable work or an explicit owner/replan change; retain the pending Vision baseline duty.",
candidate_counts: {current_agent_claimed_advancement_count: 0, unclaimed_advancement_count: 0,
blocked_wait_count: blocked.length},
vision_baseline_admission: {
schema_version: "vision_baseline_admission_v0", goal_id: goal, agent_id: agent,
turn_instance_id: admittedTurn,
replan_obligation_id: requireNonEmptyString(jsonObject(previous.details)?.replan_obligation_id, "admitted replan obligation"),
}};
return {...decision, normal_delivery_allowed: false, recovery_delivery_allowed: false,
should_run: false, replan_decision_allowed: false,
effective_action: AgentScopeFrontierAction.AGENT_SCOPE_WAIT, reason, agent_scope_frontier: frontier};
}
2 changes: 1 addition & 1 deletion loopx/control_plane/rollout_receipt_log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ export function heartbeatReceiptsFromEvents(
}

/** A receipt without an exact Goal instance belongs to the legacy goal scope. */
function receiptMatchesGoalRef(event: JsonObject, goalRef: JsonObject | null): boolean {
export function receiptMatchesGoalRef(event: JsonObject, goalRef: JsonObject | null): boolean {
if (goalRef === null) return !Object.hasOwn(event, "goal_ref");
const eventGoalRef = jsonObject(event.goal_ref);
return eventGoalRef !== null &&
Expand Down
Loading
Loading