Skip to content
Open
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
10 changes: 10 additions & 0 deletions docs/reference/required-work-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,16 @@ evidence and the complete operation/settlement contract before depending on them
The original SHA-bound full recovery remains available; a selected page's EOF
does not prove complete source delivery, model retention or fresh authority.

If the local Effect runtime is unavailable while planning a selected read,
the reader returns a runtime diagnostic and a `recovery_command` for the same
capture and cursor. After restoring the runtime, use that command to retry the
selected read with its original digests. A full-file read can verify and read
the capture directly while the selector is unavailable.

选读规划时若本地 Effect 运行时不可用,读取器会返回运行时诊断和绑定原捕获与原游标的
`recovery_command`。恢复运行时后,可用该命令按原摘要重试选读。选读服务不可用期间,
仍可按原摘要验证和读取完整捕获。

For an exact complete Turn bound to a Todo whose dated resume condition has
fired, the starting selection puts the existing reopen and same-Turn guard
commands and the current plan's obligations before the longer work context.
Expand Down
16 changes: 16 additions & 0 deletions loopx/cli_commands/quota_context_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ def read_context_capture(args: argparse.Namespace, *, presentation: dict[str, An
cannot silently mix two decisions or detail views.
EOF describes this page, never a model's complete-consumption receipt.
"""
runtime_read_retry = None
try:
digest = getattr(args, "capture_sha256", None)
value = getattr(args, "capture_file", None)
Expand Down Expand Up @@ -406,6 +407,19 @@ def read_context_capture(args: argparse.Namespace, *, presentation: dict[str, An
"recovery": ("Use recovery_command to read the original capture from offset zero; "
if initial_read else "Use recovery_command to restart the original selected read from offset zero; ")
+ "this read performs no guard, admission or spend."}
except EffectRuntimeStartupError:
# The source already passed its digest check. Retain the
# caller's cursor, including a historical reference.
unpinned = pinned_selection is None
runtime_read_retry = context_capture_read_command(path, digest, offset=offset,
page_bytes=size, max_page_output_bytes=output_limit,
select=selectors if unpinned else None,
selection_sha256=selection_digest if unpinned else None,
list_fields=list_fields if unpinned else False,
list_depth=list_depth if unpinned else None,
initial_read=initial_read if unpinned else False, reference_file=reference_file,
reader_argv=reader_argv, compact=bound_route is not None)
raise
if rejection := plan.get("rejected_selection"):
# TS alone resolves the nearest container. Reuse the original
# escaped tokens, without parsing diagnostic prose or traversing
Expand Down Expand Up @@ -460,6 +474,8 @@ def read_context_capture(args: argparse.Namespace, *, presentation: dict[str, An
result["diagnostic_code"] = exc.diagnostic_code
result["recovery"] = ("Resolve the reported runtime failure, then retry reading the same digest-bound capture; "
"no guard, admission or spend was performed.")
if runtime_read_retry is not None:
result["recovery_command"] = runtime_read_retry

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里追加完整重试命令后直接返回,跳过了序列化预算检查。相同参数的正常响应为 746 字节,显式上限为 754 字节。临时目录故障时实际输出为 863 字节,截在上限会丢失可解析 JSON。请在此错误分支保住上限,并补一个正常可读但完整失败命令放不下的 CLI 用例。短错误可以引导用户恢复运行时后重试原参数。

if isinstance(exc, EffectRuntimeRemoteError):
result["error_kind"] = exc.error_kind
if exc.error_kind == "request_rejected":
Expand Down
10 changes: 9 additions & 1 deletion loopx/control_plane/effect_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1556,7 +1556,15 @@ def effect_runtime_request(
"""Call the managed TS runtime, retrying only idempotent typed effects."""

fingerprint = _runtime_fingerprint_for_request()
info_path = _runtime_info_path(fingerprint)
try:
info_path = _runtime_info_path(fingerprint)
except OSError as exc:
# tempfile may fail before we have a locator or dispatch a request.
raise EffectRuntimeStartupError(
"TypeScript Effect runtime temporary directory is unavailable. "
"Check the host temporary directory's write access and free space.",
diagnostic_code="runtime_request_failed",
) from exc
request_id = str(uuid.uuid4())
last_error: OSError | RuntimeError | None = None
for attempt in range(2 if retry_safe else 1):
Expand Down
1 change: 1 addition & 0 deletions skills/loopx-self-repair/references/repair-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ teaches a reusable control-plane lesson.

| Pattern | Symptoms | Evidence To Read | Likely Root | Durable Repair |
| --- | --- | --- | --- | --- |
| `selected_read_runtime_directory_unavailable` | `quota context-read --select` reports that the original capture could not be read while a full read verifies the same digest. | Verify the original capture through its full reader, then compare the selected read and the local runtime temporary-directory condition. | Resolving the local Effect runtime locator can fail before dispatch and surface as a capture error. | Classify the local runtime failure at its owner. Retry the generated `recovery_command` after restoring temporary-directory access or space. Verify both digests and the original cursor through the same read entrypoint. |
| `authority_fixture_provider_aliasing` | A fixture accepts a requested backend name but initializes another provider, so a passing test can be mislabeled as real-backend qualification. | Requested provider, actual canonical provider revision/readback, physical store and writer-fence effects; verify the same fixture on an immutable base. | The fixture handles one opt-in branch and silently uses its default provider for every other value. | Reject unsupported fixture providers before storage or fence effects. Preserve positive real-provider CLI controls and negative no-write/state-preservation controls. Use the existing service-owned fixture for a service backend; an unsupported caller profile remains unqualified rather than gaining a new fallback or execution path. |
| `recorded_turn_version_drift` | An unsupported historical plan, envelope or action signature appears consistent or resumes as a committed replay. | Compare preview, inspection and explicit resume using a journal from the old writer. Change one version declaration at a time and verify capture bytes, Host invocation and quota receipts. | A historical reader extracts identity or replays the receipt without applying the version check used by the Host. | Use the typed plan source reader for resume and journal interpretation. Preserve valid historical records, and refuse unsupported declarations before recovery. Prove refusal and original replay through File and SQLite. |
| `complete_source_retry_callback_drift` | A valid complete-source Host request reaches normal execution, but its failed Session retry gives the binding callback an empty envelope and rejects the original actor. | Declared current and historical request versions, a provider callback that reads its argument, real File/SQLite sources, saved journal/capture bytes, retry actions and settlement observations. | The writer removed the current envelope while a recovery reader still selects that field; callbacks that ignore their argument hide the migration gap. | Validate supplied complete material with the existing source owner, then deliver the callback body by the recorded wire version. Current requests use the complete decision; v0 keeps its original envelope even with a complete sidecar. Refuse malformed/mixed current input before provider IO. Test original-Session resume, actor/work drift refusal, immutable source/journal recovery and once-only results/effects. Recorded callback counts do not establish real model adoption or canonical settlement. |
Expand Down
56 changes: 56 additions & 0 deletions tests/control_plane/test_context_selection_transport.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
"""Selection planning may omit scalar prose; captured values and navigation stay exact."""
import argparse
import errno
import hashlib
import json
import shlex
import tempfile

import pytest

from loopx import cli
from loopx.cli_commands.quota_capture import read_context_capture
from loopx.control_plane.quota import turn_envelope
from loopx.control_plane.turn_driver.decision_capture import context_capture_read_command, write_context_read_reference


def captured_reader(tmp_path, value, **options):
Expand Down Expand Up @@ -116,3 +121,54 @@ def test_full_reader_stays_independent_of_selection_runtime(tmp_path, transporte
page = read_context_capture(args)
assert page["ok"] and page["eof"] and page["content"].encode() == raw
assert transported_contexts == []


@pytest.mark.parametrize("mode", ["direct", "continuation", "reference"])
def test_selected_reader_retries_exact_capture_after_runtime_tempdir_failure(tmp_path, monkeypatch, capsys, mode):
value = {"stop": "Keep the complete original decision. " * 22, "other": 42}
path, raw, capture = captured_reader(tmp_path, value)
reference = write_context_read_reference(path, capture.capture_sha256) if mode == "reference" else None
selected = context_capture_read_command(path, capture.capture_sha256,
select=["/stop"], page_bytes=256, max_page_output_bytes=12000, reference_file=reference)
whole = context_capture_read_command(path, capture.capture_sha256)

def read_args(command):
words = shlex.split(command)
return words[words.index("--format"):]

def run(command):
code = cli.main(read_args(command))
return code, json.loads(capsys.readouterr().out)

first_content = ""
if mode == "continuation":
code, page = run(selected)
assert code == 0 and not page["eof"]
first_content = page["content"]
selected = page["next_command"]

def unavailable_tempdir():
raise FileNotFoundError(errno.ENOENT, "No usable temporary directory found", "fixture-private-path")

with monkeypatch.context() as fault:
fault.setattr(tempfile, "gettempdir", unavailable_tempdir)
code, complete = run(whole)
assert code == 0 and complete["eof"] and complete["content"].encode() == raw
code, failure = run(selected)
assert code == 1 and failure["ok"] is False
assert failure["diagnostic_code"] == "runtime_request_failed"
assert "temporary directory" in failure["reason"]
assert "fixture-private-path" not in json.dumps(failure)
assert "content" not in failure
assert read_args(failure["recovery_command"]) == read_args(selected)

pieces = [first_content]
next_command = failure["recovery_command"]
while next_command:
code, page = run(next_command)
assert code == 0 and page["offset"] == sum(len(piece.encode()) for piece in pieces)
pieces.append(page["content"])
next_command = page.get("next_command")
assert page["eof"]
assert json.loads("".join(pieces))["selections"] == [{"pointer": "/stop", "value": value["stop"]}]
assert path.read_bytes() == raw
Loading