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
2 changes: 1 addition & 1 deletion docs/reference/required-work-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ full/delta 字节比较计入这些 reader 命令元数据;既有进程内引
沿同一游标查阅未结外发委派。只含外发摘要的续页不送达或消费结果。
`Peer` 回传只有在送达回执绑定请求 ID 和确切结果键时才折叠简报。缺少绑定的旧回执
继续保留完整简报,直到有权限的读取实际交付该条结果。
`unavailable_count` 大于零时须恢复对应收执。收件全文用不带
`unavailable_count` 大于零时须恢复对应回执。收件全文用不带
`--attention-only` 的 `--request-id` 精读。Goal 外发委派可在同一 Goal 下用
摘要中的接收方 `agent_id` 和精确 `request_id` 查阅 `manager-inbox status`。
原摘要仍可从同一捕获取回。
Expand Down
7 changes: 4 additions & 3 deletions loopx/capabilities/manager_context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -757,9 +757,10 @@ and are not paginated by this cursor. `status --offset/--limit` remains separate
Large Markdown Inbox responses open with a reference to a private capture.
The generated native context configuration declares
`LOOPX_CONTEXT_PAGE_OUTPUT_BYTES=64000` for tools that can retain that size.
The Inbox uses that profile for both capture reader commands and keeps the
opening within 12,000 bytes. Without that declaration the reader also stays
within 12,000 bytes. Follow the capture's byte cursors and verify coverage before
The Inbox uses that profile for both capture reader commands. The Markdown
response and capture opening stay within 5,000 serialized bytes. Without the
declaration, both reader commands use the same 5,000-byte limit. Follow the
capture's byte cursors and verify coverage before
using the Inbox cursor. If a reader output is truncated, reduce both page
limits and recover the affected range of the same capture.

Expand Down
7 changes: 4 additions & 3 deletions loopx/cli_commands/manager_inbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,12 @@ def _render_read_markdown(result: dict) -> str:
def _read_markdown(result: dict, *, runtime_root: Path) -> tuple[str, bool]:
"""Deliver the already-recorded scoped read without repeating its effects."""
from ..control_plane.turn_driver.native_context_profile import (
NATIVE_CONTEXT_FIRST_READ_FALLBACK_BYTES,
NATIVE_CONTEXT_OUTPUT_ENV,
NATIVE_INBOX_MARKDOWN_OUTPUT_BYTES,
native_context_page_budget,
)

