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
115 changes: 60 additions & 55 deletions loopx/capabilities/native_chat/steward_monitor_turns.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,90 +425,95 @@ def advancement_turn_id(todo: Mapping[str, object]) -> str:
)


_PRE_DISPATCH_ADVANCEMENT_ERROR_CODES = frozenset({
"resume_failed", "runtime_unavailable", "model_auth_unavailable",
})


def _past_precommit_cooldown(turn: Mapping[str, object], now: float | None) -> bool:
"""Return True when a finished turn has passed the precommit retry cooldown."""
from .steward_turn import _iso_timestamp_seconds

completed_ts = _iso_timestamp_seconds(turn.get("completed_at"))
if completed_ts is None:
return False
return (time.time() if now is None else now) - completed_ts >= ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS


def _zero_write_advancement_response(
turn: Mapping[str, object],
*,
now: float | None = None,
turn: Mapping[str, object], *, now: float | None = None,
) -> Mapping[str, object] | None:
"""Return native_loopx payload only when a completed Turn wrote zero Steward outputs and passed cooldown."""
from .steward_turn import _iso_timestamp_seconds

if turn.get("status") != "completed":
return None
resp = turn.get("response")
if not isinstance(resp, Mapping):
return None
if (
resp.get("steward_owner_report_queued")
or resp.get("context_handoff")
or resp.get("steward_user_action_receipts")
):
if resp.get("steward_owner_report_queued") or resp.get("context_handoff") or resp.get("steward_user_action_receipts"):
return None
nl = resp.get("native_loopx")
if not isinstance(nl, Mapping) or nl.get("ok") is not False:
return None
completed_ts = _iso_timestamp_seconds(turn.get("completed_at"))
if completed_ts is None:
return None
current_ts = time.time() if now is None else now
if current_ts - completed_ts < ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS:
return None
return nl
return nl if _past_precommit_cooldown(turn, now) else None


def _is_zero_effect_pre_dispatch_failed_advancement_turn(
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
turn: Mapping[str, object], *, now: float | None = None,
) -> bool:
"""Allow bounded retry only for unstarted outer Chat preparation failures before worker launch."""
return (
turn.get("status") == "failed"
and turn.get("origin") == "native_loopx"
and turn.get("loopx_execution") is True
and turn.get("error_code") in _PRE_DISPATCH_ADVANCEMENT_ERROR_CODES
and all(turn.get(k) is None for k in ("response", "upstream_turn_id", "started_at", "first_event_at"))
and turn.get("delta_count") == 0
and _past_precommit_cooldown(turn, now)
)


