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
1 change: 1 addition & 0 deletions .github/workflows/python-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,7 @@ jobs:
tests/control_plane/test_refresh_settle_turn.py::test_wrong_or_missing_child_workspace_retains_owed_command_for_exact_recovery
tests/control_plane/test_refresh_settle_turn.py::test_legacy_posix_quoted_powershell_launcher_fails_before_settlement
tests/control_plane/test_refresh_settle_turn.py::test_pinned_powershell_launcher_settles_original_turn_once
tests/control_plane/test_replan_progress_native_cli.py::test_replan_stage_commands_run_verbatim_in_powershell

- name: Restore the primary Windows Node runtime
uses: actions/setup-node@v6
Expand Down
11 changes: 8 additions & 3 deletions docs/reference/required-work-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -1618,8 +1618,11 @@ all of them: read those pages completely before acting. No control text is cut.
Omitting the option preserves the existing full-result API. A nonpositive
budget is rejected before execution. Platforms without qualified POSIX private
capture validation reject this option before settlement; remove only the output
option to use the same Turn's full-result API. Reader references also fail closed
there; mode bits are not a substitute for Windows ACL verification.
option to use the same Turn's full-result API. On Windows, stateless progressive
delivery and the explicit `refresh-state --settle-turn --settlement-receipt`
readback use protected native ACLs for saved files and reader references.
Use `--delta-delivery off` for the stateless path. An explicit progressive
capture destination requires a private, physical parent directory.
A capture failure after evaluation keeps every original control field (including
`ok`, refusal reason, identity and receipts), omits only `before` / `after`, and
adds `result_delivery_error`; the process exits nonzero. This fallback prioritizes
Expand Down Expand Up @@ -1650,7 +1653,9 @@ Codex App heartbeat 有原生会话,且当前 Todo 已准入并就绪时,可

省略选项保留原有完整结果 API;非正预算在执行前拒绝。缺少已验证 POSIX 私有捕获
校验的平台在结算前拒绝此选项;仅移除输出选项即可使用同一 Turn 的完整结果 API。
reader reference 在该平台也安全拒绝,不能用 mode bits 代替 Windows ACL 校验。
Windows 上的无状态渐进投递及显式 `refresh-state --settle-turn --settlement-receipt`
读回使用原生受保护 ACL 保存并校验文件与读取引用。无状态路径使用
`--delta-delivery off`。显式指定渐进捕获路径时,父目录须是私有实体目录。
求值后捕获失败时保留全部原始控制字段(包括 `ok`、拒绝原因、身份和回执),只省略
`before`/`after`,追加 `result_delivery_error` 并非零退出。此故障兜底优先保全控制
信息,不保证展示预算;被拒绝的操作不一定存在 spend receipt。修复捕获权限或以
Expand Down
38 changes: 8 additions & 30 deletions loopx/cli_commands/context_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import argparse
import os
from pathlib import Path
import stat
import tempfile
from typing import Any

from ..control_plane.turn_driver.codex_context import context_delivery_for_arguments
Expand All @@ -32,14 +30,12 @@ def _private_transport_root(runtime_root: Path) -> str:
"""Create only our leaf; never repair permissions or follow a replaced leaf."""
if os.name != "posix":
raise ValueError("native context continuity is unavailable on this platform")
runtime_root = runtime_root.expanduser().resolve()
runtime_root.mkdir(mode=0o700, parents=True, exist_ok=True)
root = runtime_root / "context-delivery"
root.mkdir(mode=0o700, exist_ok=True)
info = root.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
raise ValueError("machine context transport requires a private physical directory owned by this user")
return str(root)
from ..control_plane.turn_driver.decision_capture import private_capture_root

try:
return str(private_capture_root(runtime_root))
except OSError as exc:
raise ValueError("machine context transport requires a private physical directory owned by this user") from exc


