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
25 changes: 16 additions & 9 deletions docs/reference/required-work-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,10 @@ read obligations fit in one page, the opening contains those controls and
reports EOF. Follow it and its cursor before work. Both selections pin the same
immutable capture.
`navigation.first_read_command` replays the opening. Use
`navigation.recovery.command` for other fields. If the response is lost, use the
original digest-bound capture in the wake prompt. Recovery reuses the saved
decision and its original receipt.
`navigation.recovery.command` for fields in the delivered view. For deferred
fields, use the original source in `context_details`. If the response is lost,
use the original digest-bound capture in the wake prompt. Recovery reuses the
saved decision and its original receipt.

When native quota navigation requires explicit Todo selection, the opening
keeps the discovery and same-Turn selection commands with the read obligations
Expand Down Expand Up @@ -359,8 +360,9 @@ presentation changes neither admission nor the explicit off view.
和读取义务能完整放在一页时,首屏先交付这些控制信息,并给出
`navigation.remaining_read_command`。即使首屏已到 EOF,页级 `read_instruction` 仍指向
这条命令。工作前沿这条命令及其游标读完余下的首读内容。两个选区绑定同一份不可变捕获。
`navigation.first_read_command` 可重读首屏,其他字段沿
`navigation.recovery.command` 读取。结果丢失时,用唤醒正文中的原文件及摘要恢复,复用原决策和回执。
`navigation.first_read_command` 可重读首屏。`navigation.recovery.command` 读取已交付视图
中的字段,延迟交付的字段从 `context_details` 标明的原始捕获选读。结果丢失时,用唤醒
正文中的原文件及摘要恢复,复用原决策和回执。

原生额度导航要求显式选择 Todo 时,首读把候选发现、同一轮次的选择命令、必读项和执行
约束放在一起。推荐候选的明细导致这些信息超出单页预算时,同一捕获的续读保留完整
Expand Down Expand Up @@ -877,11 +879,14 @@ setting. Ordinary machine validation still applies to business operations.
Native `quota should-run` and saved `context-project` persist the complete
capture and return a small file reference, not an eager first page. The response
names the delta/full `path`, digest and reader `command`; `recovery` names the
current complete file. A file delta additionally carries `baseline_reference`.
complete file for the current delivered view. A file delta also carries `baseline_reference`.
`index_command` lists current fields and `select_command` batches exact pointers.
Under a smaller explicit ceiling, these shortcut commands may be omitted;
append `--list` or `--select <pointer>` to `recovery.command` instead. Both
operations address the current complete capture, including during delta delivery.
operations address the current delivered view, including during delta delivery.
For a deferred field, replace `<pointer>` in `context_details.command_template`
with its exact pointer. The template reads the original capture with its digest
and the same CLI route as the delivered view.
The reference stays below 7900 serialized bytes (or the explicit smaller output
ceiling); if metadata cannot fit, recovery retains the current capture. Reader
pages remain independently bounded. A complete raw tool log is not proof that
Expand Down Expand Up @@ -1275,10 +1280,12 @@ SSH Goal 使用 `--runtime-profile codex_app_ssh_goal` 生成 context-config 和
沿用可见 Goal 的执行与结算身份;仅启用差分时接入捕获目录,不转换成自动心跳。
原生 `quota should-run` 与 `context-project` 先保存完整捕获,默认返回小型文件入口,
不内联第一页。`path`、摘要与 `command` 指向当前差分或全量;`recovery` 指向当前
完整文件;文件差分另带 `baseline_reference`。`index_command` 展示当前字段目录,
交付视图的完整文件;文件差分另带 `baseline_reference`。`index_command` 展示当前字段目录,
`select_command` 批量选读精确路径。引用输出不超过 7900 序列化字节或调用者显式更小
的上限;较小预算下可省略这两个快捷命令,改在 `recovery.command` 后追加
`--list` 或 `--select <pointer>`,差分投递时也直接读取当前完整捕获。
`--list` 或 `--select <pointer>`,差分投递时也直接读取当前交付视图。延迟字段可将
`context_details.command_template` 中的 `<pointer>` 换成精确地址,沿原捕获摘要和
本次交付使用的同一个 CLI 入口选读。
元数据仍放不下时保留当前捕获恢复入口。读取页另受输出预算约束。
原始工具日志完整,不证明宿主保留给模型的字节也完整。

