Skip to content

Latest commit

 

History

History
1560 lines (1350 loc) · 99 KB

loopx-turn-v0.md

File metadata and controls

1560 lines (1350 loc) · 99 KB

LoopX Governed Turn v0

Status: experimental protocol and implementation target.

Integrators using the built-in Codex CLI host should start with the one-Turn quickstart. This document is the protocol and maintainer reference, not required onboarding.

loopx_turn_v0 defines how LoopX can govern one bounded turn executed by an external agent-loop host, such as Codex CLI, without turning that host into a second control plane. LoopX remains authoritative for goal state, todos, claims, gates, quota, scheduler hints, and compact evidence. The host owns model execution, tools, and an opaque resumable session handle.

The turn run-once dry-run response also carries a compact planned route: kind, selected_todo_id and would_invoke_host. This additive field lets delegation preflight distinguish a successful preview from task admission while using the same executor/model arguments as execution. It grants no host invocation and changes no executing-Turn receipt; the four effect flags remain false.

The protocol is host-neutral. A Codex CLI adapter is the first target, but the driver lifecycle must not depend on Codex-specific session files, transcript formats, or benchmark task schemas.

The controller/executor RFC proposes reusing this governed lifecycle across managed, attached heartbeat and external-worker paths. A Turn remains the admitted work/settlement unit, not one model message or timer wake. Splitting native session roles does not create a second business executor, quota identity or independent control plane.

中文:controller/executor 提案 拟让托管、附着 heartbeat 与外部 worker 复用这套生命周期。Turn 仍是获准工作及其 结算单元,不等于一条模型消息或一次唤醒;拆分会话角色不增加业务执行者或 quota 身份。 上述跨入口收敛仍待实现与真实路径验收。

Execution deadline defaults

turn run-once now has no default single-turn wall-time limit (previously 120 seconds). The built-in Codex hosts and generic managed host transport wait for natural completion or cancellation. --timeout-seconds remains an explicit operator-selected deadline for bounded execution or recovery tests.

The external heartbeat scheduler likewise has no default wake-command deadline (previously 600 seconds); --wake-timeout-seconds opts into one. Quota probes, provider request/idle liveness checks, validation commands, output budgets, lease fencing and process-group cleanup retain their own boundaries. Cancellation still terminates the owned process tree; disabling an execution timer does not authorize continued effects after cancellation or lease loss.

Benchmark adapters retain their declared total trial deadline. The shared Harbor adapter defaults a call to the remaining trial allowance, including its existing startup/cleanup reserve, instead of imposing an independent 4700-second wake cap. Explicit per-call settings in existing experiment configurations remain explicit protocol choices; omit them for natural continuation.

单轮执行默认不再计时终止:Turn 的原 120 秒上限和外部 heartbeat 的原 600 秒 wake 上限均改为显式选择。取消、租约失效、输出限制、请求存活检查和进程清理 仍生效。benchmark 仍遵守整场总预算,默认不另设 4700 秒的单轮上限。

Mental Model

LoopX Turn is a four-stage control loop, not another agent runtime:

LoopX decides -> agent CLI executes -> validator proves -> LoopX commits
Stage Owner Contract
Decide LoopX CLI Select one allowed action from live goal, todo, gate, capability, quota, and cadence state.
Execute Host adapter plus an agent CLI such as Trae CLI or Codex CLI Consume one typed request, run one bounded segment, and emit one typed candidate result.
Validate Independent task-specific command or callback Check the real artifact, test, remote state, or declared read-only postcondition.
Commit LoopX CLI Write durable state and spend one quota slot only after validation passes.

This separation lets the same Turn contract govern coding, operations, data, document, knowledge-maintenance, and other long-running workflows. The agent CLI remains responsible for model and tool execution; it does not become the authority for goal state or completion.

Generic Agent CLI Quick Start

An agent CLI does not need native LoopX support. It needs a thin host adapter and an independent validator:

  1. Run loopx turn plan to inspect the live typed decision without launching the host or changing state.
  2. A new Turn sends one loopx_turn_host_request_v1 object with a complete work_contract. The adapter reads it on stdin, invokes the selected agent CLI in the governed workspace, and writes one loopx_turn_result_v0 object to stdout.
  3. The validator reads the normalized host result from stdin and independently checks the claimed postcondition. Exit zero means passed; non-zero means the result is rejected. A timeout or unavailable validator is inconclusive.
  4. loopx turn run-once --execute performs writeback and quota spend only when the typed result and independent validation both pass.

Built-in model renderers derive loopx_turn_model_context_v0 after validating the complete source in an adapter request. task_context preserves task facts, backlog, required reads, scope, execution profile and unknown additions. Source binding, the effect projection, scheduler/automation execution data and interaction_contract.cli_channel remain with the outer executor. The model view resolves existing replan authoring and Explore guidance references before hiding their outer owner, preserving the original scalar values and text. Operators can read release readiness and completed Todo archive warnings in quota/status and the original capture. The built-in Worker view omits these maintenance directions. Recognized unconfigured recall keeps its Goal, Agent and disabled status. Known empty pre-turn observations keep their hook, capability and status. The full readbacks stay with the executor. Available context, failed observations, required reads and extended readbacks reach the Worker intact. Work-context delivery keeps scoped Todo records, their provider revision and record digest. The canonical Todo reader supplies the field dictionary for both registered read formats. Unknown formats retain their supplied metadata. For ordinary admitted work, matching recognized ready lease preparations stay with the launcher and settlement reader. The Worker retains the admitted task, scope, required reads and validation conditions. Unready, differing and extended preparations stay in the task view. When admitted steering_audit_then_one_step carries the standard mixed accounting clause, that clause stays with the executor and the TypeScript source check enables the built-in work-segment guidance in the Worker prompt: check direction, then choose the largest coherent work segment it can reliably complete and verify given its capabilities, budget, admitted task, scope and execution profile (one_step is a work segment, not a single operation, and a Todo groups related steps toward one verifiable outcome). Unrecognized policy text stays in the task view untouched without substituting that guidance, because it can carry additional constraints. When admitted ordinary work carries the standard owner-only blocker rule in todo_write_hint, command templates and queue section headings remain with the outer executor while the TypeScript source check enables the Todo rules owner's Worker disposition requirements in the prompt: report verified owner-only blockers for user_gate even when noted in Next Action (non-blocking requests belong in user_action), split mixed work and isolate the smallest blocked Todo, give the owner the exact action and verification check, and continue runnable independent work or identify a useful independent successor from Goal acceptance before yielding. Custom todo_write_hint.rule text and non-ordinary turns retain the original rule in task_context (still isolating CLI templates and section headers) without substituting the built-in guidance. The model receives the original source_decision_hash, reader references and source_schema_version; that hash commits the original source, not the task view. Inline task context does not require a filesystem read of a private capture that a sandbox cannot access. Missing required evidence still holds dependent work. This presentation is not an adapter request or a permission, settlement or completion authority. Generic adapter stdin and private journal recovery retain the complete v1 source; historical envelope-only v0 inputs keep their renderer.

For admitted ordinary work, an omitted known Todo summary lane is empty. Nonempty lanes, counts, references, upstream truncation and unknown fields remain visible. Complete summaries are available through the original source reader when needed.

内置模型 renderer 在校验 adapter 请求中的完整来源后派生 loopx_turn_model_context_v0。task_context 保留任务事实、backlog、必需读取、 范围、执行要求和未知新增信息。来源绑定、effect projection、scheduler/automation 执行数据及 interaction_contract.cli_channel 留在外层执行器。 来源中指向外层 owner 的 replan 编写和 Explore 指导引用在隐藏该 owner 前展开, 保留原始标量和文本。操作方在 quota/status 和原始 capture 中读取发布资格和已完成 Todo 归档提醒。内置 Worker 视图省略这两条维护指令。能识别的未配置召回保留 Goal、Agent 和停用状态。已知的空观察 保留钩子、能力和状态。完整回执留在外层执行器。有可用上下文、观察失败、必需读取 或扩展回执时,Worker 仍收到完整内容。工作上下文保留作用域内的 Todo、读取版本和记录摘要。 两种已登记格式的字段表由 canonical Todo 读取入口提供,未知格式保留其元数据。 普通任务准入后,完全一致且可识别的就绪租约记录留在启动和结算入口。Worker 保留已准入 任务、范围、必需读取与验证条件。未就绪、有差异或带扩展字段的记录继续交付给 Worker。 当获准执行的 steering_audit_then_one_step 携带标准混合扣额条款时,该条款 留在执行器,由 TypeScript 来源校验开启内置提示中的工作段指导:先核对方向,再按 自身能力、预算、已准入任务、范围和执行要求,选择能可靠完成并验证的最大连贯工作段 (one_step 指一个工作段而非单次操作,同一可验证结果的相关操作归在一个 Todo)。 无法识别的策略原文继续完整交付给 Worker 且不以该指导替代,因为它可能带有额外约束。 当普通任务准入后的 todo_write_hint 携带标准所有者阻塞处置规则时,写入命令 模板与队列标题留在外层执行器,TypeScript 来源校验通过 Todo 规则 owner 在内置 Worker 提示中保留阻塞报告与继续工作的必要条件:确认属于所有者的阻塞时立即作为 user_gate 报告(即使已在 Next Action 记述;非阻塞请求归入 user_action),拆分混合工作并 隔离最小受阻 Todo,向所有者提供具体动作与验真检查,并在交还前继续独立可做的工作或从 Goal acceptance 中识别独立后继;自定义 todo_write_hint.rule 文本及非普通模式保留原 rule(同时继续隔离命令模板与标题)而不以内置提示替代。 模型仍收到原始 source_decision_hash、reader 引用和 source_schema_version;该 hash 绑定原始 来源,不绑定任务视图。已内联的任务上下文不要求 sandbox 读取不可访问的私有 capture, 缺少必需证据仍暂停依赖该证据的工作。此呈现不是 adapter 请求,也不授予权限、结算或 完成权。通用 adapter stdin 和私有 journal 恢复仍保留完整 v1 来源;仅携带 envelope 的历史 v0 输入保留原 renderer。

对于获准执行的普通任务,视图可以省去已知为空的 Todo 摘要列表。非空列表、计数、 引用、来源截断信息和未知字段继续可见。需要完整摘要时,使用原有来源读取入口。