def capture_context_recovery(value: dict[str, Any], *, runtime_root: Path,
Expand All @@ -51,30 +47,12 @@ def capture_context_recovery(value: dict[str, Any], *, runtime_root: Path,
unchanged; retry that same operation after repairing its private transport.
"""
from ..control_plane.turn_driver.decision_capture import (
capture_context_projection, context_capture_read_command,
capture_context_projection, context_capture_read_command, private_capture_root, private_capture_subdirectory,
)

try:
from ..control_plane.runtime.private_permissions import protect_private_path, require_private_path

# This is a write-once recovery file, not native continuity. Reuse the
# cross-platform private IO owner without enabling a native baseline.
runtime_root = runtime_root.expanduser().resolve()
runtime_root.mkdir(mode=0o700, parents=True, exist_ok=True)
root = runtime_root / "context-delivery"
try:
root.mkdir(mode=0o700)
except FileExistsError:
try:
require_private_path(root, directory=True) # Never repair an existing leaf.
except OSError as error:
raise ValueError("machine context transport requires a private physical directory owned by this user") from error
else:
protect_private_path(root, directory=True)
directory = Path(tempfile.mkdtemp(prefix="recovery-", dir=root))
protect_private_path(directory, directory=True)
directory = private_capture_subdirectory(private_capture_root(runtime_root), "recovery-")
reference = capture_context_projection(value, directory=directory, filename="required-context.json")
protect_private_path(Path(reference["path"]))
if not index_and_select:
return {key: reference[key] for key in ("path", "sha256", "command")}
path, digest = Path(reference["path"]), reference["sha256"]
Expand Down
47 changes: 30 additions & 17 deletions loopx/cli_commands/quota_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,17 +314,17 @@ def progressive_context_capture_view(payload: dict[str, Any], args: argparse.Nam
A plain read-only should-run remains read-only. Private transport files do
not admit work, mint a Turn or stand in for observed model consumption.
"""
from .context_machine import _private_transport_root
from .quota_request import quota_detail_sections_from_args
from ..control_plane.turn_driver.decision_capture import capture_progressive_context
from ..control_plane.turn_driver.decision_capture import (
capture_progressive_context, private_capture_root, private_capture_subdirectory,
)

# Only a fresh stateless source can supply this route. Saved and explicitly
# captured decisions keep the reader chosen by their existing callers.
stage_from_projection = (directory is None and captured_decision_path is None
and "vision" not in quota_detail_sections_from_args(args))
if directory is None:
root = Path(_private_transport_root(runtime_root))
directory = Path(tempfile.mkdtemp(prefix="context-", dir=root))
directory = private_capture_subdirectory(private_capture_root(runtime_root), "context-")
transport = _capture_selection_transport_template(payload, args, capture_root=directory.parent)
required, reference, review = capture_progressive_context(
payload, directory=directory, surface=quota_context_surface(payload, args),
Expand Down Expand Up @@ -469,9 +469,14 @@ def project_saved_context_capture(
saved_source = None
if complete and activation["progressive_enabled"]:
from ..control_plane.runtime.private_permissions import require_private_path
from ..control_plane.turn_driver.decision_capture import require_private_capture_directory

try:
require_private_path(path)
if os.name == "nt":
# An explicit digest can restore a historical capture, but a
# private reader also requires an owned physical directory.
require_private_capture_directory(Path(args.capture_file).expanduser().absolute().parent)
except OSError:
# A manually restored capture may still use the existing checked
# presentation path without becoming a private reader source.
Expand Down Expand Up @@ -685,7 +690,14 @@ def prepare_quota_capture(args: argparse.Namespace, directory: Path | None) -> P


def prepare_decision_capture(args: argparse.Namespace) -> Path | None:
enabled = native_context_activation(args)["enabled"]
from ..control_plane.runtime.private_permissions import protect_private_path
from ..control_plane.turn_driver.decision_capture import (
private_capture_subdirectory, require_private_capture_directory,
)

activation = native_context_activation(args)
enabled = activation["enabled"]
private_windows = os.name == "nt" and activation["progressive_enabled"]
if enabled and not (getattr(args, "codex_context_dir", None) or getattr(args, "codex_context_root", None)
or getattr(args, "decision_handoff_socket", None)):
raise QuotaCommandValidationError("context-delivery on requires a native context location or explicit host handoff")
Expand Down Expand Up @@ -723,16 +735,23 @@ def prepare_decision_capture(args: argparse.Namespace) -> Path | None:
parent = Path(root).expanduser().absolute()
if parent.is_symlink() or not parent.is_dir():
raise OSError("capture root must be an existing directory, not a symlink")
if private_windows:
require_private_capture_directory(parent)
return private_capture_subdirectory(parent, "decision-")
return Path(tempfile.mkdtemp(prefix="decision-", dir=parent))
assert requested is not None # root is absent; exactly one destination was checked above.
directory = Path(requested).expanduser().absolute()
if getattr(args, "prepared_capture_reference", False):
if private_windows:
require_private_capture_directory(directory.parent)
elif getattr(args, "prepared_capture_reference", False):
# Bind the physical parent before admission: the saved selection
# uses it as an output root, which must not be a symlink.
directory = Path(os.path.realpath(directory.parent, strict=True)) / directory.name
# A new directory per invocation prevents overwriting a prior observation,
# including a prior invocation in the same Turn. Existing symlinks fail too.
directory.mkdir(mode=0o700)
if private_windows:
protect_private_path(directory, directory=True)
except OSError as exc:
raise QuotaCommandValidationError(
"decision capture needs a new directory or an existing writable root; "
Expand Down Expand Up @@ -806,23 +825,17 @@ def budgeted_settlement_result(
Unbudgeted callers retain their existing full result.
"""
from ..control_plane.effect_runtime import MAX_REQUEST_BYTES
from ..control_plane.turn_driver.decision_capture import write_decision_capture
from ..control_plane.turn_driver.decision_capture import (
private_capture_root, private_capture_subdirectory, write_decision_capture,
)

def fits(value: dict[str, object]) -> bool:
# Match the JSON CLI serializer, including print's newline.
return len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode()) + 1 <= output_bytes
return _json_output_size(value) <= output_bytes

if supporting_fields is None and fits(payload):
return payload
try:
uid = private_capture_uid()
root = runtime_root.expanduser().resolve() / "context-delivery"
root.mkdir(mode=0o700, exist_ok=True)
metadata = root.lstat()
if (not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != uid
or metadata.st_mode & 0o077):
raise ValueError("result capture requires a private physical directory owned by this user")
directory = Path(tempfile.mkdtemp(prefix="settlement-", dir=root))
directory = private_capture_subdirectory(private_capture_root(runtime_root), "settlement-")
saved = directory / "result.json"
digest = write_decision_capture(saved, payload)
if saved.stat().st_size > MAX_REQUEST_BYTES:
Expand Down
2 changes: 1 addition & 1 deletion loopx/cli_commands/quota_context_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ def read_context_capture(args: argparse.Namespace, *, presentation: dict[str, An
if not isinstance(digest, str) or BARE_SHA256_PATTERN.fullmatch(digest) is None or not value:
raise ValueError("context-read requires the original capture file and its exact SHA-256")
_validate_context_page_window(offset, size, output_limit)
path, raw, payload = _read_capture(value, digest)
path, raw, payload = _read_capture(value, digest, private=bool(reference_file) and os.name == "nt")

def restart(failure: dict[str, Any], *, select: list[str] | None = None, list_fields: bool = False,
list_depth: int | None = None, initial_read: bool = False,
Expand Down
6 changes: 4 additions & 2 deletions loopx/control_plane/quota/turn_envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -743,8 +743,10 @@ function replanReadCommands(payload: JsonObject, path = payload.replan_read_path
args.push("--context-delivery", "on");
}
if (typeof captureSha256 === "string") args.push("--capture-sha256", captureSha256);
// Match the host CLI renderer for the PowerShell launcher captured by the first read.
const powershell = /\.ps1$/iu.test(program);
// Match the host CLI renderer for digest-bound reads, including Windows
// Python installations. Legacy commands can be part of stored signatures.
const powershell = /\.ps1$/iu.test(program) ||
(typeof captureSha256 === "string" && process.platform === "win32");
const quote = powershell ? powershellLiteral : shellQuote;
const executable = powershell && !/^[A-Za-z0-9_./-]+$/u.test(program)
? `& ${quote(program)}`
Expand Down
Loading
Loading