Expand Down
7 changes: 4 additions & 3 deletions loopx/cli_commands/quota_context_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,8 +531,7 @@ def reference(value: dict[str, Any], *, navigation: bool = False) -> dict[str, s
reference_file=Path(result["recovery"]["reference_file"]), reader_argv=reader_argv)
if "remaining_read_command" in view:
result["remaining_read_command"] = view["remaining_read_command"]
result["instruction"] += (" Append --select '<pointer>' or --list to recovery.command for current fields. "
"Reader references keep complete digests locally; the CLI checks them on every page. "
result["instruction"] += (" Reader references keep complete digests locally; the CLI checks them on every page. "
"A reference or digest grants no authority or freshness.")
if len(_native_output_bytes(result)) > min(output_bytes, 7900):
return view # Preserve usable legacy recovery under a very small ceiling.
Expand Down Expand Up @@ -578,6 +577,9 @@ def _native_context_reference(projected: dict[str, Any], reference: dict[str, An
if value is None or isinstance(value, (str, bool, int, float))
and len(json.dumps(value, ensure_ascii=False).encode("utf-8")) <= 240}
result["instruction"] = CONTEXT_CAPTURE_NAVIGATION_GUIDANCE if progressive_enabled else CONTEXT_CAPTURE_READ_GUIDANCE
result["instruction"] += " Use --select or --list on recovery.command."
if progressive_enabled:
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
result["instruction"] += " Deferred fields use context_details."
if mode != "full":
result["instruction"] += (" command reads the delta; baseline_reference identifies its exact saved base when file-backed. "
"recovery.command reads current facts directly without that baseline.")
Expand Down Expand Up @@ -627,7 +629,6 @@ def fits() -> bool:
result["baseline_reference"].pop("command", None) # Exact path/hash remain usable.
if not fits():
result.pop("index_command")
result["instruction"] += " Append --list or --select to recovery.command to discover or read current fields."
if not fits():
raise QuotaDecisionTransportError("Native context reference exceeds the output limit; "
"read the saved original decision and receipt without rerunning admission.")
Expand Down
3 changes: 2 additions & 1 deletion loopx/control_plane/quota/progressive_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,8 @@ function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSour
+ "Repeat --select to batch needed fields without replaying the outcome's requirements. "
+ "unread_context_index lists supporting fields not observed read in this epoch, or changed since that read. "
+ "source_blocks conservatively includes partially read current sources; this index is not a full-read gate. "
+ "Use its source path and sha256 with quota context-read --select for each exact pointer. "
+ "Substitute the exact pointer in context_details.command_template, or use the source path and sha256 "
+ "with quota context-read --select. "
+ "A prior selected read, EOF or saved file does not confirm model-visible coverage or retention. "
+ "Detail reads never establish a full baseline. "
+ "Uncertain or missing necessary facts must be recovered before dependent action; Agent review is not independent acceptance."};
Expand Down
4 changes: 1 addition & 3 deletions loopx/control_plane/turn_driver/codex_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -998,9 +998,7 @@ def publish_recovery(reference: dict[str, Any]) -> None:
if selection_command_args_template is not None else {}),
**({"captured_decision": captured_decision} if captured_decision is not None else {}),
**({"progressive_enabled": False} if not progressive else {}),
"command_template": context_capture_read_command(Path(recovery["path"]), recovery["sha256"],
page_bytes=page_bytes, max_page_output_bytes=output_bytes)
+ " --select '<supporting_material_pointer>/sources'",
"command_template": recovery["command"] + " --select '<pointer>'",
} if presentation else None, consumed_pointers=state.get("consumed_pointers"),
observe_first_read=progressive)
except (EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc:
Expand Down
20 changes: 20 additions & 0 deletions tests/control_plane/test_context_first_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,26 @@
from tests.control_plane.codex_checkpoint_fixture import selected_context_values


def test_small_native_navigation_keeps_both_reader_routes():
from loopx.cli_commands.quota_context_reader import _native_context_reference, _native_output_bytes

# Fixed reader paths isolate the caller's budget from checkout and temporary directory names.
capture = {"path": f"/project/{'x' * 255}/required-context.json", "sha256": "a" * 64}
view = _native_context_reference(
{}, capture, mode="full", current=capture, current_document={"ok": True},
total_bytes=2000, metadata=None, progressive_enabled=True, field_index=None,
initial_read_pointers=None, initial_read_reference=None, page_bytes=3200,
output_bytes=3200, first_read_budget=(3200, 3200),
reader_argv=["/install/bin/loopx", "--cli-bin", "/install/bin/loopx"],
)

assert len(_native_output_bytes(view)) <= 3200
recovery = shlex.split(view["recovery"]["command"])
assert recovery[recovery.index("--capture-file") + 1] == capture["path"]
assert recovery[recovery.index("--capture-sha256") + 1] == capture["sha256"]
assert recovery[recovery.index("--max-page-output-bytes") + 1] == "3200"
assert all(term in view["instruction"] for term in ("--select", "--list", "recovery.command", "context_details"))

@pytest.fixture
def decision():
return {
Expand Down
41 changes: 33 additions & 8 deletions tests/control_plane/test_quota_authority_settlement_journey.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from canonical_authority_fixture import assert_todo_read_unchanged

import json
import os
import shlex
import subprocess
from datetime import datetime, timedelta, timezone
Expand Down Expand Up @@ -355,7 +356,13 @@ def _workspace_repair_source(tmp_path, provider, goal_scopes=None, todo_scopes=N


@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_workspace_repair_opening_keeps_action_and_recovers_scopes(tmp_path, provider):
@pytest.mark.parametrize("native", [
pytest.param(False, id="stateless"),
pytest.param(True, id="native", marks=pytest.mark.skipif(
os.name != "posix", reason="Native session continuity uses a private POSIX journal",
)),
])
def test_workspace_repair_opening_keeps_action_and_recovers_scopes(tmp_path, monkeypatch, provider, native):
goal_path = "/goal_boundary/write_scope"
todo_path = "/selected_todo/required_write_scopes"
goal_scopes = ["src/**"] + [f"docs/area-{i:03d}/reference/specifications/**" for i in range(300)]
Expand All @@ -371,13 +378,26 @@ def test_workspace_repair_opening_keeps_action_and_recovers_scopes(tmp_path, pro
repair_action = plain["interaction_contract"]["agent_channel"]["primary_action"]
captures = tmp_path / "captures"
captures.mkdir(mode=0o700)
context_args = ["--codex-context-root", str(captures)]
if native:
from loopx.control_plane.turn_driver.codex_context import codex_context_hook

journal = tmp_path / "native"
journal.mkdir(mode=0o700)
session_id = "workspace-repair-native"
monkeypatch.setenv("CODEX_THREAD_ID", session_id)
assert codex_context_hook(str(journal), {"session_id": session_id, "cwd": str(project),
"hook_event_name": "SessionStart", "source": "startup"}) == {}
context_args = ["--codex-context-dir", str(journal)]
code, view = cli._run_cli(
registry, runtime, "quota", "should-run", "--codex-app",
"--goal-id", cli.GOAL_ID, "--agent-id", cli.AGENT_ID, "--todo-id", cli.TODO_ID,
"--turn-instance-id", turn, "--context-delivery", "on", "--delta-delivery", "off",
"--decision-output-root", str(captures), "--codex-context-root", str(captures), cwd=project,
"--turn-instance-id", turn, "--context-delivery", "on", "--delta-delivery", "auto" if native else "off",
"--decision-output-root", str(captures), *context_args, cwd=project,
)
assert code == 0 and view["ok"], view
if native:
assert json.loads((journal / "session.json").read_bytes())["recovery"]

def selection(command):
parts = bytearray()
Expand Down Expand Up @@ -409,11 +429,16 @@ def selection(command):
assert goal_path not in initial and todo_path not in initial
assert initial["/goal_boundary/write_scope_pointer"] == goal_path
detail = initial["/context_details/unread_context_index/source"]
_, exact = selection(
"quota context-read "
f"--capture-file {shlex.quote(detail['path'])} --capture-sha256 {detail['sha256']} "
f"--select {goal_path} --select {todo_path}"
)
template = shlex.split(initial["/context_details/command_template"])
delivered_reader = shlex.split(view["recovery"]["command"])
assert template[-2:] == ["--select", "<pointer>"]
assert template[:template.index("--format")] == delivered_reader[:delivered_reader.index("--format")]
assert template[template.index("--capture-file") + 1] == detail["path"]
assert template[template.index("--capture-sha256") + 1] == detail["sha256"]
code, rejected = cli._run_cli(registry, runtime, *delivered_reader[delivered_reader.index("quota"):],
"--select", goal_path, cwd=project)
assert code != 0 and rejected["diagnostic_code"] == "context_selection_missing_pointer"
_, exact = selection(shlex.join([*template[:-1], goal_path, "--select", todo_path]))
assert exact[goal_path] == goal_scopes and exact[todo_path] == todo_scopes
assert cli._heartbeat_receipt_count(runtime, turn) == 1

Expand Down
Loading