Use loopx turn plan --include-transaction-detail --format markdown to inspect should_run, the effective action, reason and selected work summary. Its Full plan JSON block retains the complete source contract, session and transaction that the same explicit JSON detail view exposes. Read the full source for requirements or evidence beyond the summary; neither view authorizes execution. The default short Markdown view and recorded v0 rendering remain unchanged. Both detail formats include host.supported_capabilities when the selected Turn host has a registered descriptor. Read current launchability from managed_executor and the planned session action from session. Without an explicit --execution-mode, the selected host sets the plan's mode. DSH and generic-cli default to isolated-headless. Codex CLI and Claude Code default to interactive-visible. For headless Claude execution, select generic-cli and supply a typed adapter to turn run-once.

使用 loopx turn plan --include-transaction-detail --format markdown 检查是否应运行、 有效动作、原因及已选工作的摘要。Full plan JSON 块保留同一显式 JSON 详情视图中的 完整来源合同、session 与 transaction。摘要之外的要求与证据须查看完整来源;两种视图 均不授予执行权限。默认简短 Markdown 视图与历史 v0 呈现保持原样。 所选 Turn 宿主有已注册描述符时,两种详情均包含 host.supported_capabilities。 当前能否启动见 managed_executor,本轮会话动作见 session。 省略 --execution-mode 时,计划按所选宿主决定默认模式。DSH 和 generic-cli 默认使用 isolated-headless。Codex CLI 和 Claude Code 默认使用 interactive-visible。如需无头执行 Claude,选择 generic-cli,并向 turn run-once 提供符合契约的适配器。

The example uses the repository's TraeX adapter and an integration-supplied validator. The two programs separate the executor's completion claim from validation of its artifact.

loopx turn plan \
  --goal-id example-goal \
  --agent-id example-worker \
  --host generic-cli \
  --execution-mode isolated-headless

loopx turn run-once \
  --goal-id example-goal \
  --agent-id example-worker \
  --host generic-cli \
  --execution-mode isolated-headless \
  --project "$PWD" \
  --host-adapter-request-schema loopx_turn_host_request_v1 \
  --host-adapter-command-json '["python3","./scripts/traex_turn_host_adapter.py"]' \
  --validation-command-json '["./tools/verify-turn-postcondition"]' \
  --execute

Do not pass a free-form interactive command directly as --host-adapter-command-json unless it already implements the typed stdin/stdout contract. For Trae CLI, Codex CLI, or another conversational CLI, the adapter translates between the Turn request/result objects and that CLI's prompt, session, and output model. Raw transcript text, process exit zero, and the host's own completion claim are never sufficient validation.

For Claude Code, use the native /loop path for an attached session. For headless turn run-once, select generic-cli and supply a Claude adapter that implements the typed stdin/stdout contract above.

Claude Code 的附着会话通过原生 /loop 运行。用 turn run-once 无头执行时, 选择 generic-cli,并提供实现上述标准输入输出契约的 Claude 适配器。

The TraeX reference adapter (traex exec) renders the checked complete request and accepts the shared typed result fields. LoopX owns Goal and Todo authority, independent validation, writeback and quota. For the public TRAE CLI, add "--traex-bin","traecli" to the adapter command array. The selected binary must support exec - for reading the complete prompt from stdin, --output-schema, and --output-last-message.

公版 TRAE CLI 可在适配器命令数组中加 "--traex-bin","traecli"。 所选版本须支持通过 exec - 从标准输入读取完整提示,以及 --output-schema 和 --output-last-message。

For another generic adapter, verify that the installed version accepts v1 before declaring it with --host-adapter-request-schema. A missing or incompatible declaration stops a v1 invocation before the adapter process starts.

A recorded v0 Turn keeps its original wire version. If recovery still needs the adapter, use a v0-compatible adapter and omit the declaration or pass loopx_turn_host_request_v0. Recovery with a saved typed result continues without launching an adapter.

New generic and built-in Codex CLI v1 Turns on POSIX bind the original capture's byte digest in detail_ref.captured_decision.sha256. The shared model renderer exposes detail_ref.context_read for details needed during the Turn. Add one --select '<pointer>' per known field in the same command. If a pointer is rejected, use recovery_command to locate it in the same capture and correct the selection. Follow next_command through the remaining pages when needed. In a restricted built-in Codex CLI session, the shell uses the existing local stdio transport for the reader and its continuation commands. The reader checks the digest on every read. If the capture is missing or its digest differs, restore the original before dependent work. The v1 adapter still receives its complete inline work_contract, and detail_ref.full_decision still returns the original JSON for existing readers. For a journal-bound cat reader, the Windows Host prompt uses a literal PowerShell read of that same UTF-8 file.

POSIX 上新建的 generic 与内置 Codex CLI v1 Turn 会在 detail_ref.captured_decision.sha256 里 绑定原始快照的字节摘要。共享模型呈现通过 detail_ref.context_read 补读本轮所需 细节。在同一命令中为每个已知字段加一个 --select '<pointer>'。路径定位失败时, 按 recovery_command 在同一份捕获中查找并修正选择。必要时沿 next_command 读取余页。受沙箱限制的内置 Codex CLI shell 用现有的本地 stdio 传输运行读命令和续读命令。 读入口逐页校验摘要。快照丢失或摘要不符时,先恢复原始快照,再推进依赖它的工作。 v1 适配器继续接收完整的内联 work_contract,现有调用方也可通过 detail_ref.full_decision 读取原始 JSON。 如果日志绑定的是 cat 读命令,Windows Host 提示使用按字面路径读取同一 UTF-8 文件的 PowerShell 命令。

A DeepSeek Harness adapter lives in the loopx.hosts.dsh subpackage (run with python -m loopx.hosts.dsh; the legacy scripts/dsh_turn_host_adapter.py launcher still works); it uses the optional deepseek-harness-sdk Python client to run one bounded dsh session and parses the final assistant JSON message into the same typed Turn result. Prefer the built-in loopx turn run-once --host dsh surface so structured SDK terminal failures reach the Turn Journal. The module/subprocess invocation with --host generic-cli remains the compatibility and rollback path. See DeepSeek Harness connector.

Host Selection

The Turn host is selected, never inferred from an incidental environment. An explicit --host or LOOPX_TURN_HOST always wins; only when the operator configured neither is the shipped default resolved from the operator's own credential facts:

  • operator credential configured: the default host is the managed dsh executor, which that credential authenticates;
  • no operator credential configured: the default host is the individual codex-cli executor, because a managed host nothing can authenticate would otherwise refuse to run at all.
surface value
shipped default host, credential configured dsh (managed executor)
shipped default host, no credential codex-cli (individual executor)
explicit default selector LOOPX_TURN_HOST
per-command override --host codex-cli|claude-code|dsh|generic-cli (plan), codex-cli|dsh|generic-cli (run-once)
authenticating credential DEEPSEEK_API_KEY, optional endpoint DEEPSEEK_BASE_URL

Selecting the host is not the same as choosing what runs on it. The managed host resolves one managed execution profile — provider, model, and reasoning effort — with explicit precedence: an explicit argument (for example --dsh-model, --dsh-reasoning-effort) wins, then the operator's environment, then the product default.

execution profile field product default operator override legacy lower-precedence override
provider deepseek-official LOOPX_TURN_PROVIDER DSH_PROVIDER
model deepseek-flash LOOPX_TURN_MODEL DSH_MODEL
reasoning effort high LOOPX_TURN_REASONING_EFFORT —

The managed managed_executor readback reports the resolved profile as one line, <model>@<reasoning_effort> (the shipped shape is deepseek-flash@high). The provider is prepended as <provider>/… only when the resolved provider is not the shipped one, because dropping it for a deviating provider would make the line claim a profile the Turn would not use. Whichever values the line names are the values that run, so an owner-set model appears as itself rather than as the shipped default. The line stays one line because every plan and execution payload carries it and the agent-facing output budget is a contract; the field-by-field form, with each value's source and the variable that set it, belongs to the configuration readbacks a person reads.

An explicit argument the adapter cannot honour fails closed as invalid_reasoning_effort rather than being silently coerced, and the refused effort is named in the same line. Credentials authenticate the selected profile; discovering DEEPSEEK_API_KEY never changes provider, model, or effort on its own.

This is a default behavior change for the affected lanes. Both plan and run-once previously defaulted to dsh regardless of the credential, so a lane without one failed closed on operator_credential_unconfigured; the default is now credential-resolved and a lane without a credential keeps running on the individual CLI host. --host dsh remains the explicit managed path and still fails closed with the same typed reason when nothing can authenticate it, --host generic-cli remains the compatibility path, and a machine that wants one fixed host should set LOOPX_TURN_HOST once instead of relying on the ambient environment.

plan and run-once payloads carry the executor readback managed_executor (managed_executor_binding_v0): the executor and its kind (managed, individual, generic), the credential env var name (never its value), the endpoint env var name, whether the executor is operator-credential-bound, and whether it can launch here. When it cannot, available is false, unavailable_reason names the missing fact:

unavailable_reason meaning remediation
dsh_runtime_unavailable the DeepSeek Harness runtime is not importable and no explicit runner hook was supplied install the released runtime, pass its runner hook, or select --host codex-cli
operator_credential_unconfigured the managed host is selected but no operator credential or runner hook would authenticate it set DEEPSEEK_API_KEY, or select --host codex-cli explicitly; the shipped default already resolves to codex-cli until a credential exists
invalid_reasoning_effort the resolved execution profile names a reasoning effort the host adapter does not support pass a supported --dsh-reasoning-effort, or clear the overriding environment variable

The same readback also carries unavailable_remediation, which names those exits as typed codes so a caller does not have to parse the reason string:

unavailable_remediation exit it names
configure_operator_credential set the credential env var this readback reports as credential_env
configure_dsh_runtime install the released runtime, or pass its runner hook
correct_execution_profile pass a supported --dsh-reasoning-effort, or clear the overriding environment variable
select_individual_host select the individual host instead of the managed one

The list is empty for every launchable or non-managed executor, and naming an exit selects nothing: acting on it is still an explicit credential, profile, or --host change. The refusal run-once --execute returns on that verdict repeats the exits as remediation and adds the concrete remediation_host and remediation_env_vars.

run-once --execute fails closed on that verdict: status unavailable, no host invocation, no Journal write, and no quota slot spend. An explicitly selected individual host (--host codex-cli, --host claude-code) is billed to that individual CLI login and makes no launchability claim (available: null).