limit = NATIVE_CONTEXT_FIRST_READ_FALLBACK_BYTES
limit = NATIVE_INBOX_MARKDOWN_OUTPUT_BYTES
view = _share_item_guidance(result)
body = _render_read_markdown(view)
size = len((body + os.linesep).encode("utf-8"))
Expand Down Expand Up @@ -151,7 +151,8 @@ def _read_markdown(result: dict, *, runtime_root: Path) -> tuple[str, bool]:
"Follow next_command through eof in UTF-8 byte-offset order. Compare each reported digest with "
"this opening's SHA-256. Check each "
"page's content length against its offsets, and complete coverage through total_bytes. "
"If output is missing or truncated, reread that range of the same capture with a smaller page. "
"If output is missing or truncated, reread that range of the same capture with smaller "
"--page-bytes and --max-page-output-bytes. "
+ CONTEXT_CAPTURE_CODE_MODE_GUIDANCE
+ "Apply any shared_item_guidance to the items on this page. After the page is complete, "
"follow its next_cursor, operation_handoff_next_cursor, or native_child_results.next_cursor with the original Inbox command. "
Expand Down
10 changes: 7 additions & 3 deletions loopx/control_plane/collaboration/inbox_read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ const TURN_INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
const INBOX_PAGE_SIZE = 20;
const ATTENTION_GUIDANCE = " Reconcile open_request_summaries together with items on every page, including pages with no full briefs. " +
"For an incoming summary, use the unfiltered read command with --request-id for the full current brief before working on or returning it. " +
"Use the existing scoped request status for sent requests; follow next_cursor to reach their summaries.";
"Use the existing scoped request status for sent requests and follow next_cursor to reach their summaries. " +
"An unavailable_count above zero requires receipt recovery.";
type InboxSource = Readonly<{root: string; goal: string; agent: string; scope: JsonObject; exact: boolean; recipient?: JsonObject}>;
type ReturnDelivery = Readonly<{key: string; request: JsonObject; reply: JsonObject}>;
type PeerReturnPage = Readonly<{scope: string; afterOperation: string; afterResult: string}>;
Expand Down Expand Up @@ -281,10 +282,13 @@ async function pendingPage(source: InboxSource, params: JsonObject): Promise<Jso
}
const page = entries.slice(0, INBOX_PAGE_SIZE);
const moreIncoming = entries.length > page.length;
const nextCursor = moreIncoming ? `1:${scope}:${page.at(-1)!.item.request_id}`
: outgoingScope === null ? null : (await outgoingSummaryPage(source, outgoingScope, "", 0)).next_cursor;
const outgoing = !moreIncoming && outgoingScope !== null
? await outgoingSummaryPage(source, outgoingScope, "", 0) : null;
const nextCursor = moreIncoming ? `1:${scope}:${page.at(-1)!.item.request_id}` : outgoing?.next_cursor ?? null;
return {ok: true, items: page.filter(entry => !entry.summary).map(entry => entry.item),
...(attentionOnly ? {open_request_summaries: page.filter(entry => entry.summary).map(entry => entry.item)} : {}),
...(outgoing && nextCursor === null && outgoing.unavailable_count > 0
? {unavailable_count: outgoing.unavailable_count} : {}),
has_more: nextCursor !== null, next_cursor: nextCursor, _cursor_scope: operationCursorScope,
instruction: TRIAGE + (attentionOnly ? ATTENTION_GUIDANCE : "") +
" Follow next_cursor to read later pending requests. Restart without a cursor to discover new " +
Expand Down
3 changes: 3 additions & 0 deletions loopx/control_plane/turn_driver/native_context_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
# Native openings cross a tool boundary, whether attached or linked. When
# that tool's cap is unknown, avoid the bulk-reader profile.
NATIVE_CONTEXT_FIRST_READ_FALLBACK_BYTES = 12000
# A Markdown Inbox capture must remain readable in shells that do not
# declare the larger native profile, including with multilingual briefs.
NATIVE_INBOX_MARKDOWN_OUTPUT_BYTES = 5000
# Keep the configuration declaration usable by older installed readers too.
NATIVE_CONTEXT_LARGE_OUTPUT_BYTES = 64000
NATIVE_CONTEXT_HISTORY_TOKENS = 20000
Expand Down
17 changes: 17 additions & 0 deletions tests/control_plane_ts/inbox_read_transaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,3 +431,20 @@ test("the attention cursor reaches all open sent requests without redelivering a
assert.doesNotMatch(JSON.stringify(summaries), /PRIVATE_LONG_SOURCE|Checked result/);
assert.deepEqual(sourceBytes(replies), originalReceipt);
});
test("terminal attention page reports unreadable sent requests even without a continuation", async t => {
const f = fixture(t);
const operations = join(f.base, "peer-operations", targets.exact);
mkdirSync(operations, {recursive: true});
const request = f.row(101, {agent_id: "reviewer", source_kind: "peer", source_agent_id: "worker"});
writeFileSync(join(operations, request.request_id + ".json"), JSON.stringify(request));
const before = sourceBytes(operations);

const ordinary = (await f.call("pending")).result as JsonObject;
assert.equal(ordinary.unavailable_count, undefined);
const attention = (await f.call("pending", {attention_only: true})).result as JsonObject;
assert.deepEqual(attention.items, []);
assert.deepEqual(attention.open_request_summaries, []);
assert.equal(attention.next_cursor, null);
assert.equal(attention.unavailable_count, 1);
assert.deepEqual(sourceBytes(operations), before);
});
69 changes: 49 additions & 20 deletions tests/test_delegation_turn_context.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
"""Real receipt/store journeys: a Turn agenda does not complete or replay work."""
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import sysconfig
from pathlib import Path

