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
20 changes: 16 additions & 4 deletions docs/reference/protocols/turn-envelope-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -482,10 +482,17 @@ and are published atomically with owner-only file permissions without replacing
an existing observation. They can contain private Goal context and must not be
included in public logs or artifacts.

Host retry validates and reuses the original journal's capture even if current
source text changes. Reading detail does not invoke quota or spend a slot.
Current source admission, cancellation, workspace/lease and mutation checks
retain their existing owners; the observation grants no fresh authority.
Host retry validates and reuses the original journal's capture. Before native
Codex or an external stdio Host launches with a verified selected Todo, the
current complete contract must still match the original task body, required write scopes and
required capabilities. Progress notes do not invalidate that work. A mismatch
returns `current_turn_work_changed` before dispatching the model. For stdio,
the shared process supervisor holds the launch guard through spawn. The
journal records the refused attempt and its original capture remains readable.
Use a fresh eligible Turn for the changed task. Keep original captures and receipts for
readback. Reading detail does not invoke quota or spend a slot. Current source
admission, cancellation, workspace/lease and mutation checks retain their
existing owners; the observation grants no fresh authority.
Missing, corrupt, wrong-identity or source-hash-mismatched captures refuse Host
reinvocation. Restore the original evidence rather than reconstructing it from
a new guard. A capture published before a journal write failure is retained;
Expand All @@ -507,6 +514,11 @@ blocks resume. Journal inspection can report the invalid work contract without
performing recovery or a debit. Retain the historical reader until the last
supported journal and its recovery window are reconciled.

原生 Codex 和外部 stdio Host 启动前会用当前完整契约复核所选 Todo 的已验证正文、
所需写入范围和能力。只改进度备注可以继续。改变工作声明会在模型调用前返回
`current_turn_work_changed`。stdio 进程由共用的进程管理器在准入锁内启动。
journal 记录已拒绝的尝试。变更后的工作使用新的合格 Turn,原捕获与回执仍可读回。