Five Questions For Any Agent CLI

Before wiring Trae CLI, Codex CLI, or another host, answer these five questions:

  1. How does it run unattended? Choose an explicit non-interactive command and workspace. If the CLI is interactive-only, it is not an isolated-headless adapter yet.
  2. How does it return one typed result? Prefer a native output schema or a dedicated result file. Do not scrape arbitrary conversation text as the completion contract.
  3. What is its resume handle? Keep the opaque handle in local adapter state, keyed by the declared scope: Goal/Agent for Codex exec by default, or Goal/Agent/Todo for isolated Todo context. Keep it out of public Goal narratives and evidence.
  4. Which failures may resume? A bounded timeout or lost transport may preserve an observed session. For agent-scoped Codex exec, a rejected startup contract, incompatible host version or missing session requires repair or explicit fresh context; it cannot silently fork.
  5. What proves the work independently? Name a command that checks the real repository, artifact, service readback, document revision, or other postcondition without trusting the agent CLI's own claim.

This yields one reusable integration shape:

TurnEnvelope
    -> host adapter -> agent CLI -> typed candidate result
    -> independent validator -> pass | repair | replan
    -> LoopX writeback -> one durable transition and one quota spend

A thin adapter can be implemented with this host-neutral algorithm:

request = read_one_json(stdin)
todo = request.turn_envelope.action.selected_todo
scope = request.session.context_policy.get("binding_scope", "todo")
session = load_local_session(goal_id, agent_id, scope, todo.todo_id)
prompt = render_bounded_prompt(todo, request.result_contract, temporary_result_path)
invoke_agent_cli(prompt, workspace, session, explicit_timeout)
candidate = read_and_shape_temporary_result(temporary_result_path)
write_one_json(stdout, candidate with request.turn_key)

render_bounded_prompt should tell the agent CLI to work only on the selected todo and write its candidate result to a dedicated temporary path. The adapter must reject a missing or malformed result instead of guessing from prose. It may discard raw conversation output after extracting the host's opaque session handle. LoopX then passes the candidate to a separate validator; the adapter does not call the work complete itself.

For a CLI with native structured output and resume support, the adapter is mostly field mapping. For a CLI such as a Trae installation whose selected command only returns conversational text, the wrapper must first establish a dedicated typed result channel; passing trae chat directly as the adapter is not sufficient. Check the installed CLI's help and pin the qualified command shape because flags and headless behavior may vary by version.

Managed Host Process Lifetime

The generic command executor and built-in Codex CLI adapter now share a TS process supervisor. Existing turn run-once commands need no new option. Node uses the same supported-version discovery as the control-plane runtime; the private request stream is limited to 8 MiB and is not a durable protocol.

A Host leader exiting, its output pipes closing and its descendants stopping are distinct observations. On POSIX, LoopX starts a dedicated process group, sends TERM and escalates to KILL after 300 ms, including when the leader has already exited. Normal result return also cleans up leftover group members. After KILL, the supervisor uses a one-second observation budget for group absence or an all-zombie group, observed through signal zero and POSIX ps group/state output. Zombies cannot execute and need not have been reaped by init. Live, stopped or unknown states remain non-terminal. Missing/failed observation or deadline expiry fails supervision instead of returning a normal Host result; a sent signal is not a cleanup certificate. No command timeout is extended.

KILL 后监督器以一秒观测预算核对进程组消失或只剩僵尸进程,通过零信号与 POSIX ps 的组号/状态观测判断。僵尸不能继续执行,不要求 init 已回收;存活、暂停或 未知状态仍非终态。观测缺失/失败或超时会报监督失败,不返回普通 Host 结果; 发出信号不等于清理完成,也不延长命令超时。

Host commands must not use that group to launch intended persistent services. Windows retains Python command-launch compatibility (including batch entrypoints) through a transport-only relay, then attempts tree termination before killing the leader. Windows uses best-effort process-tree cleanup; this delivery does not claim POSIX-equivalent cancellation or Windows qualification.

Timeout, output-consumer failure and loss of the owning Python process trigger cleanup. The control pipe remains open for the job lifetime; EOF cancels work. After leader exit, output drain is bounded (normally two seconds), rather than waiting indefinitely for inherited pipes. Generic stdout is capped at its existing 12,000-byte result budget while streaming. Codex output is consumed transiently with LF-framed records capped at 1,048,576 characters and a finite set of failure categories; an oversized record makes diagnostic observation incomplete. UTF-8 characters split across byte chunks remain intact. Raw Host output is not written to LoopX state.

Generic results require complete output and zero exit status. Codex retains its existing separate typed result-file contract: incomplete diagnostics do not invent a failure category, and a validated result file remains usable. Timeout still preserves the observed opaque session for the existing retry path. No process observation certifies Todo completion, refunds spend or rolls back an external effect; independent validation and settlement keep their owners.

This is process supervision, not execution authority or a sandbox. It does not renew provider leases, prevent stale remote side effects, cancel attached App sessions, or supervise in-process DSH execution. Descendants that escape the process group and killing the supervisor itself with SIGKILL are outside this boundary. Caller death can precede cleanup; the local lane lock alone cannot certify no overlap with a replacement executor. Authority-bound renewal, revocation and uncertain-effect recovery remain a separate delivery.

The Codex CLI and managed app-server operation hosts use a strict wire schema: all properties are required, and work/validation evidence is an array or null. Stop results send both evidence fields as null; the Codex boundary removes only those null placeholders before internal validation. Material results with an execution_profile must supply both evidence arrays; null or missing evidence is rejected at that boundary. Empty or malformed arrays still fail the existing executor validator. Legacy material results without a profile may omit evidence. Other host contracts are unchanged.

Repeatable Codex CLI Qualification

turn run-once --host codex-cli --codex-controller-worker-preview <subdir> selects an isolated source preview. Use --execution-mode isolated-headless, --iteration-context fresh, --codex-sandbox workspace-write, a finite --timeout-seconds, and the existing independent validation command. The physical subdirectory must match the admitted Goal and Todo write scopes. Both roles use that directory. The Controller receives the complete C1 input; the Worker receives the scoped instruction and returns findings and relative artifact references. The existing project permission profile limits both roles and disables native MCP tools for the preview.

The original Turn journal records the profile and the opaque native sessions observed for its Host attempt. turn inspect-journal projects the attempt and observed roles without session IDs. It reads the most recent atomic checkpoint while execution retains the mutation lock. --watch also emits changes to codex_role_preview.native_calls within a phase. Each role entry exposes the sequence of its latest recorded call and whether its result was observed. Calls are recorded before launch. A result that remains unobserved carries no guarantee that the process started or is still running. Older journals can omit these entries. During an attempt each native call resumes its own recorded role. After a Core interruption, resume the original Turn with --resume-turn-key, its original preview options, Codex profile and independent validator. Core can recover a final Controller result when the current native record shows that the exact Worker return reached that Controller and the matching native Turn completed. Recovery starts at independent validation and reuses the original attempt and quota identity. Missing, unfinished or later native Turns leave the original outcome unknown. A closed Turn replays its original receipt. Single-session execution remains the default for new Turns.

When a preview returns its final native result, the journal can also retain codex_role_preview.token_usage in readback. Each entry is the last verified cumulative token report for one session within the original attempt. Cached, cache-write and reasoning counters remain optional. Roles with incomplete or regressing reports appear in unobserved_usage_roles. The snapshot is read-only measurement evidence for the CLI and benchmark worker. Replay and recovery reuse it without repricing tokens or booking usage.

For a new Turn, keep the preview workspace and Codex profile and supply --iteration-context resume --codex-controller-worker-continue-from <turn-key>. The predecessor must be committed for the same Goal creation, Agent and session scope. Both role histories must still end at their matching native completions. The journal records the Worker delivery and the Controller input together before sending that input. A recovered Turn can qualify as a predecessor even when its final usage snapshot was lost. The new Turn passes the normal work, quota and scope checks and settles independently. For a resumed pair with an explicit model, the usage snapshot counts only requests attributed to the new Turn. A Goal without its original canonical creation receipt can still use the fresh preview.

--codex-controller-input enables one operator exchange on an explicitly selected local preview. turn submit-controller-input --execute takes UTF-8 input on stdin and the original Goal, Agent, Turn, Controller session, Worker sequence and operation ID. A queued receipt acknowledges storage. The authenticated Workbench read or inspect-journal with the original Controller match returns the answer once observed. A reserved input whose native outcome is unknown retains its operation ID for reconciliation. An observed executor loss closes intake for new inputs. Retrying an accepted input with the same operation ID and content returns its original receipt.

--codex-controller-worker-preview <subdir> 是显式选择的隔离源码预览。通过现有 turn run-once --host codex-cli 入口,使用 isolated-headless、fresh、workspace-write、 有限超时和独立校验。共享子目录须与原准入 Goal 和 Todo 的写入范围一致。Controller 接收 完整 C1 输入。Worker 接收有范围的指令,返回发现和工作区相对产物引用。 原 Turn 日志保存 profile 和本次 Host 尝试观察到的原生会话。turn inspect-journal 可以 读回尝试序号与角色,省略会话 ID。执行者持有修改锁期间,查看命令可读最近一次原子提交的 检查点。--watch 会在同一阶段内发出 codex_role_preview.native_calls 的变化,各角色仅 展示最近一次已记录调用的序号和是否观察到结果。记录先于启动,结果未观测时,调用是否启动 或仍在运行均无法从该记录确定。旧日志可以省略这些条目。每次角色调用恢复自己的会话。Core 中断后,用 --resume-turn-key 和原预览参数、Codex profile、独立校验器恢复原 Turn。只有原生记录 能证明同一 Controller 收到本次 Worker 回传、相同原生 Turn 已结束且已有最终结果, 才继续独立校验,沿用原尝试与额度身份。原生记录缺失、仍在执行或已有后继 Turn 时, 原尝试继续保持状态不明。已关闭的 Turn 重放原回执。新 Turn 仍默认单会话。

双角色预览交回最终原生结果时,日志可记录角色用量,在 codex_role_preview.token_usage 回读每个原会话最后一次核验过的累计 token 数。缓存、缓存写入和推理计数依原生报告提供。 报告不完整或计数回退的角色列在 unobserved_usage_roles。CLI 和 benchmark worker 从原回执读取这份测量。恢复和重放沿用快照,额度结算沿用原路径。

