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
29 changes: 23 additions & 6 deletions docs/reference/required-work-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -529,10 +529,21 @@ readback for the original claim receipt, current lease and any verified ready
capture without repeating the claim or guard. A Hook response alone does not
prove delivery. For this session the repeat hint is suppressed after a tool
read is verified against the recorded ready capture.
Follow the captured readiness check for the same Todo and Turn once the active
lease matches. An authorized retry of the same bound capture reuses its
managed claim operation, and the authority owner checks the original lease on
replay. The native session keeps the latest eligible live guard digest
If the hook has no recorded ready capture, its readback provides
`readiness_command` and `ready_context_command_template`. Run the readiness
command from the original workspace after the claim receipt and the active
lease match in Goal, Todo, owner, key and version. The same-Turn guard stages a
private capture separately from the active session journal. Require normal
delivery, the same Goal, Agent, Todo and Turn, and a ready lease proof with the
original key and version. Use the returned digest to fill the template from
that receipt. After staging, the native publisher checks the original claim
receipt and matching active lease under the same local writer lock used by
lease release and replacement. It holds that lock through the journal
commit. If the lease has retired, return the original receipt readback.
The original capture remains readable through `quota context-read`.
An authorized retry of the same bound capture reuses its managed claim
operation, and the authority owner checks the original lease on replay.
The native session keeps the latest eligible live guard digest
separately from the capture. Presenting the exact saved decision preserves
that binding. Older captures and copies with different bytes remain readable.
Preserve any original claim receipt and use `quota should-run` with the same
Expand All @@ -550,8 +561,14 @@ reader. Quota still checks ownership and lease expiry before reporting readiness
中文:私有原生日志在对绑定 capture 发起领取前先登记自动准备,并在投影前记录已校验的
ready capture。若就绪检查或 Hook 送达中断,Hook 可重复提供原领取回执、当前租约
及 ready capture 的回读入口,不再重复自动领取或准入。Hook 输出本身不足以确认送达。
观察到针对原 ready capture 的已验证工具读取后,同会话才停止重复提示。活动租约匹配后,
沿同一 Todo 与 Turn 完成就绪检查。对同一绑定 capture 的授权重试复用原受管领取操作,
观察到针对原 ready capture 的已验证工具读取后,同会话才停止重复提示。Hook 尚未登记
ready capture 时,回读会提供 `readiness_command` 和 `ready_context_command_template`。
先核对原领取回执与活动租约的 Goal、Todo、归属、键和版本,再在原工作目录执行就绪命令。
同轮检查会在活动会话日志以外生成私有 capture。确认允许正常交付、Goal、Agent、Todo
及 Turn 一致,且就绪的租约凭证与原键和版本匹配后,用返回的摘要填入同一回执的模板,
再读取校验通过的原生上下文。暂存完成后,发布端在租约释放和换代共用的本地写锁内核对
原领取回执和当前活动租约,并持锁提交会话日志。租约已退役时提供原回执读回。
原 capture 仍可通过 `quota context-read` 读取。对同一绑定 capture 的授权重试复用原受管领取操作,
由权威 owner 验证原租约。原生会话独立保存最新合格准入的摘要,重新展示逐字节一致的
快照会保留绑定。旧快照和字节不同的副本仍可读,保留已有领取回执。仍需准备时,用原
Goal、Agent、Todo 和 Turn 运行 `quota should-run`,生成新的 capture,再按当前准入
Expand Down
103 changes: 83 additions & 20 deletions loopx/cli_commands/quota_native_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import subprocess
import tempfile
from collections.abc import Callable
from contextlib import AbstractContextManager, nullcontext
from functools import partial
from pathlib import Path
from typing import Any

