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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions benchmark/runtime/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ def turn_command(
if execution.timeout_seconds is not None else []),
"--validation-command-json",
json.dumps(execution.validation_command),
*(["--validation-command-scope", "selected_todo"] if execution.validation_command else []),
"--available-capability",
"shell",
"--available-capability",
Expand Down
36 changes: 28 additions & 8 deletions loopx/cli_commands/quota_should_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ def dispatch_quota_turn_start_hooks(
)

dispatch: dict[str, object] = {}
reconciled_ids: list[str] = []
should_reconcile = (
not preview
and not getattr(args, "scheduler_observation", False)
and bool(getattr(args, "goal_id", None))
)
with capability_hook_request_scope():
if not preview and lark_turn_start_hook_dispatcher is not None:
dispatch = lark_turn_start_hook_dispatcher(
Expand All @@ -86,6 +92,27 @@ def dispatch_quota_turn_start_hooks(
goal_id=args.goal_id,
agent_id=args.agent_id,
)
if args.agent_id or should_reconcile:
from ..history import load_registry
from ..paths import resolve_runtime_root

root = resolve_runtime_root(
load_scoped_registry(registry_path, loader=load_registry),
runtime_root_arg,
registry_path=registry_path,
)
if should_reconcile:
from ..control_plane.turn_driver.replan_successor_publication import (
reconcile_settled_replan_successors,
)

reconciled_ids = reconcile_settled_replan_successors(
registry_path=registry_path,
runtime_root=root,
runtime_root_arg=runtime_root_arg,
goal_id=args.goal_id,
agent_id=args.agent_id,
)
if args.agent_id:
from ..capabilities.decision_context.turn_start_hook import (
extend_turn_start_dispatch as extend_decision_context,
Expand All @@ -94,14 +121,7 @@ def dispatch_quota_turn_start_hooks(
from ..capabilities.semantic_preference.agent_preferences import (
extend_turn_start_dispatch as extend_preferences,
)
from ..history import load_registry
from ..paths import resolve_runtime_root

root = resolve_runtime_root(
load_scoped_registry(registry_path, loader=load_registry),
runtime_root_arg,
registry_path=registry_path,
)
if not preview:
from ..capabilities.turn_start import (
extend_turn_start_dispatch as extend_registered_capabilities,
Expand Down Expand Up @@ -166,7 +186,7 @@ def dispatch_quota_turn_start_hooks(
goal_id=args.goal_id,
agent_id=args.agent_id,
)
local_private_state_mutated = bool(dispatch.get("uncertain_local_effects")) or any(
local_private_state_mutated = bool(reconciled_ids) or bool(dispatch.get("uncertain_local_effects")) or any(
isinstance(result, Mapping)
and result.get("local_private_state_mutated") is not False
for result in (dispatch.get("results") or [])
Expand Down
11 changes: 11 additions & 0 deletions loopx/cli_commands/turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,19 @@ def execution_preparer(decision: Mapping[str, Any]) -> str | None:
turn_start_hook_dispatch = {}
if args.turn_command == "run-once" and args.execute:
from ..capabilities.periodic_report.cadence_runtime import extend_cadence_turn_start_dispatch
from ..control_plane.turn_driver.replan_successor_publication import (
reconcile_settled_replan_successors,
)
from .lark_inbox import dispatch_goal_lark_turn_start_hooks

reconcile_settled_replan_successors(
registry_path=registry_path,
runtime_root=runtime_root,
runtime_root_arg=runtime_root_arg,
goal_id=args.goal_id,
agent_id=args.agent_id,
goal_ref=goal_ref,
)
turn_start_hook_dispatch = dispatch_goal_lark_turn_start_hooks(
registry_path=registry_path,
runtime_root_arg=runtime_root,
Expand Down
10 changes: 10 additions & 0 deletions loopx/cli_commands/turn_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,16 @@ def register_turn_commands(
"The normalized host result is provided on stdin; shell parsing is never used."
),
)
run_once.add_argument(
"--validation-command-scope",
choices=["all", "selected_todo"],
default="all",
help=(
"When --validation-command-json applies: all (default, including "
"Todo-less governance replans) or selected_todo (skip Todo-less "
"governance replans without reflection)."
),
)
run_once.add_argument(
"--validation-timeout-seconds",
type=float,
Expand Down
231 changes: 111 additions & 120 deletions loopx/cli_commands/turn_run_once.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,14 @@
finish_turn_explore_delivery,
require_settlement_effect_ref,
)
from .turn_todo_writeback import write_turn_validated_completion
from .turn_todo_writeback import (
build_replan_task_validator,
defer_staged_replan_successor,
materialize_replan_successor_before_refresh,
publish_settled_replan_successor,
refresh_turn_candidate,
write_turn_validated_completion,
)
from .project_lifecycle_inputs import split_explore_result_input

if _TYPE_CHECKING:
Expand Down Expand Up @@ -290,106 +297,42 @@ def refresh_candidate(
*,
completion_todo_id: str | None = None,
completion_turn_key: str | None = None,
staged_replan_successor_todo_id: str | None = None,
dry_run: bool = False,
) -> dict[str, object]:
# The host workspace is execution context, not state authority.
state_project = None
result_kind = str(result.get("result_kind") or "")
if result_kind in {"repair_required", "replan_required"}:
todo_id = str(selected_todo.get("todo_id") or "")
if not todo_id and not settlement_identity.replan_obligation_id:
raise ValueError(
f"{result_kind} requires one selected todo for typed writeback"
)
# Diagnostics already live in the journal's typed host_result.
# Do not overwrite task context before refresh can reject a result.
progress_observation = result.get("progress_observation")
vision, explore_result = split_candidate_vision(result)
recovery_turn_instance_id = (
settlement_identity.turn_instance_id
if (
bool(args.retry_failed_turn)
and not dry_run
and completion_turn_key == settlement_identity.turn_instance_id
)
else None
)
refresh_task_lease_proof = (
None
if completion_todo_id is not None and (recovery_turn_instance_id is None or rebound_lease_active)
else task_lease_proof
)
return refresh_state_run(
return refresh_turn_candidate(
result,
refresh_state_fn=refresh_state_run,
split_vision_fn=split_candidate_vision,
registry_path=registry_path,
runtime_root_override=runtime_root_arg,
runtime_root_arg=runtime_root_arg,
goal_id=args.goal_id,
project=state_project,
state_file=None,
classification=str(result["classification"]),
recommended_action=str(result["recommended_action"]),
# A host's next_action is follow-up guidance, not refresh-state's
# explicit within-task step edit (which requires a runnable Todo).
# Keep both host texts in the durable host_result, including for
# completion/repair, without decorating a completed or blocked task.
delivery_batch_scale=str(result["delivery_batch_scale"]),
delivery_outcome=str(result["delivery_outcome"]),
delivery_workspace_path=delivery_workspace_path,
todo_id=settlement_identity.todo_id,
replan_obligation_id=settlement_identity.replan_obligation_id,
turn_instance_id=settlement_identity.turn_instance_id,
agent_id=args.agent_id,
progress_scope="goal",
autonomous_replan_recorded=result_kind == "replan_required",
progress_observation=(
dict(progress_observation)
if isinstance(progress_observation, dict) else None
),
agent_vision_packet=vision,
explore_result=explore_result,
vision_unchanged_reason=(
str(result.get("vision_unchanged_reason") or "") or None
),
selected_todo=selected_todo,
settlement_identity=settlement_identity,
delivery_workspace_path=delivery_workspace_path,
task_lease_proof=task_lease_proof,
rebound_lease_active=rebound_lease_active,
retry_failed_turn=bool(args.retry_failed_turn),
no_global_sync=bool(args.no_global_sync),
goal_ref=goal_ref,
completion_todo_id=completion_todo_id,
completion_turn_key=completion_turn_key,
staged_replan_successor_todo_id=staged_replan_successor_todo_id,
dry_run=dry_run,
sync_global=not bool(args.no_global_sync),
goal_ref=goal_ref,
task_lease_proof=refresh_task_lease_proof,
allow_same_generation_lease_renewal=refresh_task_lease_proof is not None,
validation_recovery_turn_instance_id=recovery_turn_instance_id,
)
# A Todo-less native governance Turn has no business artifact/argv.
# Its independent validator is the canonical semantic writeback preview,
# with the same captured obligation and fresh authority as the commit.
# Never treat a model's progress/completion assertion as that validation.
if task_validator is None and settlement_identity.replan_obligation_id and not selected_todo:
def validate_replan(_plan: Mapping[str, Any], result: Mapping[str, Any]) -> dict[str, Any]:
from ..control_plane.work_items.semantic_replan_writeback import ReplanWritebackRejected

try:
passed = (result.get("result_kind") == "replan_required"
and refresh_candidate(dict(result), dry_run=True).get("ok") is True)
except ReplanWritebackRejected as exc:
reason_code = str(
(exc.semantic_delta or {}).get("reason_code") or "replan_writeback_rejected"
).strip() or "replan_writeback_rejected"
return {
"status": "failed",
"validator_kind": "callback",
"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 {})}
task_validator = validate_replan
# Always enforce the Todo-less native governance validator (composing
# after any caller-supplied task validator).
if settlement_identity.replan_obligation_id and not selected_todo:
task_validator = build_replan_task_validator(
caller_validator=task_validator,
validation_command_scope=getattr(args, "validation_command_scope", "all"),
registry_path=registry_path,
runtime_root=runtime_root,
runtime_root_arg=runtime_root_arg,
settlement_identity=settlement_identity,
refresh_candidate=refresh_candidate,
)

def writeback(
result: dict[str, object],
Expand All @@ -401,36 +344,68 @@ def writeback(
require_effect_ref(effect_ref, SettlementStepKind.DURABLE_WRITEBACK)
if args.execute and completion_todo_id is None:
rebind_resumed_settlement_lease()
refresh = refresh_candidate(result, completion_todo_id=completion_todo_id,
completion_turn_key=completion_turn_key)
if refresh.get("ok") and (
refresh.get("appended")
or refresh.get("idempotent_replay")
or refresh.get("receipt_repair_required")
):
# Receipt repair returns the verified original Run without
# appending it again. Its committed payload can deliver the
# requested attachment before repairing the quota receipt.
refresh = finish_explore_delivery({
**refresh, "appended": True,
"idempotent_replay": bool(
refresh.get("idempotent_replay") or refresh.get("receipt_repair_required")
staged_successor, materialization_failure = (
materialize_replan_successor_before_refresh(
payload,
result,
registry_path=registry_path,
runtime_root=runtime_root,
runtime_root_arg=runtime_root_arg,
settlement_identity=settlement_identity,
selected_todo=selected_todo,
)
if completion_todo_id is None
else (None, None)
)
if materialization_failure is not None:
return materialization_failure
committed = False
try:
refresh = refresh_candidate(
result,
completion_todo_id=completion_todo_id,
completion_turn_key=completion_turn_key,
staged_replan_successor_todo_id=(
staged_successor["todo_id"] if staged_successor is not None else None
),
})
if refresh.get("ok") is True:
# The shared quota owner treats this receipt as proof of
# completed writeback. Keep it absent while a requested
# attachment is still pending, even though the Run exists.
append_settlement_event(
refresh,
event_kind="refresh_state",
status="appended",
details={"command": "turn run-once"},
)
if refresh.get("ok") and (
refresh.get("appended")
or refresh.get("idempotent_replay")
or refresh.get("receipt_repair_required")
):
# Receipt repair returns the verified original Run without
# appending it again. Its committed payload can deliver the
# requested attachment before repairing the quota receipt.
refresh = finish_explore_delivery({
**refresh, "appended": True,
"idempotent_replay": bool(
refresh.get("idempotent_replay") or refresh.get("receipt_repair_required")
),
})
if refresh.get("ok") is True:
committed = True
# The shared quota owner treats this receipt as proof of
# completed writeback. Keep it absent while a requested
# attachment is still pending, even though the Run exists.
append_settlement_event(
refresh,
event_kind="refresh_state",
status="appended",
details={"command": "turn run-once"},
)
# Turn callbacks acknowledge committed data, including
# the original primary record returned on receipt repair.
return {**refresh, "appended": True}
if staged_successor is not None:
return {**refresh, "staged_replan_successor": {**staged_successor, "status": "deferred"}}
return refresh
finally:
if not committed and staged_successor is not None:
defer_staged_replan_successor(
registry_path=registry_path, runtime_root_arg=runtime_root_arg,
settlement_identity=settlement_identity, todo_id=staged_successor["todo_id"],
)
# Turn callbacks acknowledge committed data, including
# the original primary record returned on receipt repair.
return {**refresh, "appended": True}
return refresh

def completion_intent(_result: dict[str, object]) -> dict[str, object]:
todo_id = str(selected_todo.get("todo_id") or "")
Expand Down Expand Up @@ -965,11 +940,27 @@ def on_managed_start_admitted() -> None:
**({"host_input_renderer": None} if unmeasurable_operation_host else {}),
)
if args.execute:
if result.get("status") == "committed":
publish_settled_replan_successor(
registry_path=registry_path, runtime_root=runtime_root,
runtime_root_arg=runtime_root_arg, settlement_identity=settlement_identity,
selected_todo=selected_todo,
turn_key=str(result.get("turn_key") or result.get("resume_turn_key") or transaction.get("turn_key") or ""),
goal_ref=goal_ref,
)
result.update(drain_committed_turn_post_writeback_hooks(
registry_path=registry_path, runtime_root=runtime_root,
identity=settlement_identity, goal_ref=goal_ref,
available_capabilities=args.available_capabilities,
))
if (
result.get("ok") is False
and result.get("result_kind") == "writeback_failed"
and isinstance(result.get("reason"), str)
and result["reason"]
and "error" not in result
):
result["error"] = result["reason"]
return result
except Exception as exc: # noqa: BLE001 - CLI boundary renders typed JSON failure
from ..usage_ping import capture_failure
Expand Down
Loading
Loading