新 Turn 沿用预览工作区和 Codex profile,并提供 --iteration-context resume --codex-controller-worker-continue-from <turn-key>。 前驱已结算,且须匹配 Goal 原创建回执、Agent 与会话范围。两个会话末尾都须保留匹配的 原生完成记录。日志在发送 Controller 输入前一并写下 Worker 交接和 Controller 输入的指纹。 最终用量丢失时,已恢复的 Turn 仍可凭两份完成记录作为前驱。新 Turn 通过原工作、额度和 范围检查后独立结算。接续时显式指定模型,用量 快照只计入新 Turn 的请求。缺少原始权威创建回执的 Goal 仍可使用 fresh 预览。

--codex-controller-input 为显式选择的本地预览开启一次操作者交流。 turn submit-controller-input --execute 从标准输入读取 UTF-8 内容,并接收原 Goal、 Agent、Turn、Controller 会话、Worker 调用序号和操作 ID。入队回执确认内容已保存。 经认证的 Workbench 回读,或匹配原 Controller 的 inspect-journal,可读到已观测的 回应。已保留但原生结果未知的输入保留原操作 ID,供后续对账。 观测到执行进程失联后关闭新输入准入。用同一操作 ID 和相同内容重试已接受的输入时,返回原回执。

The repository includes an opt-in end-to-end qualification that creates an ephemeral LoopX project and workspace. Its default mode uses a no-model Codex fixture while exercising the built-in host adapter, independent validator, state writeback, one quota spend, and idempotent transaction replay:

python3 examples/loopx-turn-codex-cli-e2e-smoke.py

Use the real mode only when a local Codex login is available and one isolated model call is intended:

python3 examples/loopx-turn-codex-cli-e2e-smoke.py \
  --real-codex-cli \
  --codex-model <compatible-model>

The real mode emits only a compact LoopX qualification summary. LoopX does not copy the prompt, transcript, stdout, or stderr into fixture state, the temporary workspace and LoopX session binding are removed, and the disposable goal never syncs into the global registry. Codex CLI may retain its opaque host session according to local Codex policy so a later adapter turn can resume it. A compact codex_cli_model_requires_newer_codex failure is a host-compatibility result: the transaction must show zero state writes and zero quota spend; select a compatible model or update Codex before retrying.

Multiple distinct thread.started session IDs make a Codex CLI invocation ambiguous in both Agent and Todo scopes. LoopX rejects its result before persisting a session binding or settling the Turn. Repeated observations of the same ID are accepted.

Agent 和 Todo 作用域的 Codex CLI 调用如果通过 thread.started 报告多个不同的原生 会话 ID,LoopX 会在保存会话绑定或结算 Turn 前拒绝该结果。重复报告同一个 ID 可以正常处理。

For a coding collaboration, the validator may run focused tests and inspect the expected git diff. For operations, it may read back the declared resource state. For data work, it may check a schema and bounded quality assertions. For documents or knowledge maintenance, it may verify the target revision and required sections. These are different validators over the same Turn orchestration contract; they do not require different control loops.

Authority Boundary

Concern Authority
Goal, todo, claim, gate, quota, and cadence LoopX CLI and registry-backed state
Session creation, resume, cancellation, and tool execution External host adapter
Repository write isolation LoopX workspace guard plus repository policy
Validation Task-specific validator selected by the agent or adapter
Durable outcome and quota spend LoopX writeback after validation

The host must not infer a different action from status prose. It consumes a fresh loopx_turn_envelope_v0 decision and preserves its action signature. Full quota/status detail remains available through the envelope cold-path references.

Turn Lifecycle

One driver tick has exactly these ordered phases:

  1. Wake: resolve goal_id, registered agent_id, host kind, explicit execution mode, available capabilities, and an optional opaque session handle.
  2. Decide: run live quota should-run with the observed capabilities. A fixture is valid only in tests and shadow replay.
  3. Route: obey the envelope without invoking the host when the user channel requires action, work is throttled, a monitor is unchanged, or delivery is otherwise disallowed. Apply and acknowledge scheduler-only changes without spending quota.
  4. Prepare: preserve the selected todo identity, claim or lease when the contract requires it, and satisfy the workspace guard before any repository write.
  5. Execute: resume the declared host session only when the adapter marked it eligible, or create a new session when the execution mode permits it. Give the host the thin task body plus the current envelope, and request one bounded work segment.
  6. Validate: classify the host result and validate the claimed artifact or state transition. Host process exit zero is not validation.
  7. Write back: update or complete the current todo, create a repair or successor todo when required, and refresh state with compact public-safe evidence.
  8. Spend and schedule: spend one quota slot only after validated writeback, then apply and acknowledge the latest scheduler hint. Cadence-only work does not spend quota.

The driver may stop after any phase. A stop must return a typed result and must not silently continue with a different execution mode.

Executing admission entrypoints compose registered TurnStart observations before collecting the decision. The capability owns permission resolution, provider IO and bounded readback; the shared dispatcher validates the existing registration/result contract and isolates failures. Core Turn rendering consumes readback.summary_lines, without knowing the capability's domain. The same registration is used by executing quota guards and compatibility prequota. Read-only builders, plans, managed-step and original-journal recovery do not invoke new observations. An observer may establish a fact during a business wait or compute pause, but it cannot grant host execution or spend authority.

TurnStart results may carry bounded capability-owned readback without an Agent message-read obligation. Failed/partial/unavailable results may report unknown external reads or local effects as null; external writes remain an explicit boolean. If invocation precedes a rejected/lost result, the dispatcher retains uncertain_local_effects for declared local writes and callers refresh their decision projection. These extensions do not make post-writeback hooks effectful or authorize new provider writes.

执行准入入口在决策收集前组合注册的 TurnStart 观察。能力负责权限、provider IO 与 有界读回;共享 dispatcher 校验既有契约并隔离失败,核心 renderer 只消费通用 readback.summary_lines。执行 quota guard 与兼容 prequota 复用该注册。只读 builder、 plan、managed-step 和原 journal 恢复不添加观察。业务等待或额度暂停中的事实观察 不授予宿主执行或扣费权限。失败/退化/不可用结果可用 null 表示外部读取或本地效果 未知,远端写入仍须显式布尔声明。执行后响应丢失/被拒绝时,dispatcher 为已声明的 本地写入保留 uncertain_local_effects,调用方刷新决策投影;post-writeback hook 继续无效果,不由此获得 provider 写入权限。

One Executor Per Turn Lane

A Turn lane is one agent working one goal. Phase 5 launches exactly one executing Turn per lane: while an executing Turn holds the lane, a second executing Turn for the same goal and agent stops before the journal, the host, and quota, and returns the typed refusal instead:

{
  "status": "unavailable",
  "reason": "turn_lane_in_flight",
  "remediation": ["wait_for_in_flight_turn"],
  "in_flight": {"agent_id": "...", "operation": "loopx_turn_lane", "pid": 1234, "acquired_at": "..."}
}

in_flight names the holder so the operator can see what to wait for; the runtime path, the lock id, and the lock policy stay out of it. The fence is a kernel lock held by the executing process, so a crashed or killed Turn releases the lane instead of leaving a stale claim that no later Turn can enter, and a settled Turn releases it for the next Turn, including an idempotent replay.

Only an executing Turn takes the fence. A non-executing decision — a preview, or a route that stops before the host — invokes no host and spends nothing, so it always answers. Lanes stay independent: one agent on two goals, or two agents on one goal, do not contend.

Read-Only Journal Inspection

Maintainers can inspect one existing fenced journal without entering the live Turn lifecycle:

loopx turn inspect-journal \
  --goal-id <goal-id> \
  --agent-id <agent-id> \
  --turn-key <sha256:64-hex-digest> \
  --format markdown

The command resolves the canonical runtime journal path, reads it under the existing journal lock, and projects interpret_turn_journal into loopx_turn_journal_inspection_v1. It branches before status collection, quota construction, scheduler context, planning, host invocation, settlement, spend, or state writeback. Its effects field is therefore always an empty list.

recorded_effects separately reports lower-bound observations of the original Turn, not effects performed by this inspection or a recovery invocation. Boolean values mean checkpointed execution or no recorded attempt; null means unknown. A saved Host attempt precedes launch confirmation; a prepared writeback or spend is not a commit receipt. Inconsistent/foreign identity or phase lineage supplies only unknown effect facts. A scheduler phase does not imply host acknowledgement.

host_attempt_runtime reports the LoopX release identity captured with each Host reservation. Join its identities to host_attempt_usage using the attempt number from the same Turn. A verified installed snapshot can have an identity before launch and even when usage is unavailable. Earlier or unqualified reservations count as unidentified_attempts when the section is present. The section is absent when no identities were captured. Inspection and replay use only the saved identities. A retry records its own runtime release.

host_attempt_runtime 随 Host 尝试预留记录当时运行的 LoopX 发布标识。通过同一 Turn 的尝试编号,可将 identities 与 host_attempt_usage 关联。来自已核验安装快照的标识 可先于启动落盘,也可在用量缺失时回读。该字段出现时,旧尝试或来源无法核验的尝试计入 unidentified_attempts。没有采集到发布标识时省略该字段。检查和回放使用已保存的标识, 重试记录自己的运行版本。

host_attempt_usage reports the numbered Host attempts with observed token counts. The Codex CLI path requires an explicit model and one complete Turn with valid counters. Input includes cached input. A fresh session uses its completion event and the configured model label. For a resumed CLI session, LoopX resolves the indexed rollout from its selected native home and checks the newly appended records for exactly one completed native Turn and the original prompt. Its unique native requests must reconcile with the recorded Turn counters and the completion event's cumulative thread total. Attempts lacking this evidence remain unobserved_attempts. The journal stores compact counts with the existing attempt identity. A saved attempt can precede launch. Older journals may omit this section. The inspection records neither USD nor an extra Goal ledger entry. Replaying a saved result leaves the original observations intact.

host_attempt_usage 按实际记录的 Host 尝试编号回读 token 用量。原生 Codex CLI 在显式配置模型且返回一轮完整、计数有效的结束事件时可归因。 输入 token 包含缓存命中部分。恢复会话时,从已绑定的原生索引定位文件,核对本次追加 记录中唯一完成的宿主回合与实际输入,并以逐请求用量复核该回合计数和结束事件里的会话 累计值。来源无法核验时计入 unobserved_attempts。日志沿用原有尝试标识来记录计数。预留尝试可能还未启动, 旧日志可能没有此字段。检查回执只读,不估算美元费用、不追加 Goal 用量账本, 回放保留原有观测。