Expand All @@ -20,6 +22,11 @@
QuotaCommandValidationError,
QuotaDecisionTransportError,
)
from ..control_plane.turn_driver.codex_execution_preparation import (
NativeRecoveryLeaseUnavailable,
guard_native_recovery_publication,
require_native_recovery_lease,
)
from ..control_plane.turn_driver.decision_capture import (
CONTEXT_CAPTURE_NAVIGATION_GUIDANCE,
CONTEXT_CAPTURE_READ_GUIDANCE,
Expand All @@ -46,13 +53,17 @@
def _saved_context_transport_failure(
error: Exception, *, args: argparse.Namespace, receipt: dict[str, Any],
recovery: dict[str, Any], reader_argv: list[str], source_unverified: bool = False,
authority_unverified: bool = False,
) -> dict[str, Any]:
page_bytes, output_bytes = native_context_page_budget()
limit = getattr(args, "max_page_output_bytes", None)
if isinstance(limit, int) and limit > 0:
output_bytes = min(output_bytes, limit)
page_bytes = min(page_bytes, output_bytes)
if source_unverified:
if authority_unverified:
instruction = ("Read the original receipt with recovery.command. The saved capture remains readable, "
"but publishing ready work requires the original current lease.")
elif source_unverified:
instruction = (
"The saved source could not be verified. Use recovery.command for diagnostic receipt readback. "
"Restore an intact, supported capture and retry context-project with its original Goal, Agent, Turn "
Expand All @@ -71,13 +82,20 @@ def _saved_context_transport_failure(
"heartbeat_receipt": receipt, "capture_sha256": args.capture_sha256,
"recovery": {**recovery, "command": context_capture_read_command(
Path(recovery["path"]), recovery["sha256"], page_bytes=page_bytes,
max_page_output_bytes=output_bytes, list_fields=not source_unverified,
select=["/heartbeat_receipt"] if source_unverified else None, reader_argv=reader_argv)},
max_page_output_bytes=output_bytes, list_fields=not (source_unverified or authority_unverified),
select=["/heartbeat_receipt"] if source_unverified or authority_unverified else None,
reader_argv=reader_argv)},
"instruction": instruction}


def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str | None = None) -> dict[str, Any]:
"""Present an immutable already-decided quota capture, without authority IO.
def project_saved_context_capture(
args: argparse.Namespace, *, hook_session: str | None = None,
registry_path: Path | None = None, runtime_root_arg: str | None = None,
) -> dict[str, Any]:
"""Present an immutable already-decided quota capture.

Resumed Host preparation rechecks the original claim before publication.
Historical capture projection remains independent of live authority.

Publication is delayed until this native tool runs, so the lifecycle owner
can select its current continuity basis. Optional codec failure returns the
Expand All @@ -93,6 +111,7 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
)

reader_argv = current_loopx_cli_argv()
prepared_claim = getattr(args, "prepared_claim_operation_id", None)
try:
activation = quota_capture.native_context_activation(args)
saved_page = bool(getattr(args, "initial_read", False) or getattr(args, "select", None))
Expand All @@ -110,7 +129,7 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
if saved_page and args.page_bytes is not None:
_validate_context_page_window(args.offset, args.page_bytes, output_limit)
path, _, payload = _read_capture(args.capture_file, args.capture_sha256,
private=hook_session is not None)
private=hook_session is not None or prepared_claim is not None)
if payload.get("ok") is False:
raise ValueError("The saved capture is diagnostic. Read it with quota context-read.")
identity = payload.get("agent_identity")
Expand All @@ -133,6 +152,28 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
full_reference = dict(reference)
version = payload.get("schema_version")
complete = version == COMPLETE_TURN_DECISION_VERSION
publication_guard: Callable[[], AbstractContextManager[None]] = nullcontext

def authority_refusal(error: Exception) -> dict[str, Any]:
return _saved_context_transport_failure(error, args=args, receipt=receipt,
recovery=full_reference, reader_argv=reader_argv, authority_unverified=True)

if prepared_claim is not None:
from ..history import load_registry
from ..paths import resolve_runtime_root