import pytest
import test_manager_context_roundtrip as roundtrip_tests

from loopx.capabilities.manager_context import acknowledge, deliver, turn_start_hook, _root, _write
from loopx.capabilities.manager_context.roundtrip import report, drain
from loopx.capabilities.manager_context import (
_root,
_write,
acknowledge,
deliver,
turn_start_hook,
)
from loopx.capabilities.manager_context.roundtrip import drain, report
from loopx.control_plane.capability_hooks import dispatch_turn_start_hooks
from loopx.control_plane.collaboration.peers import request, read_inbox, consume_return
from loopx.control_plane.collaboration.turn_context_observation import read_delegation_turn_context
import test_manager_context_roundtrip as roundtrip_tests
from loopx.control_plane.collaboration.peers import consume_return, read_inbox, request
from loopx.control_plane.collaboration.turn_context_observation import (
read_delegation_turn_context,
)


@pytest.fixture
Expand Down Expand Up @@ -290,17 +298,25 @@ def test_separate_agent_has_no_access_to_another_receivers_agenda(flow):

@pytest.mark.skipif(os.name != "posix", reason="native context delivery requires POSIX")
@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("reader_output_bytes", [12_000, 64_000])
@pytest.mark.parametrize("reader_output_bytes", [5_000, 64_000])
def test_unbound_cli_first_read_leaves_inbox_rows_to_its_required_read(
tmp_path, monkeypatch, provider, reader_output_bytes,
):
from loopx.control_plane.turn_driver.decision_capture import (
read_context_read_reference,
)
from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime
from tests.control_plane.test_context_first_read import read_selection
from tests.control_plane.test_quota_settlement_cli import (
AGENT_ID, GOAL_ID, TURN_ID, _heartbeat_receipt_count, _initialize_fixture_authority,
_run_cli, _spend_run_count, _write_fixture,
AGENT_ID,
GOAL_ID,
TURN_ID,
_heartbeat_receipt_count,
_initialize_fixture_authority,
_run_cli,
_spend_run_count,
_write_fixture,
)
from loopx.control_plane.turn_driver.decision_capture import read_context_read_reference