The inspector and journal writer share the original TS prepared-intent contract: one supported step, object shape, prepared status, exact settlement effect ref, the next phase and a nonterminal status. Unknown or malformed intents block the existing recovery decision, including Host reinvocation. Valid lineage's already completed effects remain proved; other effects are unknown, not false. The writer's empty-map rejection is retained: no pending intent uses an absent field; committed history is carried by completed checkpoints, not retained intents.

Python-origin journal snapshots remain JSON objects through that same TypeScript writer. They reuse context delivery's sparse numeric IO metadata and validator to preserve integral floats, signed zero and unsafe integers before atomic publication. Replay and immutable-plan comparison distinguish these source numbers; refusals retain the original file. Ordinary objects without metadata retain their encoding and operation identity; historical receipts are not rewritten. This remains one RPC under the shared 8 MiB request limit and avoids double escaping evidence text. Metadata still costs bytes for number-dense sources. Source fidelity and transport checks do not establish latency or long-horizon benefit.

Python 来源的 journal 快照仍经同一 TypeScript writer 传递 JSON 对象,复用 context delivery 的稀疏数值 IO 元数据与校验器,在原子发布前保留整值浮点、带 符号零和非安全整数。重放与不可变 plan 比较区分这些来源数值;拒绝时保留原 文件。无元数据的普通对象保留已有编码与操作身份,不改写历史回执。仍为一次 RPC,沿用共享的 8 MiB 请求上限,避免证据正文的双重转义;数值密集来源仍有元数据 字节成本。来源保真与传输检查不代表延迟或长程收益已得到验证。

If executing run-once raises unexpectedly, its error response retains the original error and resume key, marks uncertain current-invocation effects as null, and adds journal_observation from this same read-only TS owner. Its scope=original_turn prevents a saved Host result being mistaken for another launch. Unavailable inspection remains explicit; there is no Python fallback. Use the original recovery_decision and provider readback to recover, never a fresh task or repeated model call inferred from a failed CLI reply. This readback does not bypass controller completion validation, lease conflicts or quota gates. Pre-execution failures retain known Turn-start hook writes without claiming Host execution. Normal successful/replayed effects remain invocation-scoped.

When a prior unsettled Turn blocks run-once, resume_turn_instance_id names the original Turn with a verified dispatch journal. Receipt-only recovery keeps the owning guard or typed closeout instructions in next_cli_actions.

中文:recorded_effects 是原 Turn 的持久观察,不是本次检查或恢复又发生了副作用。 null 表示未知:已登记 Host attempt 不等于模型已启动,prepared 不等于写回或扣额 已提交。异常返回保留原错误/恢复身份,以同一 TS owner 的只读 journal_observation 区分本次调用与原 Turn;读回失败不猜测“没有执行”。按原恢复判定和 provider 回执 继续,不能因 CLI 报错新建任务重跑模型,也不放松验收、租约或扣额门禁。 原 Turn 未结算而阻止 run-once 时,resume_turn_instance_id 指向已核实派发日志 的原 Turn。只有准入回执的恢复沿 next_cli_actions 提供的原准入或类型化收口指引继续。 检查与写入共用原 TS prepared-intent 合同,校验步骤、形状、状态、effect 身份和 阶段绑定。未知或畸形 intent 阻断原恢复判定,不能建议重调 Host;保留合法身份与 阶段已经证明的执行事实,其余返回未知而非 false。不放松原 writer 的空 map 拒绝语义:无待决 intent 应省略该字段,已提交历史由完成 checkpoint 表达。

Exit zero means that inspection completed, including when decision is replay_blocked. A non-zero exit means the command could not inspect the requested journal because a selector, file, JSON document, or schema was invalid. This surface is diagnostic evidence only: it grants no authority to resume, retry, settle, schedule, spend, or write, and it is never an execution gate. Settlement replay enforcement remains owned by the Turn executor.

Version 1 separates two questions that version 0 exposed through replay fields alone:

  • replay_legal says whether a terminal Journal can be reinterpreted without effects; it is not recovery permission.
  • recovery_decision is the plan the real executor consumes for an existing Journal: action, can_continue, resume_from, reinvoke_host, a typed reason, and the checks that actually participated.

journal_consistent also requires a complete canonical typed settlement identity. Its goal and agent must match the Journal, envelope, and requested owner; its Turn instance must match the transaction; and its binding and effect id must validate under the settlement schema. A Todo binding must also match the envelope's authoritative selected Todo, including the adaptive primary Todo override. A mismatch therefore produces a blocked recovery decision before Host or any settlement provider is called, even when the completed phase prefix would otherwise resume at durable writeback or a later effect. A Todo-less autonomous-replan Journal instead retains the original signed quota settlement plan and matching obligation. The shared TypeScript envelope owner checks that binding for both planning and Journal recovery; a missing Todo never supplies it.

For example, an in_progress Journal with a saved Host Result has replay_legal=false but may continue from validation without another Host call. scheduler_action_required continues from scheduler_apply and does not repeat Host, writeback, or quota spend. A failed Host Session is evaluated only when --retry-failed-turn is explicit and must pass the current Session Binding check. Retryable Host failures also carry a content-free loopx_turn_host_failure_v0 record. The Journal persists the attempt before Host invocation, and the TypeScript recovery decision rejects another invocation after the declared bounded budget. Backoff is an outer-scheduler hint; run-once never sleeps in-process or silently changes the selected model. The default run-once Markdown readback shows every recorded Host failure's kind, retryability and attempt, plus the retry ceiling and backoff when present. These are the existing journal facts, not permission to launch another attempt: even a retryable class may have exhausted its budget. Replaying the original Turn exposes the same diagnostics without re-running the Host. JSON and the admission policy are unchanged; raw provider messages are not added to readback. A dangling prepared effect remains owned by the existing provider readback protocol; the recovery decision only records that the readback is the next required check and does not claim general exactly-once execution.

An in_progress Journal without a saved typed result may invoke Host only when its durable host_attempt_count is exactly zero. A positive, missing or invalid counter means host_outcome_unknown: recovery is blocked even with --retry-failed-turn. Reconcile the original execution and downstream effects; do not clear its journal or create a replacement settlement identity. New journals record zero before dispatch intent. Recovery also rechecks the current Goal lifetime for legacy registrations, without rerunning quota admission. Retired Goals are unsupported for executing recovery, including terminal receipt replay. Refusal preserves the original journal and any committed debit; read-only inspect-journal remains available. Active Goals retain original-receipt replay without another Host invocation or debit. This check does not provide continuous external-tool fencing.

中文:in_progress 且未保存 typed result 时,只有持久化的 attempt 计数明确为零, 才可调用 Host。正数、缺失或无效计数返回 host_outcome_unknown;显式重试也不能 绕过。先核对原执行与下游结果,不清空 journal,也不另造结算身份。新 journal 在 派发意图前保存零值。恢复旧格式 Goal 时也检查当前生命周期,但不重新准入额度。 退役 Goal 不支持执行恢复,包括终态回执重放。拒绝时保留原 journal 与已提交扣费; 仍可通过只读 inspect-journal 查看历史。有效 Goal 继续复用原回执,不重新调用 Host 或扣费。此检查不提供外部工具的持续围栏。

When an existing Journal is continued, run-once persists one bounded loopx_turn_recovery_audit_v0 record. Its planned value is the adopted shared decision; its actual value distinguishes started from finished and records only final Journal status, completed phase ids, and whether this recovery invoked Host. inspect-journal exposes that record as last_recovery. Raw Host output, Session data, effect payloads, credentials, and local paths remain excluded.

User-Gate Quiet Wait

When the user owns the next step and the agent lane has no executable work, the decision envelope carries an execution obligation of kind user_gate_quiet_wait with must_attempt_work=false and delivery_allowed=false. This happens when at least one open user-action todo exists while the agent lane exposes no first executable item, and no agent replan obligation takes precedence.

A quiet-wait envelope is not a stall:

  • the host must not invoke the model, send prompts, retry with backoff, or consume a heartbeat spend;
  • the host must not report a stall, session failure, or dead-process risk for a driver that is correctly waiting at this obligation;
  • the driver stays quiet until the projected user action clears the frontier or a later decision rotates the obligation (for example to a replan or a fresh runnable todo).

The obligation is machine-enforced by the control plane, not host prose: the host reads must_attempt_work=false from the typed obligation and preserves the quiet wait without re-deriving an action from status text.

For material results, schema-valid host output is only candidate evidence. The caller or adapter must select an independent task/postcondition validator before host execution. The generic CLI accepts a trusted JSON argv array, passes the normalized host result on stdin, never invokes a shell, and discards validator stdout and stderr. A missing, failed, or inconclusive validator stops at validation_failed, records a typed repair_required or replan_required recovery disposition, and cannot write state or spend quota. Typed stop results do not require task validation because they produce no material writeback.

An independent callback validator may distinguish terminal completion from validated intermediate progress. status=passed means the declared terminal postcondition holds and uses exit code 0. status=progress means a bounded, task-facing postcondition is independently proven but the terminal postcondition is still open; it uses an explicit non-zero marker. Both statuses may commit exactly one Turn and one quota spend. Only progress permits a host adapter to start another Turn, and only under a predeclared maximum, shared total time budget, and no-feedback continuation policy. Every other validator status fails closed before writeback.

Adapters that lack a separate terminal signal may declare a bounded fixed-n terminal policy. Under that policy, each successful independent validator call proves progress, while only a successful final configured Turn satisfies the sequence terminal postcondition. The default validator policy continues to interpret exit code 0 as per-Turn terminal completion. Within a bounded multi-Turn sequence, a successful Turn that also proves a durable content change receives one further blinded review Turn before sequence termination; the next successful no-change Turn may terminate early. The policy is explicit in public-safe runner prerequisites and never changes benchmark scoring.

Turn Input

The driver input is a small composition of existing contracts:

{
  "schema_version": "loopx_turn_request_v0",
  "goal_id": "example-goal",
  "agent_id": "codex-worker",
  "host": {
    "kind": "codex_cli",
    "execution_mode": "interactive_visible",
    "session_handle": "opaque-local-handle"
  },
  "wake": {
    "reason": "scheduler_due",
    "turn_key": "stable-idempotency-key",
    "available_capabilities": ["shell", "filesystem_write"]
  },
  "decision": {
    "schema_version": "loopx_turn_envelope_v0",
    "action_signature": {
      "matches": true
    }
  }
}

session_handle is local adapter state. It must not be committed, copied into LoopX public state, or treated as identity authority. The stable control-plane identity is the original quota settlement binding: Goal/Agent/Todo/Turn, or Goal/Agent/autonomous-replan obligation/Turn for admitted empty-frontier planning.

Adapters may support two explicit execution modes:

  • interactive_visible: user-visible and interruptible; never falls back to hidden execution.
  • isolated_headless: an explicitly selected experiment or worker mode in an isolated workspace; never claims to preserve an interactive TUI.

Mode selection is input policy, not a retry heuristic.

Typed Result

Every attempted tick returns one result kind:

Result kind Meaning Required next state
validated_progress One bounded segment produced validated evidence. Update current todo, refresh, spend once.
validated_completion Acceptance for the current todo is met. Complete todo with exactly one typed continuation (successor, active_goal, or no_followup), refresh, spend once.
repair_required The todo remains sound but a recoverable execution defect blocks it. Keep or create a concrete repair todo; do not mark success.
replan_required The current route is exhausted or incompatible while the goal acceptance gap remains. Write a bounded todo delta or vision replan trigger.
user_action_required A concrete user decision, payload, or credential action is projected. Notify with the projected action in the configured operator language; no host run and no spend.
wait Quota, monitor, scheduler, or another typed wait contract applies. Preserve state, apply cadence if needed, no spend.
iteration_failed This bounded iteration did not satisfy its task-facing outcome, and no continuation was requested. Stop this iteration without retry, successor, writeback, or spend; a later iteration requires a new decision.
host_failure The host could not start, resume, or finish a turn. Record the failure class and retry or repair policy.
validation_failed Host output exists but task validation failed or is inconclusive. Preserve failure evidence and route to repair/replan.
writeback_failed Validated work could not be durably recorded. Do not spend; retry idempotent writeback before more delivery.

Managed host adapters carry the existing path-delta fields through the typed result unchanged: path_delta_mode, agent_vision_json, and vision_unchanged_reason. A material path change uses path_delta_mode: "material_replan", result_kind: "replan_required", and a JSON-encoded goal_vision_replan_contract_v0 packet whose goal_path_delta_v0.outcome is replan; it must not also claim an unchanged reason. An unchanged path uses path_delta_mode: "unchanged" with either a bounded vision_unchanged_reason to reuse the current checkpoint, or a fresh vision packet whose goal_path_delta_v0.outcome is continue or no_change. The fresh packet carries evidence for progress or completion while retaining the route; it must not also declare vision_unchanged_reason. A fresh packet requires an explicit path mode: omitting it retains the legacy inference of material_replan. The Turn executor remains the owner of packet parsing, bounds, and semantic validation. These declarations do not grant write or Goal authority, and legacy hosts that omit both path-delta fields retain their prior compatibility behavior. For material results, an explicit null or other non-string value for either path-delta field is invalid; omitting the field remains distinct from supplying null. Stop results (wait, user_action_required, and iteration_failed) do not declare a path delta. Managed dsh and optional-cloud prompts may omit both fields; the Codex CLI output schema requires both strings, so empty strings express the same no-declaration result. The executor accepts those empty strings and rejects non-empty stop-result declarations. The shared material validation applies to generic CLI, Codex CLI, dsh, and optional-cloud host results.

Shared dsh/optional-cloud adapters preserve candidate text through the existing Turn result limits. They must not truncate a supplied classification, summary, next action, recommendation or unchanged-path reason to make it pass validation: a trailing constraint can change the meaning. The executor rejects over-limit text before task validation, durable writeback, quota spend or scheduler ACK. Generated adapter diagnostics remain bounded. Existing transport/output limits still apply, and a failed result does not undo work the Host already performed. Candidate text fields retain their JSON types until validation: booleans, numbers, arrays and objects are rejected, including false, zero and empty containers. They must not become instructions through string coercion or missing-field fallbacks. Legacy null/omitted optional text keeps its absence semantics; sparse adapter candidates retain their established defaults. Explicit delivery_batch_scale and delivery_outcome also pass through to their existing validators; only omitted metadata uses the legacy single_surface / outcome_progress defaults. The adapter must not replace a declared result with progress or accept read-only scale aliases for new writes. Valid vocabulary does not establish a qualifying settlement. For new material Host results, the validator reuses the existing settlement rule before task validation or effect preparation. surface_only and outcome_gap return validation_failed at host_result_contract: observation transport does not add a no-spend Host closeout. The failed journal retains no prepared writeback; ordinary replay has no effects, and a corrected candidate needs a new Turn or an explicitly admitted failed-result retry. Historical cached results keep their provider readback and settlement recovery; a possibly committed effect cannot be discarded by this new-candidate check. Ordinary CLI typed-blocker settlement remains unchanged. Valid declared scales reach durable history unchanged.

共享 dsh/可选云端适配器保留候选结果的完整文本,交给现有 Turn 结果校验器判定上限; 不得截短分类、摘要、后续行动、建议或路径不变理由以使其通过,否则可能丢失末尾约束。 超限结果在任务验证、持久写回、quota 扣费和 scheduler ACK 前被拒绝。适配器生成的 诊断仍有界,原传输和输出上限保留;结果被拒绝不会撤销 Host 已经执行的工作。 候选文本字段保留原 JSON 类型直到校验;布尔值、数字、数组和对象(含 false、零和 空容器)会被拒绝,不得经字符串转换或缺字段兜底变成行动。旧 null/省略的可选 文本继续按缺省处理,稀疏适配器候选保留既有默认值。 明确提供的 delivery_batch_scale 与 delivery_outcome 也原样交给既有校验器; 只有省略元数据时才使用旧 single_surface / outcome_progress 默认值。适配器 不得将所声明结果替换为进展,也不得让只读 scale 别名用于新写入。词汇合法不代表 满足结算条件。新材料 Host 结果在任务校验或效果准备前复用既有结算规则: surface_only 与 outcome_gap 返回 host_result_contract 阶段的 validation_failed;新增的 observation 传输不扩展 Host 的免扣额收口路径。 失败 journal 不留下 prepared 写回;普通重放无效果,修正候选须通过新 Turn 或明确 准入的失败结果重试。历史缓存结果继续走 provider 读回和结算恢复,不能由新增候选 校验丢弃可能已经提交的效果。普通 CLI 的 typed blocker 结算保持原行为。合法声明 的规模原样进入持久历史。

The existing TypeScript Vision normalizer owns packet interpretation and emits the canonical goal_vision_replan_contract_v0 shape. Its current compatibility behavior does not verify the submitted packet's top-level schema_version; the nested path_delta.schema_version remains optional, and when present the existing owner requires goal_path_delta_v0.

Settlement identity decoding / 结算身份解码

Executable settlement decodes exactly one Todo or autonomous-replan binding in effect_program.ts. Goal, Agent, Turn and active binding IDs must be non-empty strings. Declared binding_kind and binding_id must agree with that target; scoped v1 requires both fields. Unknown declared versions and v0 replan records are rejected. Legacy Todo v0 records may omit binding metadata, and supported schema-less adapter records remain readable. Generated payloads and effect IDs are unchanged; unbound planning identities cannot authorize settlement.

This tightens previously permissive malformed-input handling: invalid identities return invalid_identity before writeback, spend or receipt replay. Journal inspection reports settlement_identity_invalid and blocks recovery without rewriting the stored record. A valid shape still needs current authority and the existing commit-time fences.

可执行结算由 effect_program.ts 解码唯一的 Todo 或自主 replan 绑定。Goal、Agent、 Turn 及有效 target ID 必须是非空字符串;声明的 binding_kind/binding_id 必须 与 target 一致,scoped v1 必须同时提供两者。不支持的声明版本和 v0 replan 记录会 被拒绝;旧 Todo v0 可省略 binding metadata,支持的无 schema adapter 记录继续 可读。生成的 payload 和 effect ID 不变,unbound 规划身份不能授权结算。

本修订收紧此前宽松的损坏输入处理:非法身份在 writeback、扣额或 receipt replay 前返回 invalid_identity。Journal inspection 报告 settlement_identity_invalid, 阻止恢复且不重写记录。合法结构仍需通过当前权限及已有 commit-time fence。

Receipt-bound planning without a Todo / 无 Todo 的回执绑定规划

When the native quota owner requires a genuine autonomous replan with no selected Todo, turn run-once --host codex-cli --session-scope agent can execute it with an explicit --turn-instance-id. The existing Agent conversation, independent validator, journal, writeback and quota owners retain the same Goal/Agent/ obligation/Turn identity. The launch boundary rereads current admission. A successful resume through --resume-turn-key reads the original result and effects; it does not repeat Host work or debit another slot. No surrogate Todo or Todo completion is created.

The signed plan and semantic obligation must agree. Missing, conflicting or corrupt identity/source evidence refuses execution or recovery. Without a genuine replan binding, ordinary Todo-less work remains unbound. Todo-scoped sessions and other Host adapters retain their existing no-Todo refusal. Selecting the existing --session-scope todo retains that boundary; no new execution configuration or scheduler is introduced.

Material Host results may supply progress_observation_json, a JSON string of at most 4096 characters using the existing typed_progress_observation_v0 contract. The adapter preserves it, the existing normalizer validates it, and refresh-state judges it against the original obligation. Use observed result_class, surface/hypothesis/probe or blocker/coverage identifiers, and opaque evidence_ids; prose and successful process exit do not establish a semantic delta. Independent task validation still must pass. Omission or an empty string preserves prior behavior. A normalized observation is retained with the original Host result for recovery; a stop result cannot carry one.

This qualifies the native planning/settlement transport. Ordinary Inbox request admission, trusted idle wake, busy queue handling, App presentation and an installed original-message-to-conclusion journey remain separate delivery work. An Inbox message cannot be relabeled as an autonomous-replan obligation to use this path.