try:
if not complete or registry_path is None:
raise ValueError("Native readiness recovery requires a bound complete Turn.")
assert_complete_turn_decision(payload)
registry_path = registry_path.resolve()
runtime_root = resolve_runtime_root(load_registry(registry_path), runtime_root_arg).resolve()
require_native_recovery_lease(payload, claim_operation_id=prepared_claim,
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
registry_path=registry_path, runtime_root=runtime_root)
except (OSError, RuntimeError, ValueError, TypeError) as exc:
return authority_refusal(exc)
publication_guard = partial(guard_native_recovery_publication, payload,
claim_operation_id=prepared_claim, registry_path=registry_path, runtime_root=runtime_root)
try:
if not complete and not is_legacy_saved_quota_decision(payload):
if activation["enabled"]:
Expand All @@ -142,7 +183,7 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
goal_id=args.goal_id, agent_id=args.agent_id, capture_sha256=args.capture_sha256,
hook_session=hook_session)
raise QuotaDecisionTransportError("Unsupported saved quota decision version or mixed Turn binding.")
if complete and not activation["enabled"] and not activation["progressive_enabled"]:
if complete and prepared_claim is None and not activation["enabled"] and not activation["progressive_enabled"]:
assert_complete_turn_decision(payload)
except (QuotaDecisionTransportError, EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc:
return _saved_context_transport_failure(exc, args=args, receipt=receipt,
Expand Down Expand Up @@ -173,10 +214,13 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
navigation = quota_capture.progressive_context_capture_view(payload, args,
runtime_root=Path(getattr(args, "_context_delivery_machine_runtime", path.parent)),
directory=None, reader_argv=reader_argv, captured_decision=captured_decision, page_attached=saved_page)
if saved_page:
return _saved_context_read_page(args, navigation, initial_reference=None,
initial_read_plan=None, output_limit=output_limit, reader_argv=reader_argv)
return navigation
with publication_guard():
if saved_page:
return _saved_context_read_page(args, navigation, initial_reference=None,
initial_read_plan=None, output_limit=output_limit, reader_argv=reader_argv)
return navigation
except NativeRecoveryLeaseUnavailable as exc:
return authority_refusal(exc)
except (QuotaDecisionTransportError, OSError, ValueError, EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc:
if complete:
return _saved_context_transport_failure(exc, args=args, receipt=receipt,
Expand Down Expand Up @@ -237,7 +281,7 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
progressive_enabled=activation["progressive_enabled"], selection_command_args_template=transport,
captured_decision=captured_decision if activation["progressive_enabled"]
and (args.initial_read or "sha256" in captured_decision) else None,
hook_session=hook_session, saved_capture=True)
hook_session=hook_session, saved_capture=True, publication_guard=publication_guard)
projected = prepared.delivery
initial_read_plan = prepared.initial_read_plan
native_prepared = True
Expand All @@ -262,6 +306,8 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
mode, target = native_view["mode"], native_view.get("target")
initial_reference = native_view.get("first_read_reference")
native_view = model_context_reference(native_view, reader_argv=reader_argv)
except NativeRecoveryLeaseUnavailable as exc:
return authority_refusal(exc)
except (EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc:
if not complete:
raise
Expand All @@ -287,10 +333,14 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
"instruction": "Presentation of the original decision only; authority and freshness are unchanged. "
+ (CONTEXT_CAPTURE_NAVIGATION_GUIDANCE if activation["enabled"] else CONTEXT_CAPTURE_READ_GUIDANCE)}
navigation = native_view or result
if saved_page:
return _saved_context_read_page(args, navigation, initial_reference=initial_reference,
initial_read_plan=initial_read_plan, output_limit=output_limit, reader_argv=reader_argv)
return navigation
try:
with nullcontext() if native_prepared else publication_guard():
if saved_page:
return _saved_context_read_page(args, navigation, initial_reference=initial_reference,
initial_read_plan=initial_read_plan, output_limit=output_limit, reader_argv=reader_argv)
return navigation
except NativeRecoveryLeaseUnavailable as exc:
return authority_refusal(exc)


def _handle_context_config(
Expand Down Expand Up @@ -372,6 +422,8 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any]
and event.get("hook_event_name") in CONTEXT_LIFECYCLE_HOOKS):
directory = codex_context_directory(directory=args.codex_context_dir,
root=getattr(args, "codex_context_root", None), session=event.get("session_id"), create=True)
scenario = activation["scenario"]
progressive_enabled = activation["progressive_enabled"]
payload = codex_context_hook(directory, event)
request = None
preparation_context = ""
Expand All @@ -383,15 +435,19 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any]
if "claim_source_sha256" not in request or not request.get("turn_instance_id"):
raise LegacyNativePreparationCapture()
if request.get("readback_only") is True:
preparation_context = codex_execution_preparation_readback_context(request) or ""
preparation_context = codex_execution_preparation_readback_context(
request, scenario=scenario, context_directory=directory,
progressive_enabled=progressive_enabled,
) or ""
else:
capture = Path(tempfile.mkdtemp(prefix="prepared-", dir=directory)) / "ready"
receipt = execute_codex_execution_preparation(
request,
cwd=workspace.resolve(),
scenario=activation["scenario"],
scenario=scenario,
capture_directory=capture,
context_directory=Path(directory),
progressive_enabled=progressive_enabled,
)
record_native_execution_preparation(
directory,
Expand Down Expand Up @@ -434,7 +490,10 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any]
directory, event, readback_for=request["source_sha256"],
)
if readback is not None:
preparation_context = codex_execution_preparation_readback_context(readback) or ""
preparation_context = codex_execution_preparation_readback_context(
readback, scenario=scenario, context_directory=directory,
progressive_enabled=progressive_enabled,
) or ""
if preparation_context:
existing = payload.get("hookSpecificOutput")
existing_context = str(existing.get("additionalContext") or "") if isinstance(existing, dict) else ""
Expand All @@ -455,6 +514,10 @@ def handle_native_context_command(args: argparse.Namespace, *, print_payload: Ca
"""Dispatch captured reads and native lifecycle IO before quota authority access."""
from . import quota_capture

if getattr(args, "prepared_claim_operation_id", None) is not None and args.quota_command != "context-project":
print_payload({"ok": False, "reason": "--prepared-claim-operation-id requires quota context-project"},
args.format, str)
return 1
if getattr(args, "complete_turn", False) and (args.quota_command != "should-run" or args.format != "json"):
print_payload({"ok": False, "reason": "--complete-turn requires JSON quota should-run"}, args.format, str)
return 1
Expand Down Expand Up @@ -540,7 +603,7 @@ def handle_native_context_command(args: argparse.Namespace, *, print_payload: Ca
)
return _handle_context_hook(args, activation=activation)
if args.quota_command == "context-project":
payload = project_saved_context_capture(args)
payload = project_saved_context_capture(args, registry_path=registry_path, runtime_root_arg=runtime_root_arg)
print_payload(payload, args.format, lambda value: str(value.get("command", value.get("reason", ""))))
return 0 if payload["ok"] else 1
if args.quota_command == "context-read":
Expand Down
1 change: 1 addition & 0 deletions loopx/cli_commands/quota_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ def register_quota_command(
# immutable view after the model's lifecycle hooks establish continuity.
quota_parser.add_argument("--defer-context-presentation", action="store_true", help=argparse.SUPPRESS)
quota_parser.add_argument("--prepared-capture-reference", action="store_true", help=argparse.SUPPRESS)
quota_parser.add_argument("--prepared-claim-operation-id", help=argparse.SUPPRESS)
from ..control_plane.turn_driver.codex_context import CONTEXT_DELIVERY_SETTINGS, DELTA_DELIVERY_SETTINGS

quota_parser.add_argument("--context-delivery", choices=CONTEXT_DELIVERY_SETTINGS,
Expand Down
Loading
Loading