isolate_sqlite_runtime(tmp_path, monkeypatch)
monkeypatch.delenv("CODEX_THREAD_ID", raising=False)
Expand Down Expand Up @@ -404,7 +420,7 @@ def read_receipts():
if logical_pages == 1:
reference_path.unlink()
failed = subprocess.run(shlex.split(page["command"]), cwd=project, capture_output=True, timeout=40)
assert failed.returncode == 1 and len(failed.stdout) <= 12_000
assert failed.returncode == 1 and len(failed.stdout) <= 5_000
assert "content" not in json.loads(failed.stdout)
recovered = json.loads(invoke(direct, reader_output_bytes))
assert recovered["offset"] == 0 and recovered["sha256"] == pinned
Expand All @@ -420,7 +436,7 @@ def read_receipts():
if cursor is None:
break
assert seen == request_ids and logical_pages == 2 and captured_pages > 1
assert (largest_reader_output > 12_000) is (reader_output_bytes > 12_000)
assert (largest_reader_output > 5_000) is (reader_output_bytes > 5_000)
_, saved = read_selection(view["recovery"]["command"] + " --select " + shlex.quote(address))
assert saved[address] == channel["work_context"]["sources"][index]["content"]["unfinished_delegations"]
assert path.read_bytes() == original
Expand All @@ -442,7 +458,7 @@ def test_large_inbox_does_not_fall_back_to_unbounded_output(flow):
invocation = [sys.executable, "-m", "loopx.entrypoint", "--registry", str(registry), "--runtime-root", str(root),
"manager-inbox", "read", "--format", "markdown", "--goal-id", "research", "--agent-id", "worker"]
result = subprocess.run(invocation, cwd=root, capture_output=True, timeout=40)
assert result.returncode == 1 and len(result.stdout) <= 12_000
assert result.returncode == 1 and len(result.stdout) <= 5_000
output = result.stdout.decode()
failure = json.loads(output.split("\n```json\n", 1)[1].removesuffix("\n```\n"))
assert not failure["ok"] and not failure["read_complete"]
Expand Down Expand Up @@ -479,7 +495,7 @@ def test_large_inbox_reader_commands_run_verbatim_in_powershell(flow, directory)
opening = subprocess.run([*powershell, "-Command", required_read["command"]], cwd=root, env=environment,
capture_output=True, timeout=60)
assert opening.returncode == 0, opening.stderr
assert 0 < len(opening.stdout) <= 12_000
assert 0 < len(opening.stdout) <= 5_000
markdown = opening.stdout.decode().replace("\r\n", "\n")
view = json.loads(markdown.split("\n```json\n", 1)[1].removesuffix("\n```\n"))
before = {p.relative_to(root): p.read_bytes() for p in _root(root).rglob("*.json")}
Expand All @@ -490,7 +506,7 @@ def test_large_inbox_reader_commands_run_verbatim_in_powershell(flow, directory)
output = subprocess.run([*powershell, "-Command", command], cwd=root, env=environment,
capture_output=True, timeout=60)
assert output.returncode == 0, output.stderr
assert 0 < len(output.stdout) <= 12_000
assert 0 < len(output.stdout) <= 5_000
page = json.loads(output.stdout)
assert page["ok"] and page["offset"] == len(original) and page["sha256"] == view["sha256"]
original.extend(page["content"].encode())
Expand All @@ -510,11 +526,19 @@ def test_large_inbox_reader_commands_run_verbatim_in_powershell(flow, directory)
def test_actual_cli_guards_and_host_envelopes_preserve_the_agenda(
tmp_path, monkeypatch, provider, delivery, partial, parent_context,
):
from control_plane.canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime
from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection
from control_plane.canonical_authority_fixture import (
initialize_canonical_authority,
isolate_sqlite_runtime,
)

from loopx.control_plane.coordination.runtime_shadow import (
build_todo_runtime_shadow_projection,
)
from loopx.control_plane.testing.canary_harness import write_fixture_registry
from loopx.control_plane.todos.active_state_todo_parser import parse_todo_source
from loopx.control_plane.todos.goal_todo_projection import retained_todo_summary_fields
from loopx.control_plane.todos.goal_todo_projection import (
retained_todo_summary_fields,
)
if provider == "sqlite":
isolate_sqlite_runtime(tmp_path, monkeypatch)
# A module launched from the checkout can mask a stale inherited package.
Expand Down Expand Up @@ -581,7 +605,10 @@ def run(*arguments):
assert code == 0 and tracking["rows"][0]["read"]["at"]
before = {p.relative_to(root): p.read_bytes() for p in _root(root).rglob("*.json")}
if delivery == "native_files":
from loopx.control_plane.turn_driver.codex_context import codex_context_directory, codex_context_hook
from loopx.control_plane.turn_driver.codex_context import (
codex_context_directory,
codex_context_hook,
)
(tmp_path / "captures").mkdir()
(tmp_path / "context").mkdir(mode=0o700)
monkeypatch.setenv("CODEX_THREAD_ID", "agenda-session")
Expand Down Expand Up @@ -623,7 +650,9 @@ def run(*arguments):
assert page["next_offset"] == len(content) > page["offset"]
command = page["next_command"]
assert pages > 1, "Exercise complete selected-context pagination."
from tests.control_plane.codex_checkpoint_fixture import selected_context_values
from tests.control_plane.codex_checkpoint_fixture import (
selected_context_values,
)

values = selected_context_values(content.decode("utf-8"))
pointer = next(key for key in values if key.endswith("/content/unfinished_delegations"))
Expand Down
Loading