def _is_precommit_retryable_advancement_turn(
turn: Mapping[str, object],
*,
now: float | None = None,
turn: Mapping[str, object], *, now: float | None = None,
) -> bool:
"""Allow one delayed retry only when zero kernel/Steward writes occurred."""
if _is_zero_effect_pre_dispatch_failed_advancement_turn(turn, now=now):
return True
nl = _zero_write_advancement_response(turn, now=now)
if nl is None or nl.get("status") != "failed":
if nl is None:
return False
if nl.get("result_kind") not in {"validation_failed", "host_failure"}:
effects = nl.get("effects")
if nl.get("error_code") == "turn_todo_selection_deferred":
refusal = nl.get("selection_rejection")
return (
isinstance(refusal, Mapping) and refusal.get("state") == "deferred"
and refusal.get("reason_code") == "autonomous_replan"
and isinstance(effects, Mapping) and effects.get("host_invoked") is True
and all(effects.get(k) is False for k in ("state_written", "quota_spent", "scheduler_acknowledged"))
)
if nl.get("status") != "failed" or nl.get("result_kind") not in {"validation_failed", "host_failure"}:
return False
receipt = nl.get("receipt")
commit_eligibility = (
receipt.get("commit_eligibility") if isinstance(receipt, Mapping) else None
) or {}
effects = nl.get("effects") or {}
if not isinstance(commit_eligibility, Mapping) or not isinstance(effects, Mapping):
elig = (receipt.get("commit_eligibility") if isinstance(receipt, Mapping) else None) or {}
eff = effects or {}
if not isinstance(elig, Mapping) or not isinstance(eff, Mapping):
return False
if not (
commit_eligibility.get("writeback") is False
or effects.get("state_written") is False
):
return False
return not (
effects.get("state_written") is True
or effects.get("quota_spent") is True
or effects.get("scheduler_acknowledged") is True
return (elig.get("writeback") is False or eff.get("state_written") is False) and not any(
eff.get(k) is True for k in ("state_written", "quota_spent", "scheduler_acknowledged")
)


def _is_zero_effect_selection_deferred_advancement_turn(
turn: Mapping[str, object],
*,
now: float | None = None,
turn: Mapping[str, object], *, now: float | None = None,
) -> bool:
"""Allow bounded retry only for zero-effect pre-host selection deferrals."""
nl = _zero_write_advancement_response(turn, now=now)
if nl is None or nl.get("error_code") != "turn_todo_selection_deferred":
return False
refusal = nl.get("selection_rejection")
if not isinstance(refusal, Mapping) or refusal.get("state") != "deferred":
return False
effects = nl.get("effects")
if not isinstance(effects, Mapping):
return False
return not any(
effects.get(key) is not False
for key in (
"host_invoked",
"state_written",
"quota_spent",
"scheduler_acknowledged",
)
refusal = nl.get("selection_rejection") if nl is not None else None
effects = nl.get("effects") if nl is not None else None
return (
nl is not None and nl.get("error_code") == "turn_todo_selection_deferred"
and isinstance(refusal, Mapping) and refusal.get("state") == "deferred"
and isinstance(effects, Mapping)
and not any(effects.get(k) is not False for k in ("host_invoked", "state_written", "quota_spent", "scheduler_acknowledged"))
)


Expand Down
5 changes: 2 additions & 3 deletions loopx/capabilities/native_chat/steward_turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,14 +573,13 @@ def report_selection_recovery(self, original: dict[str, Any], *,
return None
current_guard, journal_status = None, journal.get("status")
if (journal_status == "failed" and journal.get("result_kind") == "validation_failed"
and journal.get("validation_stage") == "host_result_contract"):
and journal.get("validation_stage") in {"host_result_contract", "task_postcondition"}):
current_guard = self._cleared_replan_guard(actor)
if current_guard is None:
return None
elif journal_status != "stopped":
return None
# Transport canonical observations to the shared typed admission
# owner.
# Transport canonical observations to the shared typed admission owner.
proof["probe"] = {"turn": probe_turn,
"inspection": inspect_loopx_turn_journal(reports.root, goal_id=actor["goal_id"],
agent_id=actor["agent_id"], turn_key=key),
Expand Down
7 changes: 7 additions & 0 deletions loopx/cli_commands/turn_run_once.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,13 @@ def validate_replan(_plan: Mapping[str, Any], result: Mapping[str, Any]) -> dict
"summary": f"independent native semantic replan preview rejected ({reason_code})",
"recovery_kind": "replan_required",
}
except ValueError:
return {
"status": "failed",
"validator_kind": "callback",
"summary": "independent native semantic replan preview rejected invalid candidate",
"recovery_kind": "repair_required",
}
return {"status": "passed" if passed else "failed", "validator_kind": "callback",
"summary": "independent native semantic replan preview " + ("passed" if passed else "failed"),
**({"recovery_kind": "repair_required"} if not passed else {})}
Expand Down
5 changes: 3 additions & 2 deletions loopx/control_plane/collaboration/steward_managed_mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,9 +363,10 @@ function admitReportSelectionRecovery(params: JsonObject, request: JsonObject, s
throw new EffectRuntimeRequestError("report continuation requires its canonical host-only admission stop; retain all model or unknown work");
}
if (journal.status === "failed" && journal.result_kind === "validation_failed"
&& journal.validation_stage === "host_result_contract") {
&& (journal.validation_stage === "host_result_contract"
|| journal.validation_stage === "task_postcondition")) {
// Only once the blocking autonomous replan obligation is cleared elsewhere
// may a report whose prior governance probe failed host contract validation
// may a report whose prior governance probe failed pre-commit validation
// resume cleanly via one bounded .admission-resume carrier.
const receipt = requireJsonObject(journal.receipt, "probe receipt");
const eligibility = requireJsonObject(receipt.commit_eligibility, "probe commit eligibility");
Expand Down
6 changes: 5 additions & 1 deletion tests/control_plane_ts/steward_reports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -609,10 +609,14 @@ test("only a proven original pre-execution replan refusal admits one correlated
const clearedProbe = {turn: {...source, turn_id: "d".repeat(32), delta_count: 18, upstream_turn_id: "model-turn"},
journal: validationJournal, inspection: validationInspection, current_guard: clearedGuard};
assert.equal(admitStewardManagedTurn({...input, report_selection_recovery: {...proof, probe: clearedProbe}}).observation_only, false);
const postconditionProbe = {...clearedProbe, journal: {...validationJournal, validation_stage: "task_postcondition"}};
assert.equal(admitStewardManagedTurn({...input, report_selection_recovery: {...proof, probe: postconditionProbe}}).observation_only, false);
for (const badProbe of [
{...clearedProbe, current_guard: {effective_action: "autonomous_replan_required", replan_action_packet: {obligation_id: "replan-1"}}},
{...postconditionProbe, current_guard: {effective_action: "autonomous_replan_required", replan_action_packet: {obligation_id: "replan-1"}}},
{...clearedProbe, current_guard: {effective_action: "normal_run", replan_action_packet: {obligation_id: "replan-1"}}},
{...clearedProbe, journal: {...validationJournal, validation_stage: "task_postcondition"}},
{...clearedProbe, journal: {...validationJournal, validation_stage: "settlement_postcondition"}},
{...postconditionProbe, journal: {...postconditionProbe.journal, completed_phases: ["host_execute", "typed_result", "validation"]}},
{...clearedProbe, journal: {...validationJournal, receipt: {...validationJournal.receipt,
commit_eligibility: {writeback: true, quota_spend: false, scheduler_ack: false}}}},
{...clearedProbe, inspection: {...validationInspection, recorded_effects: {...inspection.recorded_effects, state_written: true}}},
Expand Down
4 changes: 2 additions & 2 deletions tests/test_native_steward_reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -2737,7 +2737,7 @@ def now(cls, tz=None):
assert "360" in frozen["reporting"] and "https://github.com/example-org/example-repo/pull/123" in frozen["reporting"]


def test_report_selection_recovery_fails_closed_for_task_postcondition_probe_without_looping(
def test_report_selection_recovery_fails_closed_for_settlement_postcondition_probe_without_looping(
steward, tmp_path, monkeypatch, caplog
):
import logging
Expand Down Expand Up @@ -2820,7 +2820,7 @@ def now(cls, tz=None):
turn_key = replan_events[0]["resume_turn_key"]
jpath = turn_journal_path(reports.root, goal_id=actor["goal_id"], turn_key=turn_key)
journal = load_turn_journal(jpath)
journal["validation_stage"] = "task_postcondition"
journal["validation_stage"] = "settlement_postcondition"
jpath.write_text(json.dumps(journal), encoding="utf-8")

assert configure_goal(
Expand Down
Loading
Loading