恢复预览和 journal 解释共用同一个 typed plan reader。受支持的历史记录保留原版本和
字节。显式声明不支持的 plan、envelope 或动作签名版本及覆盖范围时,恢复会停止。
检查入口仍可报告契约无效,不执行恢复或扣额。保留历史读取器,直到最后一份受支持的
Expand Down
5 changes: 4 additions & 1 deletion loopx/cli_commands/turn_decision.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ def current_turn_host_launch_decision(
args: argparse.Namespace, *, registry_path: Path, runtime_root: Path,
identity: SettlementIdentity,
planned_effective_action: object,
planned_selected_work_basis: str | None,
scheduler_execution_context: Mapping[str, Any],
operator_inbox_urgency_projector: Callable[..., dict[str, Any]],
turn_start_hook_dispatch: Mapping[str, Any] | None = None,
Expand Down Expand Up @@ -416,7 +417,7 @@ def current_turn_host_launch_decision(
plan = build_loopx_turn_plan(
current_contract, host=args.host, execution_mode=args.execution_mode,
scheduler_owner=args.scheduler_owner, turn_instance_id=identity.turn_instance_id,
goal_ref=goal_ref,
goal_ref=goal_ref, include_selected_work_basis=planned_selected_work_basis is not None,
)
route = plan["route"]
if route.get("would_invoke_host") is not True:
Expand All @@ -425,6 +426,8 @@ def current_turn_host_launch_decision(
raise FirstPartyHostRuntimeRejected("current_turn_selection_changed")
if (identity.replan_obligation_id or identity.request_subject is not None) and plan["transaction"]["settlement_plan"]["identity"] != identity.as_dict():
raise FirstPartyHostRuntimeRejected("current_turn_selection_changed")
if planned_selected_work_basis is not None and plan.get("_selected_work_basis") != planned_selected_work_basis:
raise FirstPartyHostRuntimeRejected("current_turn_work_changed")
return launch


Expand Down
45 changes: 20 additions & 25 deletions loopx/cli_commands/turn_run_once.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import argparse
from functools import partial
import sys as _sys
from collections.abc import Callable, Mapping
from pathlib import Path
Expand Down Expand Up @@ -767,18 +768,24 @@ def scheduler(_spend_payload: dict[str, object]) -> dict[str, object]:

host_runner: Callable[[Mapping[str, Any]], dict[str, Any]] | None = None
session_binding_resolver = None
if args.host == "codex-app-server":
def native_launch_decision(current_registry: Path) -> Mapping[str, Any]:
return current_turn_host_launch_decision(args, registry_path=current_registry,
runtime_root=runtime_root, identity=settlement_identity,
planned_effective_action=execution_context["effective_action"],
scheduler_execution_context=payload.get("scheduler_execution_context") or {},
operator_inbox_urgency_projector=operator_inbox_urgency_projector,
turn_start_hook_dispatch=turn_start_hook_dispatch, goal_ref=goal_ref)

def current_launch_decision(current_registry: Path) -> Mapping[str, Any]:
# Native and stdio transports recheck the original work at launch.
# A global route checks its source even if the mirror is unchanged.
return current_turn_host_launch_decision(
args, registry_path=current_registry, runtime_root=runtime_root,
identity=settlement_identity,
planned_effective_action=execution_context["effective_action"],
planned_selected_work_basis=execution_context.get("selected_work_basis"),
scheduler_execution_context=payload.get("scheduler_execution_context") or {},
operator_inbox_urgency_projector=operator_inbox_urgency_projector,
turn_start_hook_dispatch=turn_start_hook_dispatch, goal_ref=goal_ref,
)

if args.host == "codex-app-server":
native_admission = (goal_admission or FirstPartyHostGoalAdmission.for_plan(
registry_path=registry_path, goal_id=args.goal_id, planned_goal_ref=goal_ref,
)).with_launch_decision(native_launch_decision)
)).with_launch_decision(current_launch_decision)

def run_native_host(request: Mapping[str, Any]) -> dict[str, Any]:
return native_host_runner(request, lambda: native_admission.launch_lifetime(
Expand All @@ -787,22 +794,6 @@ def run_native_host(request: Mapping[str, Any]) -> dict[str, Any]:
host_runner = run_native_host
session_binding_resolver = native_session_binding_resolver
elif args.host == "codex-cli":

def current_launch_decision(current_registry: Path) -> Mapping[str, Any]:
# Revalidate the already admitted identity through the same
# owner. In a global route the source is checked first, even
# when its mirror still advertises old quota or health.
return current_turn_host_launch_decision(
args, registry_path=current_registry, runtime_root=runtime_root,
identity=settlement_identity,
planned_effective_action=execution_context["effective_action"],
scheduler_execution_context=payload.get("scheduler_execution_context") or {},
operator_inbox_urgency_projector=operator_inbox_urgency_projector,
# Keep this Turn's already dispatched required reads at launch.
turn_start_hook_dispatch=turn_start_hook_dispatch,
goal_ref=goal_ref,
)

host_runner = build_codex_cli_host_runner(
args, runtime_root=runtime_root, project=project,
registry_path=registry_path, goal_ref=goal_ref,
Expand Down Expand Up @@ -924,6 +915,10 @@ def on_managed_start_admitted() -> None:
admit_start=managed_cadence.admit if args.execute else None,
confirm_start=managed_cadence.confirm if args.execute else None,
goal_admission=goal_admission,
host_launch_guard=(partial(
goal_admission.with_launch_decision(current_launch_decision).launch_lifetime,
operation="turn_external_host_launch",
) if raw_argv is not None and goal_admission is not None else None),
)
if args.execute:
result.update(drain_committed_turn_post_writeback_hooks(
Expand Down
19 changes: 17 additions & 2 deletions loopx/control_plane/quota/turn_envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1957,6 +1957,7 @@ export function completePlanningFacts(request: JsonObject): JsonObject {
return {...lineage, work, source_decision_hash: decisionSourceHash(decision),
action_source_hash: canonicalHash(turnEnvelopeActionSignatureDocument(work)),
scoped_settlement_identity: scopedIdentity, scoped_identity_error: identityError,
...(request.include_selected_work_basis === true ? {selected_work_basis: selectedWorkLaunchBasis(decision)} : {}),
...(request.inspect_plan === true &&
(lineage.route === "ready_for_host" || lineage.route === "replan_required")
? {inspection_paths: turnPlanInspectionPaths(decision, lineage.route)} : {})};
Expand Down Expand Up @@ -2010,6 +2011,19 @@ function completeTaskTextSha256(decision: JsonObject, todoId: unknown): string |
return capturedTodoTextSha256(declared, context, decision.recommended_action, todoId);
}

/** Launch rechecks the admitted task, not the provider revision or the bounded
* action signature. Progress, diagnostics and receipt changes are not edits to
* the work. Losing the verified body on a fresh read is not a match. */
function selectedWorkLaunchBasis(decision: JsonObject, verifiedTextSha256?: string | null): string | null {
const todoId = selectedWorkTodoId(decision);
const selected = object(decision.selected_todo);
if (!todoId || todoId !== selected.todo_id) return null;
const textSha256 = verifiedTextSha256 === undefined ? completeTaskTextSha256(decision, todoId) : verifiedTextSha256;
return textSha256 === null ? null : canonicalHash({todo_id: todoId, text_sha256: textSha256,
required_write_scopes: selected.required_write_scopes ?? [],
required_capabilities: selected.required_capabilities ?? []});
}

export function composeCompleteTurnDecision(value: unknown): JsonObject {
const request = requireJsonObject(value, "complete Turn decision request");
const payload = requireJsonObject(request.payload, "complete Turn decision source");
Expand Down Expand Up @@ -2655,8 +2669,9 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject {
const {decision, projection} = completeHostSource(request);
const work = {selected_todo: object(projection.action).selected_todo,
task_orchestration_contract: projection.task_orchestration_contract};
return {selected_todo: selectedWorkTodo(work),
sha256: completeTaskTextSha256(decision, selectedWorkTodoId(work) ?? ""),
const sha256 = completeTaskTextSha256(decision, selectedWorkTodoId(work) ?? "");
return {selected_todo: selectedWorkTodo(work), sha256,
selected_work_basis: selectedWorkLaunchBasis(decision, sha256),
effective_action: decision.effective_action ?? null,
writeback: object(projection.writeback),
task_lease_proof: object(object(decision.execution_preparation).lease_proof),
Expand Down
30 changes: 20 additions & 10 deletions loopx/control_plane/turn_driver/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,21 @@ def _bind_host_child_operations(
return bound


def _complete_plan_source_fields(
work_contract: object, projection: Mapping[str, Any], original_envelope: Mapping[str, Any] | None,
) -> dict[str, Any]:
fields = {"work_contract": work_contract, "source_decision_hash": projection["source_decision_hash"]}
for key in ("inspection_paths", "selected_work_basis"):
if key in projection:
fields[f"_{key}"] = projection[key]
if original_envelope is not None:
# Carry the reader of the original capture from a transitional pair.
header = captured_turn_host_input({"turn_envelope": original_envelope})
if "detail_ref" in header:
fields["detail_ref"] = header["detail_ref"]
return fields


def build_loopx_turn_plan(
turn_envelope: Mapping[str, Any],
*,
Expand All @@ -431,6 +446,7 @@ def build_loopx_turn_plan(
goal_ref: Mapping[str, object] | None = None,
work_contract: object = _ABSENT_WORK_CONTRACT,
inspect_plan: bool = False,
include_selected_work_basis: bool = False,
) -> dict[str, Any]:
"""Plan from one complete source; retain the recorded v0 input codec.

Expand Down Expand Up @@ -483,6 +499,7 @@ def build_loopx_turn_plan(
projection = _turn_envelope_result("planning_facts", payload=work_contract,
turn_instance_id=turn_instance_id,
**({"inspect_plan": True} if inspect_plan else {}),
**({"include_selected_work_basis": True} if include_selected_work_basis else {}),
**({} if source_only_input else {"envelope": supplied}))
envelope = _mapping(projection["work"])
else:
Expand Down Expand Up @@ -609,16 +626,9 @@ def build_loopx_turn_plan(
),
}
if current:
payload["work_contract"] = work_contract
payload["source_decision_hash"] = projection["source_decision_hash"]
if "inspection_paths" in projection:
payload["_inspection_paths"] = projection["inspection_paths"]
if not source_only_input:
# Older callers may already carry an original quota capture. Keep
# its exact header without retaining that caller's second source.
header = captured_turn_host_input({"turn_envelope": supplied})
if "detail_ref" in header:
payload["detail_ref"] = header["detail_ref"]
payload.update(_complete_plan_source_fields(
work_contract, projection, None if source_only_input else supplied,
))
else:
payload["turn_envelope"] = envelope
if child_operations:
Expand Down
62 changes: 36 additions & 26 deletions loopx/control_plane/turn_driver/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,7 @@ def _run_host(
argv: Sequence[str],
project: Path,
timeout_seconds: float | None,
launch_guard: Callable[[], AbstractContextManager[None]] | None = None,
) -> dict[str, Any]:
# Dispatch has checked the source and its internal effect adapter before
# journal/cadence admission. External stdin gets the same single complete
Expand All @@ -900,7 +901,10 @@ def count_stderr(text: str) -> None:
stdout_limit_bytes=HOST_RESULT_MAX_BYTES,
on_stdout=stdout.append,
on_stderr=count_stderr,
launch_guard=launch_guard,
)
except FirstPartyHostRuntimeRejected:
raise
except (OSError, RuntimeError, ValueError) as exc:
return {"ok": False, "reason": type(exc).__name__, "returncode": None}
if observed["outcome"] == "output_limit":
Expand Down Expand Up @@ -1011,6 +1015,7 @@ def _host_result_stage(
confirm_start: Callable[[], None] | None = None,
usage_runtime_root: Path | None = None,
usage_goal_id: str = "",
host_launch_guard: Callable[[], AbstractContextManager[None]] | None = None,
) -> tuple[dict[str, Any] | None, list[str], dict[str, Any] | None]:
completed_phases = list(journal.get("completed_phases") or [])
from_journal = "typed_result" in completed_phases
Expand All @@ -1033,22 +1038,32 @@ def _host_result_stage(
confirm_start()
from ...usage_goal import observe_goal_execution

with observe_goal_execution(
usage_runtime_root or project,
usage_goal_id,
host=str((plan.get("host") or {}).get("kind") or "unknown"),
):
host_observation = (
_run_host_runner(request, runner=host_runner)
if host_runner is not None
else _run_host(
request,
argv=argv or [],
project=project,
timeout_seconds=timeout_seconds,
rejected_launch = None
try:
with observe_goal_execution(
usage_runtime_root or project,
usage_goal_id,
host=str((plan.get("host") or {}).get("kind") or "unknown"),
):
host_observation = (
_run_host_runner(request, runner=host_runner)
if host_runner is not None
else _run_host(
request,
argv=argv or [],
project=project,
timeout_seconds=timeout_seconds,
launch_guard=host_launch_guard,
)
)
)
effects["host_invoked"] = True
except FirstPartyHostRuntimeRejected as exc:
# Stdio checks the Goal only before spawn. A native Host can reject
# after dispatch too, so retain reconciliation for other failures.
if host_runner is not None and exc.code != "current_turn_work_changed":
raise
rejected_launch = exc.code
host_observation = {"ok": False, "reason": str(exc), "failure_kind": "contract_rejected"}
effects["host_invoked"] = rejected_launch is None
if not host_observation.get("ok"):
failure = _host_failure(
plan,
Expand All @@ -1074,17 +1089,10 @@ def _host_result_stage(
else:
journal.pop("host_recovery", None)
persist_journal(journal)
return (
None,
[],
execution_payload(
plan,
journal,
execute=True,
replayed=False,
effects=effects,
),
)
terminal = execution_payload(plan, journal, execute=True, replayed=False, effects=effects)
if rejected_launch is not None:
terminal["error_code"] = rejected_launch
return None, [], terminal
result = dict(host_observation["value"])
completed_phases = list(TRANSACTION_PHASES[:2])

Expand Down Expand Up @@ -1575,6 +1583,7 @@ def run_loopx_turn_once(
admit_start: Callable[[Mapping[str, Any]], dict[str, Any]] | None = None,
confirm_start: Callable[[], None] | None = None,
goal_admission: FirstPartyHostGoalAdmission | None = None,
host_launch_guard: Callable[[], AbstractContextManager[None]] | None = None,
) -> dict[str, Any]:
argv, host_projection = _prepare_host_invocation(plan, host_argv=host_argv, host_runner=host_runner)
transaction_plan = (
Expand Down Expand Up @@ -1846,6 +1855,7 @@ def finish_recovery(payload: dict[str, Any]) -> dict[str, Any]:
persist_journal=persist_journal,
effects=effects,
confirm_start=confirm_start if reserved_start else None,
host_launch_guard=host_launch_guard,
)
if terminal is not None:
return finish_recovery(terminal)
Expand Down
Loading
Loading