原生 quota owner 确认需要自主重规划且没有选中 Todo 时,既有 Codex Agent 会话可用 显式 --turn-instance-id 执行该规划。Host、独立校验、journal、写回和扣额始终保留 原 Goal/Agent/obligation/Turn 身份,启动前重读当前准入;按原 --resume-turn-key 恢复只读回原结果和效果,不重跑 Host、不重复扣额,也不造 Todo 或调用 Todo 完成。签名计划、语义义务或来源证据缺失、冲突、损坏时拒绝。普通无 Todo 请求不因此获权;Todo 会话及其他 Host 仍保留原拒绝边界。

材料结果可提供不超过 4096 字符的 progress_observation_json,复用既有 typed_progress_observation_v0。原 owner 规范化并对照本次原义务判断,独立校验仍须 通过;摘要或进程成功不能代替语义变化。省略或空串保持旧行为,规范 observation 随 原 Host 结果持久保存供恢复,停止结果不能携带它。这只是原生规划和结算传输的验收; 普通 Inbox 准入、可信空闲唤醒、忙碌队列、App 展示和安装态原消息到结论仍待各自交付, 不能伪造 replan 义务代替原请求。

In-flight Turn settlement / 在途 Turn 结算

A Todo can stay open across several bounded Turns. An exact accountable outcome_progress writeback with an accepted vision_checkpoint_v0 in_flight_continuation boundary discharges that Turn's progress obligation, not the Todo's terminal acceptance. With its matching durable writeback and quota-spend receipts, the original Turn replays as heartbeat_settled_skip: no more work and no second debit. Without the spend receipt it remains settlement_pending; a missing writeback receipt, unaccepted checkpoint or wrong Goal/Agent/Todo/Turn cannot prove settlement. A plain progress claim or semantic_closeout checkpoint is not this exception.

Todo 可以跨多个有界 Turn 保持开放。与原始身份精确绑定的 outcome_progress 写回,只有携带已获准的 vision_checkpoint_v0、in_flight_continuation 边界和 当前 Todo 的 trigger,才履行该 Turn 的进展义务,而非 Todo 的最终验收。有匹配 的写回和扣额回执后,同一 Turn 返回 heartbeat_settled_skip,不得再次执行或 重复扣额;缺少扣额回执时仍是 settlement_pending。缺少写回回执、未获准 checkpoint 或错配 Goal/Agent/Todo/Turn 均不能证明结算,普通进展声明或 semantic_closeout 也不能替代这项凭证。

Waiting conditions and frontier/successor changes do not reopen a settled Turn. A fresh Turn must recompute admission to continue the open Todo or select an independent successor. The Todo's completion validator, definition revision, leases and Goal acceptance remain authoritative and unchanged.

等待条件和 frontier/后继变化不能重新打开已结算 Turn。继续开放 Todo 或选择 独立后继必须用新 Turn 重新准入。Todo 完成验证器、定义版本、租约和 Goal 验收 仍由原权威负责,不因在途结算而放宽或改写。

validated_completion is admitted only when the Turn caller supplies an explicit Todo lifecycle adapter. After independent validation, the adapter must authorize and complete the selected Todo through the existing Todo lifecycle, then return a compact outcome for that same Todo: linked successors, an authorized no_followup record, or active_goal continuation. The durable Turn journal records that outcome before quota spend. A Todo completion alone never terminates the goal; a fresh decision owns successor selection and goal termination.

Every newly completed Todo persists completion_continuation and an opaque completion identity explicitly. The value must agree with its durable relations: successor requires at least one successor_todo_id, no_followup requires no_followup=true, and active_goal requires neither. A completed record that omits the field is not interpreted as active_goal; it fails closed until an agent explicitly repairs it by replaying loopx todo complete. The only post-completion transition is the narrow #3261 recovery seam: during the original quota-bound completion_turn_key, an explicit active_goal may be upgraded to no_followup after the matching writeback and spend receipts exist. The recovery records completion_recovery=same_turn_terminal_closeout; it cannot cross a Turn or replace a successor. A completion made outside a quota Turn instead persists a TS-derived local_completion_* identity. When a strict refresh-state rejection later proves that only Todo lifecycle settlement is missing, it may project that exact key through --completion-identity-key. The completion fence accepts this distinct lifecycle_reentry_terminal_closeout only for the matching completed Todo with active_goal, no successor, and an authorized lifecycle actor. It does not reinterpret the local key as a quota receipt or permit arbitrary cross-Turn terminal replay.

After legacy state is promoted to a canonical provider, this lifecycle-only closeout uses its own stable closeout operation receipt. The authoritative completed Todo supplies the original identity even when its pre-promotion completion has no native operation receipt. The transition preserves the original completion timestamp, evidence, validation commitment, completion receipt and quota history. It neither resolves nor reruns the old validator. Only continuation metadata changes; new results, successors, ownership edits, replacement evidence, a mismatched identity or an active execution lease are rejected. Exact retry recovers the closeout receipt, including after a lost response. This does not relax the original Turn's writeback/spend ordering. Quota-bound identities must resolve through original durable settlement receipts and pass the existing settlement readback; missing history rejects. Only the exact TS-derived local completion identity is exempt from quota readback. Historical closeout replay still precedes fresh authority lookup.

旧状态迁移到 canonical provider 后,这类生命周期收尾使用独立、稳定的收尾操作 回执。即使迁移前的完成记录没有 native operation receipt,也从权威已完成 Todo 读取原始身份,只更新 continuation 元数据;原始完成时间、证据、验证声明、完成 回执与 quota 历史保持不变,不重新解析或执行旧验证器。身份不符、新结果、后继、 所有权或证据修改,以及仍持有执行租约的请求均拒绝。响应丢失后的精确重试恢复 已有收尾回执,不放宽原始 Turn 的 writeback/spend 顺序。 绑定 quota 的身份必须从原始持久回执解析,并通过既有 settlement 读回;历史缺失 时拒绝。只有精确匹配 TS 生成的本地完成身份才能免除 quota 读回。已提交收尾的 历史重放仍先于新的权威检查。

repair_required and replan_required are distinct. Repair preserves the current task intent. Replan changes the runnable todo set or route because the existing task no longer advances the goal. Replan is required when any of the following is true:

  • no runnable todo exists while the active vision still has an acceptance gap;
  • the selected todo is terminal, obsolete, or incompatible with observed host capabilities;
  • validated negative evidence invalidates the current route; or
  • two eligible turns produce no material progress through the same route.

A driver must not terminate merely because one todo ended. Goal termination requires goal acceptance evidence, an explicit user stop, or a typed blocked state with a concrete projected action.

Recoverable Failure Classes

Failure class Driver behavior
auth_required Stop for the concrete credential action; never read or upload credentials.
session_unavailable Return host_failure; retry resume or start a new session only if the selected mode permits it.
capability_missing Re-run decision with observed capabilities and use capability repair routing, not a fabricated user gate.
workspace_guard_denied Repair or relocate the workspace before writes.
executor_timeout or transport_lost Return host_failure with bounded retry metadata; do not infer completion.
provider_capacity, provider_overloaded, or rate_limited Prefer an exact structured provider code, otherwise use a bounded adapter-local diagnostic fallback. Preserve only the typed class, exact attempt, same-configuration strategy, bounded exponential backoff, and maximum attempts. Never persist provider prose or silently select another model.
quota_exhausted Treat hard plan, billing, or included-usage exhaustion as non-retryable repair. Do not collapse it into a timed rate limit.
result_missing Return validation_failed; a process exit without typed result is inconclusive.
validation_failed Preserve compact negative evidence and choose repair or replan.
writeback_failed Retry idempotent writeback; never spend first.
scheduler_apply_failed Preserve completed writeback, record cadence failure, and retry scheduler control without a delivery spend.

Structured failure discrimination is fail-closed. A known error.code wins over HTTP status and prose. An unknown non-empty code becomes unknown and routes to repair; it must not be reinterpreted from its message. HTTP 429 is a bounded rate_limited signal only when no more-specific provider code exists, so an insufficient_quota response remains non-retryable even when transported as HTTP 429. Current codex exec --json releases expose message-only error events, so diagnostic matching remains the live compatibility path for that adapter; structured Responses, app-server, and JSON-RPC envelopes are accepted as forward-compatible inputs but are not claimed as fields emitted by the current exec JSONL contract.

Session recovery is fail-closed:

Host observation Session disposition Next Turn
Typed result returned Keep the opaque session eligible. Resume within the selected conversation scope; refresh current Todo inputs.
Timeout or transport loss after a session was observed Keep it eligible, but do not infer progress. Retry the side-effect-safe host phase.
Incompatible host version or rejected startup/output contract Agent-scoped Codex exec retains the binding and fails closed; Todo scope invalidates it. Repair, then explicitly select fresh for agent scope.
Host reports the session is missing Agent-scoped Codex exec retains the binding and fails closed; Todo scope invalidates it. Repair history or explicitly select fresh for agent scope.
Failure before any session was observed Store nothing. Re-decide, then start fresh only if allowed.

Session eligibility is recovery metadata, not evidence that work happened. It never bypasses a fresh Turn decision, task lease, independent validation, or writeback ordering.

Cross-Iteration Context Policy

For a ready Codex CLI Turn, turn plan --include-transaction-detail observes the same scoped native binding as turn run-once. Planning is read-only. Execution rechecks the Goal lifetime and binding before dispatch.

对已就绪的 Codex CLI Turn,turn plan --include-transaction-detail 和 turn run-once 查询同一范围内的原生会话绑定。计划查询只读。执行在启动宿主前 复核 Goal 实例和会话绑定。

Each turn plan or turn run-once invocation declares an iteration context policy independently from the Todo and Goal lifecycle:

  • resume is the CLI default. The first invocation starts a session; later invocations reuse its exact native ID. The retired context name is rejected.
  • Codex exec defaults to --session-scope agent: the same Goal and Agent keep their conversation when Todos change. --session-scope todo explicitly isolates conversations per Todo. These scopes use separate persistence keys; existing Todo-scoped bindings are not automatically adopted into agent scope.
  • fresh starts a clean session. After a native ID is observed, that session normally replaces the binding for the selected scope, including on timeout. It implies no new Todo, successor, retry, progress or Goal.

When an opt-in EpochReset supplies the fresh Codex exec context, the observed session remains a candidate until independent validation passes and the original Turn settles. A failed Turn keeps the previous binding. The final write compares that binding with the original snapshot. If a newer binding exists, it wins. session_binding_updated reports the result of this adoption when attempted.

显式启用的 EpochReset 为新的 Codex exec 会话提供上下文时,独立验收通过并完成 原 Turn 结算后才采用候选会话。失败时保留原绑定。写入时对比原绑定快照,已有更新 的绑定优先。session_binding_updated 回报实际尝试采用的结果。

The Codex exec binding includes the exact Goal lifetime where available and a profile digest for agent scope: workspace, Codex home/settings, executable, model, effort, sandbox and MCP configuration. A corrupt/incompatible binding, missing native history or unexpected resumed ID fails closed; it cannot silently fork. A read-only agent-scoped exec session may resume with workspace-write when that is the only profile change and the current registry records an unexpired operator checkpoint approving the entire working directory. The Agent must remain registered in the active Goal; file-only, sibling, expired, malformed-expiry or projection-only approval is insufficient. Expiration is optional: omitted, null or blank expires_at/fresh_until retains no expiry. The first nonblank expires_at, or its fresh_until compatibility alias, must be an ISO timestamp string with a representable UTC instant. Invalid supplied expiration makes the checkpoint inactive in the shared normalization owner; it cannot authorize a write resume or add projected write scope. A valid expires_at takes precedence over the alias. Other profile changes retain the explicit fresh gate. Configure the approval through configure-goal --boundary-authority-scope DIRECTORY/** --boundary-authority-source SOURCE and preview before --execute; it grants neither publication nor production actions. This transition preserves the native Session and updates its profile digest only after the same native ID is observed. Current Turn selection, task lease, validation and settlement remain Todo-bound. Session scope grants no additional tool or effect authority. Managed operation-equipped app-server sessions retain their existing Todo-bound approval/handoff contract; this CLI option applies to exec conversations. Other hosts retain their adapter's Todo-based session contract.

For a managed turn run-once --host codex-cli --codex-operation-tools invocation, set LOOPX_CODEX_OPERATION_WORKER_USER and LOOPX_CODEX_OPERATION_WORKER_HOME to opt into Linux process isolation. The Core launcher needs root authority to start the app server as the named unprivileged Worker. Provision the absolute Worker home and its .codex directory with mode 0700 and Worker ownership. Configure model access in that account. The Core environment is excluded, and the app server starts without supplementary groups or the ability to gain privileges on exec.

Use a read-only sandbox and omit a Core-provided MCP server. The Core runtime root and owning project registry directory must be private, Core-owned physical directories with protected ancestors. The Worker profile is bound to the native session. Core rechecks current Goal authority at durable writeback, and the existing Turn journal keeps its original effect identity and recovery rules. This profile protects local LoopX writeback. Additional business write endpoints need their own credentials and authorization checks.

Use a new turn_instance_id for each new iteration. Reuse the same id only for an explicit replay or failed-Turn recovery. The context policy controls Host memory, while the TurnEnvelope and durable LoopX frontier remain the sole authority for work selection and continuation.

On Codex exec resume, --epoch-prefetch-json can measure an explicit inline replacement. The native session still sends its history. A staged prefetch candidate backed only by an external capture returns KeepRaw with reason host_input_unmeasurable. An explicit fresh still starts a clean session, including when prefetch falls back. Callers that require prior facts should verify the handoff before requesting a fresh session.

中文:Codex exec 续跑时,--epoch-prefetch-json 可计量显式替换的内联内容。 原生会话仍会发送历史,仅有外部快照支撑的预取候选以 host_input_unmeasurable 返回 KeepRaw。显式 fresh 会开启新会话,预取回退时也一样。依赖上轮 事实的调用方应先验证交接,再请求新会话。

run-once --resume-turn-key loads that original plan before fresh selection or Turn-start context, inbox synchronization and recall. It does not mint a new TurnEnvelope for recovery. The existing actor/Goal-lifetime checks, typed journal/session recovery decision, provider revalidation and post-writeback recovery still apply; --retry-failed-turn retains its existing bounded policy. If the reply containing the key was lost, --resume-turn-instance-id ID resolves the unique journal for the original Goal, Agent and instance before entering that same path. Missing, unreadable or ambiguous history stops recovery before Host invocation. Use a fresh instance ID for a new admission.

中文:显式 resume 先读原计划,不为恢复另建一次选任务、TurnEnvelope 或 Turn-start 上下文、inbox 同步和 recall。原身份/Goal 生命周期、journal/Session 恢复、provider 当前校验与写回后恢复流程保持;失败重试仍受既有有界策略约束。若包含 key 的回包丢失,可用 --resume-turn-instance-id ID 按原 Goal、Agent 和轮次定位唯一 journal,再进入相同 恢复流程。历史缺失、不可读或不唯一时停在 Host 调用前。新准入使用新轮次 ID。

When opted in with --context-strategy-mode auto (default off; an explicit off from the CLI or benchmark worker overrides any Goal-level policy), the continuation/settlement Turn piggybacks an optional context_strategy_proposal_json field onto the existing host result without an extra model call. Read-only planning (turn plan --include-transaction-detail) opens existing SQLite stores in read-only mode without creating tables or mutating database bytes. The Agent may leave the field empty (KeepRaw, preserving live prefix KV-cache reuse) or propose KeepRaw, FoldToReceipt, or EpochReset with bounded failure facts, open obligations, and an optional read-only next_command. LoopX records the Agent's proposal, the selected host's physical HostCapabilities carrier, and Core's verified adoption separately: active raw-trace dependencies, unsettled or repair outcomes, native resumes that retain prior history without replacement, unsafe/failed prefetch probes, or net token savings below cold-prefix amortization deterministically retain KeepRaw. Before dispatching a staged EpochReset, both planning and run-once revalidate the current scope, staged source digest, and native session/rollout provenance—retaining resume and omitting the rejected handoff if the source moved—and failed-candidate rollback restores the backed-up binding under the native session lock only if the persisted binding is still that candidate. The backup belongs to the Turn that staged it and is retired after rollback. A later explicit fresh Turn owns its observed native binding.

Context-strategy telemetry reports the last cumulative provider token snapshot from the same complete rollout capture used to measure source size. A matching native session header and a unique source file establish the binding. Duplicate requests or repeated equal snapshots do not add usage. Missing or inconsistent counters remain unknown. A changed, ambiguous or unreadable source invalidates a staged handoff when the native source is checked before dispatch.

上下文策略从同一份完整的原生 rollout 读取体积和最后一条累计 token 快照。文件需唯一, 且会话头与已绑定的原生会话一致。重复的请求记录和同值快照不会重复计入用量。用量缺失 或计数不一致时保留未知。投递前发现原生来源已变更、不唯一或不可读时,暂存交接失效。

中文:显式启用 --context-strategy-mode auto(默认 off,且 CLI 或 benchmark worker 显式传入的 off 优先于 Goal 级配置)时,接续/结算回合会在既有宿主返回结构上顺带承载可选的 context_strategy_proposal_json,不增加独立模型调用;只读规划预览(turn plan --include-transaction-detail)以只读连接访问既有 SQLite 库,不建表、不改数据库字节。Agent 可留空以维持 KeepRaw(保持当前前缀与 KV cache 复用),或在边界处提议 KeepRaw、 FoldToReceipt 或 EpochReset,附带受界失败事实、未结义务与可选只读 next_command。 LoopX 分别记录 Agent 提议、宿主 HostCapabilities 物理执行方式与 Core 核验采用结果:凡存在 原始反例依赖、未结算或待修复结果、原生续跑仍保留旧历史、预取探测不安全/失败,或扣减冷前缀摊销后的净 token 节省不足时,一律回退 KeepRaw。在投递已暂存 EpochReset 前,规划与 run-once 共用来源 核验(校验当前作用域、来源摘要及原生会话/rollout 一致性),来源失效时续用原会话并省去已拒交接;新会话 候选若校验失败,仅在原生会话锁下确认当前绑定仍为本次候选时才恢复备份,保留并发提交的较新绑定。 备份绑定到暂存它的 Turn,并在回滚后清除。之后显式选择 fresh 的 Turn 保留自己观测到的原生绑定。

Context strategy reads the native session scope and the selected Todo from the admitted Turn plan. Under Todo scope, pending handoffs and rollback backups follow that Todo through planning, dispatch and settlement, including when the Agent alternates between Todos. An old handoff without a verifiable Todo binding leaves the saved native session available for ordinary resume.

中文:上下文策略从已准入的 Turn 计划读取原生会话作用域和选中的 Todo。使用 Todo 级会话时,待交接记录与回滚备份在规划、派发和结算时始终跟随该 Todo,即使同一 Agent 交替处理多个 Todo。旧记录缺少可验证的 Todo 绑定时,仍可用原有的宿主会话继续执行。

Adapter Requirements

An external host adapter must provide:

  • capability discovery that can be passed to --available-capability;
  • start, resume, cancel, and bounded-timeout operations;
  • a public-safe typed result channel separate from raw transcript output;
  • an explicit execution mode and no silent mode fallback;
  • an opaque local session handle with no authority beyond host resume;
  • visibility and idle proof before injecting into an interactive session; and
  • deterministic failure mapping to the result and failure classes above.

The smallest useful adapter has only three responsibilities: translate the typed request into one bounded agent-CLI invocation, preserve an opaque local resume handle when the host supports it, and translate the final outcome into one typed candidate result. It must not parse LoopX status prose, write LoopX state, spend quota, or validate its own work.

The driver may discard raw stdout and stderr, but it must not mistake their absence for a typed result. Raw prompts, transcripts, benchmark task text, verifier tails, credentials, and local session paths stay outside committed fixtures and LoopX state.

Promotion Gates

The protocol remains experimental until all of these are true:

  1. shadow replay preserves the live TurnEnvelope action signature across delivery, user gate, monitor wait, capability repair, workspace repair, replan, blocked, and throttled states;
  2. one real host adapter proves start/resume, typed result, validation, idempotent writeback, spend ordering, and scheduler acknowledgement;
  3. interactive and isolated-headless modes fail closed without switching into each other;
  4. a controlled benchmark dogfood run shows source, budget, concurrency, and no-feedback boundaries remain comparable; and
  5. rollback can disable the adapter while leaving normal LoopX CLI state and Codex App heartbeat operation intact.

This protocol does not authorize benchmark launch, leaderboard submission, production writes, credential handling, or default replacement of Codex App.