From ee8c798cef9e22fdcde7b9674511dbb2b79d43f1 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:45:58 +0800 Subject: [PATCH 1/3] fix(collaboration): read pending peer results without reopening the Inbox Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/capabilities/manager_context/README.md | 23 +++-- loopx/collaboration_mcp.py | 15 +++ loopx/control_plane/collaboration/peers.py | 32 +++++- tests/test_collaboration_mcp.py | 100 ++++++++++++++++++- 4 files changed, 154 insertions(+), 16 deletions(-) diff --git a/loopx/capabilities/manager_context/README.md b/loopx/capabilities/manager_context/README.md index ac38d7bf00..658ba99e36 100644 --- a/loopx/capabilities/manager_context/README.md +++ b/loopx/capabilities/manager_context/README.md @@ -250,11 +250,11 @@ work-context sources, while the full result text remains behind the existing does not interrupt an active Turn or treat visibility as consumption. Ordinary peer results may wait for the next work Turn. Cancellation, blocking -and priority-control paths keep their immediate handling. The invocation-bound -`read_context` tool records a `model_turn` supply fact for the results it -returns. The required CLI read and its paged recovery record transport delivery. -Peer results stay eligible for the next Turn until a bound Turn accepts or -rejects them. +and priority-control paths keep their immediate handling. Use the invocation-bound +`read_peer_returns` tool when only the peer results need review. It records the +same `model_turn` supply fact as the full `read_context` tool. The required CLI +read and its paged recovery record transport delivery. Peer results stay +eligible for the next Turn until a bound Turn accepts or rejects them. Outgoing requests to an original project conversation use the same typed address reader as explicit peer returns. The agenda retains that conversation recipient @@ -1153,9 +1153,11 @@ granting execution, changing priorities or broadening the return audience. The peer independently acknowledges a request and reports a conclusion through the same commands as a manager request. The original requester can inspect it under `peer_returns` in `manager-inbox read`. In a host with the -invocation-bound tools configured, use `read_context` to receive the result and -`consume_peer_result` after checking it. The result also carries a CLI -acknowledgement command for that exact delivery: +invocation-bound tools configured, call `read_peer_returns` for the results alone +and `consume_peer_result` after evaluating them. A read records delivery and +leaves the results pending. A true `has_more` indicates that additional results +are pending beyond the current window. The full `read_context` response also +carries a CLI acknowledgement command for each exact delivery: ```sh loopx manager-inbox acknowledge-return --goal-id allocation --agent-id builder \ @@ -1224,9 +1226,10 @@ the normal governed Turn arguments: ``` Use the Python interpreter with this LoopX checkout/release installed and -absolute configuration paths. Each server exposes only `read_context`, +absolute configuration paths. Each server exposes `read_context`, `assess_request`, `link_work`, `request_peer`, `return_result` and `consume_peer_result`. -The managed invocation supplies the current Turn key to the scoped tool process. +A managed invocation supplies the current Turn key to the scoped tool process. +Only a bound process also exposes `read_peer_returns`. Identity and filesystem roots are host-bound. Every call rechecks the registered actor. The server has no shell, Todo/lease writer, credential tools or network listener. Installing/configuring it does not diff --git a/loopx/collaboration_mcp.py b/loopx/collaboration_mcp.py index 75ad729df6..334b9595c7 100644 --- a/loopx/collaboration_mcp.py +++ b/loopx/collaboration_mcp.py @@ -74,6 +74,7 @@ read_inbox, request, require_operation_id, + read_turn_peer_returns, ) from .presentation.answer_instruction import ( collaboration_answer_instruction, @@ -284,6 +285,20 @@ def read_context(cursor: str | None = None) -> dict: result["instruction"] += " " + collaboration_answer_instruction() return result + if turn_instance_id is not None: + @server.tool() + def read_peer_returns() -> dict: + """Read only peer results awaiting review by this bound work Turn. + + Evaluate the returned result and use consume_peer_result to accept, + defer or reject it. A read leaves the result pending. If has_more + is true, more results are still pending beyond this bounded window. + """ + return {"peer_returns": read_turn_peer_returns( + root, registry, goal_id, agent_id, + turn_instance_id=turn_instance_id, caller_goal_ref=caller_goal_ref, + )} + @server.tool() def assess_request( request_id: str, diff --git a/loopx/control_plane/collaboration/peers.py b/loopx/control_plane/collaboration/peers.py index 84984ab33b..01cb46d19c 100644 --- a/loopx/control_plane/collaboration/peers.py +++ b/loopx/control_plane/collaboration/peers.py @@ -326,12 +326,34 @@ def request( -def returns(root, goal_id, agent_id, *, mark_read=False, scope=None): +def returns(root, goal_id, agent_id, *, mark_read=False, scope=None, turn_instance_id=None): + """Read outgoing peer results through the shared Inbox transaction.""" from .inbox import read_inbox_transaction - return read_inbox_transaction(root, { + query = { "operation": "returns", "goal_id": goal_id, "agent_id": agent_id, "mark_read": mark_read, - }, scope=scope) + } + if turn_instance_id is not None: + query["turn_instance_id"] = turn_instance_id + return read_inbox_transaction(root, query, scope=scope) + + +def read_turn_peer_returns(root, registry, goal_id, agent_id, *, + turn_instance_id: str, caller_goal_ref): + """Supply pending peer results under the host's current Goal and Turn.""" + from ..effect_runtime import EffectRuntimeResponseAmbiguous + + try: + with collaboration_goal_scope( + registry, goal_id=goal_id, agents=(agent_id,), caller_goal_ref=caller_goal_ref, + ) as scope: + return returns(root, goal_id, agent_id, mark_read=True, scope=scope, + turn_instance_id=turn_instance_id) + except EffectRuntimeResponseAmbiguous as exc: + raise ValueError( + "Peer result delivery is uncertain. Repeat the same peer result read in this work Turn " + "before acknowledging it." + ) from exc def _deferred_acknowledgement( @@ -764,8 +786,8 @@ def read_inbox( ) else: result["followthrough"] += ( - " Peer conclusions stay pending after this read. Use the current host-bound " - "read_context tool to receive them for acknowledgement when it is available." + " Peer conclusions stay pending after this read. In a bound work Turn, use " + "read_peer_returns and then consume_peer_result after evaluating each result." ) if result.get("native_child_results", {}).get("items"): result["followthrough"] += ( diff --git a/tests/test_collaboration_mcp.py b/tests/test_collaboration_mcp.py index e84c39b779..f0482a4813 100644 --- a/tests/test_collaboration_mcp.py +++ b/tests/test_collaboration_mcp.py @@ -52,8 +52,13 @@ def test_stdio_lost_read_response_preserves_original_page_and_result_receipts(tm from loopx.collaboration_mcp import main transport = inbox.read_inbox_transaction records = 0 +lost_peer_read = False def interrupted(root, query, **kwargs): - global records + global records, lost_peer_read + if query["operation"] == "returns" and not lost_peer_read: + lost_peer_read = True + transport(root, query, **kwargs) + raise EffectRuntimeResponseAmbiguous("collaboration.inbox.read", timeout=10) if query["operation"] == "record_read": records += 1 if records == 2: @@ -109,6 +114,19 @@ async def exercise(): disposition = {"request_id": rid, "disposition": "accepted"} refused = await session.call_tool("consume_peer_result", disposition) assert refused.isError and "read the peer conclusion" in refused.content[0].text + + failed_peer_read = await session.call_tool("read_peer_returns", {}) + assert failed_peer_read.isError and "Repeat the same peer result read in this work Turn" in failed_peer_read.content[0].text + assert "Private peer conclusion" not in failed_peer_read.content[0].text + delivery = _root(tmp_path) / "replies" / rid / "conclusion.delivery.json" + receipt = delivery.read_bytes() + assert json.loads(receipt)["model_turn"]["turn_instance_id"] == turn_key + recovered_peer = await session.call_tool("read_peer_returns", {}) + assert not recovered_peer.isError + result, = json.loads(recovered_peer.content[0].text)["peer_returns"]["items"] + assert result["request_id"] == rid and result["text"] == "Private peer conclusion" + assert delivery.read_bytes() == receipt + assert [_receipt(tmp_path, "reads", row)[0] for row in tail] == receipts recovered = await session.call_tool("read_context", {"cursor": cursor}) assert not recovered.isError assert {row["request_id"] for row in json.loads(recovered.content[0].text)["items"]} == {row["request_id"] for row in tail} @@ -129,6 +147,8 @@ async def exercise(): revoked = await session.call_tool("read_context", {"cursor": cursor}) assert revoked.isError and "requires registered Agents" in revoked.content[0].text assert '"recovery"' not in revoked.content[0].text + blocked_peer_read = await session.call_tool("read_peer_returns", {}) + assert blocked_peer_read.isError and "requires registered Agents" in blocked_peer_read.content[0].text asyncio.run(exercise()) @@ -286,6 +306,84 @@ async def exercise(): asyncio.run(exercise()) +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_bound_peer_read_preserves_result_without_resupplying_inbox(tmp_path, monkeypatch, provider): + from loopx.control_plane.collaboration.inbox import _root, acknowledge + from loopx.control_plane.collaboration.peers import request, return_result + from loopx.control_plane.turn_driver.codex_cli import ( + LOOPX_DELEGATION_CODEX_MCP_SERVER_NAME, collaboration_mcp_turn_environment, + ) + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime, promoted_create_fixture + + isolate_sqlite_runtime(tmp_path, monkeypatch) + registry, root, _ = promoted_create_fixture(tmp_path, provider=provider) + config = json.loads(registry.read_text()) + config["goals"][0]["coordination"]["registered_agents"].append("agent-b") + registry.write_text(json.dumps(config)) + brief = {"schema_version": "collaboration_brief_v0", "purpose": "Inspect the artifact", + "context": "Review the evidence.", "constraints": [], "inputs": [], + "acceptance": ["Return the verified finding"], "return_requirement": "Report the result"} + unrelated = {**brief, "context": "Unrelated Inbox evidence. " * 150} + incoming = { + request(root, registry, "goal-a", "agent-b", "agent-a", f"inbox-{index}", unrelated)["request_id"] + for index in range(6) + } + rid = request(root, registry, "goal-a", "agent-a", "agent-b", "peer-review", brief)["request_id"] + acknowledge(root, "goal-a", "agent-b", rid, "adopt", "Review the artifact", registry=registry) + return_result(root, "goal-a", "agent-b", rid, "One finding needs a follow-up.", registry=registry) + delivery = _root(root) / "replies" / rid / "conclusion.delivery.json" + + opening = subprocess.run([sys.executable, "-m", "loopx.entrypoint", "--format", "json", + "--registry", str(registry), "--runtime-root", str(root), "manager-inbox", "read", + "--goal-id", "goal-a", "--agent-id", "agent-a"], capture_output=True, timeout=30, check=True) + opening_view = json.loads(opening.stdout) + assert {row["request_id"] for row in opening_view["items"]} == incoming + assert "read_peer_returns" in opening_view["followthrough"] + assert "model_turn" not in json.loads(delivery.read_text()) + + turn = "sha256:" + "e" * 64 + bound_environment = collaboration_mcp_turn_environment( + {"name": LOOPX_DELEGATION_CODEX_MCP_SERVER_NAME}, turn_key=turn, + lineage={"goal_id": "goal-a", "agent_id": "agent-a"}, project=tmp_path, + ) + params = StdioServerParameters(command=sys.executable, args=[ + "-m", "loopx.collaboration_mcp", "--runtime-root", str(root), + "--registry", str(registry), "--goal-id", "goal-a", "--agent-id", "agent-a", "--workspace", str(tmp_path), + ], env={**os.environ, **bound_environment}) + + async def exercise(): + async with stdio_client(params) as (read, write), ClientSession(read, write) as session: + await session.initialize() + args = {"request_id": rid, "disposition": "accepted"} + unproved = await session.call_tool("consume_peer_result", args) + assert unproved.isError and "in this work Turn" in unproved.content[0].text + + result = await session.call_tool("read_peer_returns", {}) + assert not result.isError + narrow = json.loads(result.content[0].text) + assert set(narrow) == {"peer_returns"} + peer, = narrow["peer_returns"]["items"] + assert peer == opening_view["peer_returns"]["items"][0] + assert peer["request_id"] == rid and peer["text"] == "One finding needs a follow-up." + assert json.loads(delivery.read_text())["model_turn"]["turn_instance_id"] == turn + assert not list((_root(root) / "replies" / rid).glob("*.consumed.json")) + + full = await session.call_tool("read_context", {}) + assert not full.isError + full_view = json.loads(full.content[0].text) + assert {row["request_id"] for row in full_view["items"]} == incoming + previous_peer, = full_view["peer_returns"]["items"] + assert {key: value for key, value in previous_peer.items() if key != "acknowledge_command"} == peer + + consumed = await session.call_tool("consume_peer_result", args) + assert not consumed.isError and json.loads(consumed.content[0].text)["status"] == "consumed" + empty = await session.call_tool("read_peer_returns", {}) + assert not empty.isError + assert json.loads(empty.content[0].text) == {"peer_returns": {"items": [], "has_more": False}} + + asyncio.run(exercise()) + + @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_stdio_receiver_links_existing_work_and_returns_without_duplicate_tasks(tmp_path, monkeypatch, provider): from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime, promoted_create_fixture From fce0ce7c9baed96855bbd4883578a2ba3be5af35 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:26:44 +0800 Subject: [PATCH 2/3] fix(collaboration): continue past the first page of peer results Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/capabilities/manager_context/README.md | 12 +-- loopx/collaboration_mcp.py | 8 +- .../control_plane/collaboration/inbox_read.ts | 32 +++++-- loopx/control_plane/collaboration/peers.py | 8 +- tests/test_collaboration_mcp.py | 88 +++++++++++++++++++ 5 files changed, 131 insertions(+), 17 deletions(-) diff --git a/loopx/capabilities/manager_context/README.md b/loopx/capabilities/manager_context/README.md index 658ba99e36..59ed1ef4b6 100644 --- a/loopx/capabilities/manager_context/README.md +++ b/loopx/capabilities/manager_context/README.md @@ -1155,9 +1155,11 @@ through the same commands as a manager request. The original requester can inspect it under `peer_returns` in `manager-inbox read`. In a host with the invocation-bound tools configured, call `read_peer_returns` for the results alone and `consume_peer_result` after evaluating them. A read records delivery and -leaves the results pending. A true `has_more` indicates that additional results -are pending beyond the current window. The full `read_context` response also -carries a CLI acknowledgement command for each exact delivery: +leaves the results pending. Follow `next_cursor` as `cursor` in the same Turn to +read later results even when earlier ones are deferred. Omit the cursor to +restart the live scan and discover results added before the previous page +boundary. The full `read_context` response also carries a CLI acknowledgement +command for each exact delivery: ```sh loopx manager-inbox acknowledge-return --goal-id allocation --agent-id builder \ @@ -1173,8 +1175,8 @@ Consumption does not mark a Todo done or certify peer acceptance. The requester checks the actual artifact, incorporates or rejects the findings, and reports the original owner conclusion through its original request. A second review round uses a new operation id. Repeating an operation recovers the same request; -changing its content or recipient is rejected. Peer replies currently support -one conclusion (including an explicit blocker/defer result), not interim replies. +changing its content or recipient is rejected. Peer replies use the conclusion +phase for results, later updates and explicit blockers. Parent lineage preserves the original owner context through peer requests. External-audience parent requests cannot be forwarded through this owner-local diff --git a/loopx/collaboration_mcp.py b/loopx/collaboration_mcp.py index 334b9595c7..b43c7e90ed 100644 --- a/loopx/collaboration_mcp.py +++ b/loopx/collaboration_mcp.py @@ -287,16 +287,16 @@ def read_context(cursor: str | None = None) -> dict: if turn_instance_id is not None: @server.tool() - def read_peer_returns() -> dict: + def read_peer_returns(cursor: str | None = None) -> dict: """Read only peer results awaiting review by this bound work Turn. Evaluate the returned result and use consume_peer_result to accept, - defer or reject it. A read leaves the result pending. If has_more - is true, more results are still pending beyond this bounded window. + defer or reject it. Follow next_cursor in this Turn for more + results. Omit cursor to start a fresh scan. """ return {"peer_returns": read_turn_peer_returns( root, registry, goal_id, agent_id, - turn_instance_id=turn_instance_id, caller_goal_ref=caller_goal_ref, + turn_instance_id=turn_instance_id, caller_goal_ref=caller_goal_ref, cursor=cursor, )} @server.tool() diff --git a/loopx/control_plane/collaboration/inbox_read.ts b/loopx/control_plane/collaboration/inbox_read.ts index df8a4db1a3..5385c9840a 100644 --- a/loopx/control_plane/collaboration/inbox_read.ts +++ b/loopx/control_plane/collaboration/inbox_read.ts @@ -28,6 +28,7 @@ const RESULT_KEY = /^(?:decision|conclusion)(?:-[0-9]{8})?$/; const TURN_INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; 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}>; function fail(message: string): never { throw new EffectRuntimeRequestError(message); } function missing(error: unknown): boolean { return (error as NodeJS.ErrnoException)?.code === "ENOENT"; } @@ -279,13 +280,31 @@ function outgoingEntry(source: InboxSource, operation: JsonObject): JsonObject { || conversation && !equal(row.requester, requester)) fail("peer return scope mismatch"); return row; } -async function collectReturns(source: InboxSource): Promise<{view: JsonObject; deliveries: ReturnDelivery[]}> { +function peerReturnPage(source: InboxSource, params: JsonObject): PeerReturnPage | null { + if (params.turn_instance_id == null && params.cursor == null) return null; + const turn = requireNonEmptyString(params.turn_instance_id, "work Turn identity"); + if (!TURN_INSTANCE_ID.test(turn) || params.mark_read !== true) fail("a bound peer result read is required"); + const scope = digest(["peer_returns_v1", source.root, target(source), turn]); + if (params.cursor == null) return {scope, afterOperation: "", afterResult: ""}; + const match = typeof params.cursor === "string" + ? /^1:([a-f0-9]{64}):([a-f0-9]{64}):(conclusion(?:-[0-9]{8})?)$/u.exec(params.cursor) + : null; + if (!match) fail("invalid peer result cursor"); + const [, suppliedScope, afterOperation, afterResult] = match; + if (suppliedScope !== scope) fail("peer result cursor scope mismatch"); + return {scope, afterOperation, afterResult}; +} + +async function collectReturns(source: InboxSource, page: PeerReturnPage | null = null): + Promise<{view: JsonObject; deliveries: ReturnDelivery[]}> { const items: JsonObject[] = [], deliveries: ReturnDelivery[] = []; if (source.recipient) return {view: {items: [], has_more: false}, deliveries}; + let nextCursor: string | undefined; const folder = join(source.root, "peer-operations", digest(target(source))); for (const [index, name] of names(folder).entries()) { if (index > 0 && index % 128 === 0) await yieldToRuntime(); - if (!name.endsWith(".json") || !BARE_SHA256_PATTERN.test(name.slice(0, -5))) continue; + const operationId = name.slice(0, -5); + if (!name.endsWith(".json") || !BARE_SHA256_PATTERN.test(operationId) || operationId < (page?.afterOperation ?? "")) continue; const operation = readRecord(join(folder, name)); const conversation = operation.schema_version === CONVERSATION_ENTRY_SCHEMA; let row: JsonObject; @@ -294,7 +313,7 @@ async function collectReturns(source: InboxSource): Promise<{view: JsonObject; d const replies = join(source.root, "replies", String(row.request_id)); for (const [resultIndex, key] of resultKeys(replies).entries()) { if (resultIndex > 0 && resultIndex % 128 === 0) await yieldToRuntime(); - if (key === "decision") continue; + if (key === "decision" || (page?.afterOperation === operationId && key <= page.afterResult)) continue; const reply = readRecord(join(replies, key + ".json")), inspected = inspectResult(source.root, row, key, reply); if (["request_id", "goal_id", "agent_id", "source_id", "goal_ref", "recipient", "requester"].some(field => Object.hasOwn(row, field) && !equal(reply[field], row[field])) || reply.phase !== "conclusion" || !inspected) fail("peer reply identity conflict"); @@ -310,13 +329,16 @@ async function collectReturns(source: InboxSource): Promise<{view: JsonObject; d text: reply.text, ...(reply.remaining_work ? {remaining_work: reply.remaining_work} : {}), decision: reply.decision, created_at: reply.created_at}); if (items.length > 20) break; + if (page) nextCursor = `1:${page.scope}:${operationId}:${key}`; deliveries.push({key, request: Object.fromEntries(["request_id", "goal_id", "agent_id", "goal_ref", "recipient", "requester"] .filter(field => Object.hasOwn(row, field)).map(field => [field, row[field]])), reply: Object.hasOwn(reply, "result_key") ? {result_key: reply.result_key} : {}}); } if (items.length > 20) break; } - return {view: {items: items.slice(0, 20), has_more: items.length > 20}, deliveries}; + const hasMore = items.length > 20; + return {view: {items: items.slice(0, 20), has_more: hasMore, + ...(hasMore && nextCursor ? {next_cursor: nextCursor} : {})}, deliveries}; } function replyStatuses(root: string, row: JsonObject): JsonObject[] { const folder = join(root, "replies", requestId(row.request_id)); @@ -533,7 +555,7 @@ export async function readCollaborationInbox(params: JsonObject): Promise Date: Thu, 19 Nov 2026 01:00:28 +0800 Subject: [PATCH 3/3] fix(collaboration): require peer result readback before consumption Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/capabilities/manager_context/README.md | 22 ++++--- loopx/cli_commands/manager_inbox.py | 4 ++ loopx/collaboration_mcp.py | 20 +++---- .../control_plane/collaboration/inbox_read.ts | 36 ++++++++--- loopx/control_plane/collaboration/peers.py | 60 ++++++++++++------- tests/test_collaboration_mcp.py | 48 +++++++++++---- 6 files changed, 129 insertions(+), 61 deletions(-) diff --git a/loopx/capabilities/manager_context/README.md b/loopx/capabilities/manager_context/README.md index 59ed1ef4b6..b080e0940f 100644 --- a/loopx/capabilities/manager_context/README.md +++ b/loopx/capabilities/manager_context/README.md @@ -251,10 +251,13 @@ does not interrupt an active Turn or treat visibility as consumption. Ordinary peer results may wait for the next work Turn. Cancellation, blocking and priority-control paths keep their immediate handling. Use the invocation-bound -`read_peer_returns` tool when only the peer results need review. It records the -same `model_turn` supply fact as the full `read_context` tool. The required CLI -read and its paged recovery record transport delivery. Peer results stay -eligible for the next Turn until a bound Turn accepts or rejects them. +`read_peer_returns` tool when only the peer results need review. It binds each +result's `read_token` to the current Turn. A committed receipt can outlast a +lost response, so pass the token from the returned body when acknowledging +the result. If the read fails ambiguously, repeat the same page in the same +Turn. The required CLI read and its paged recovery record transport delivery. +Peer results stay eligible for the next Turn until a bound Turn accepts or +rejects them. Outgoing requests to an original project conversation use the same typed address reader as explicit peer returns. The agenda retains that conversation recipient @@ -913,11 +916,12 @@ Retry the same update with the same id and text. Each update has its own after verified delivery of the preceding result. Unknown delivery blocks later sends rather than allowing them to overtake it. After the bound tool supplies an update, use its acknowledgement command with the exact `--result-key` or -call `consume_peer_result` with that key. `accepted` and `rejected` consume it. +call `consume_peer_result` with that key and the result's `read_token` when +supplied. `accepted` and `rejected` consume it. `deferred` records the review but keeps it visible on the next Turn. Consuming the first result does not consume later updates. MCP callers use the corresponding `return_result(update_id=...)` and -`consume_peer_result(disposition=..., result_key=...)`; the MCP host binds the +`consume_peer_result(disposition=..., result_key=..., read_token=...)`; the MCP host binds the current Turn identity and does not expose it as a model-selected argument. Full texts stay in immutable receipts; the typed publication planner receives identities and content digests. @@ -1154,12 +1158,14 @@ The peer independently acknowledges a request and reports a conclusion through the same commands as a manager request. The original requester can inspect it under `peer_returns` in `manager-inbox read`. In a host with the invocation-bound tools configured, call `read_peer_returns` for the results alone -and `consume_peer_result` after evaluating them. A read records delivery and +and supply each result's `read_token` to `consume_peer_result` after evaluating it. +A read records delivery and leaves the results pending. Follow `next_cursor` as `cursor` in the same Turn to read later results even when earlier ones are deferred. Omit the cursor to restart the live scan and discover results added before the previous page boundary. The full `read_context` response also carries a CLI acknowledgement -command for each exact delivery: +command for each exact delivery. When the result carries a `read_token`, the +supplied command includes the corresponding `--read-token`: ```sh loopx manager-inbox acknowledge-return --goal-id allocation --agent-id builder \ diff --git a/loopx/cli_commands/manager_inbox.py b/loopx/cli_commands/manager_inbox.py index 117519a81a..88fde04b81 100644 --- a/loopx/cli_commands/manager_inbox.py +++ b/loopx/cli_commands/manager_inbox.py @@ -246,6 +246,7 @@ def register_manager_inbox(subparsers, add_format): help="For report: explicit relative file in the registered Goal workspace; bound-owner App only, at most four files.") parser.add_argument("--update-id", help="For report: stable identity for a later conclusion; retry the same id and text.") parser.add_argument("--result-key", help="For acknowledge-return: the exact peer result read; defaults to the initial conclusion.") + parser.add_argument("--read-token", help="For acknowledge-return: the read_token supplied with the peer result, if present.") parser.add_argument("--turn-instance-id", help="For acknowledge-return: identify the work Turn that already received the peer result.") parser.add_argument("--disposition", choices=("accepted", "deferred", "rejected"), help="For acknowledge-return: whether this Turn used, deferred, or rejected the peer result.") @@ -343,6 +344,8 @@ def handle_manager_inbox(args, registry_path, runtime_root): raise ValueError("--attachment-ref is only supported for report") if getattr(args, "result_key", None) is not None and args.manager_inbox_action != "acknowledge-return": raise ValueError("--result-key is only supported for acknowledge-return") + if getattr(args, "read_token", None) is not None and args.manager_inbox_action != "acknowledge-return": + raise ValueError("--read-token is only supported for acknowledge-return") if getattr(args, "turn_instance_id", None) is not None and args.manager_inbox_action not in {"read", "acknowledge-return"}: raise ValueError("--turn-instance-id is only supported for read/acknowledge-return") if getattr(args, "disposition", None) is not None and args.manager_inbox_action != "acknowledge-return": @@ -458,6 +461,7 @@ def handle_manager_inbox(args, registry_path, runtime_root): result_key=getattr(args, "result_key", None) or "conclusion", turn_instance_id=args.turn_instance_id, disposition=args.disposition, + read_token=getattr(args, "read_token", None), ) elif args.manager_inbox_action == "read": from ..control_plane.collaboration.peers import read_inbox diff --git a/loopx/collaboration_mcp.py b/loopx/collaboration_mcp.py index b43c7e90ed..2cc80304f9 100644 --- a/loopx/collaboration_mcp.py +++ b/loopx/collaboration_mcp.py @@ -288,16 +288,14 @@ def read_context(cursor: str | None = None) -> dict: if turn_instance_id is not None: @server.tool() def read_peer_returns(cursor: str | None = None) -> dict: - """Read only peer results awaiting review by this bound work Turn. - - Evaluate the returned result and use consume_peer_result to accept, - defer or reject it. Follow next_cursor in this Turn for more - results. Omit cursor to start a fresh scan. + """Read only peer results for this bound work Turn. + Follow next_cursor in this Turn, or omit it to start a fresh scan. + Repeat the same page after an ambiguous read. After evaluating the result, + pass its read_token to consume_peer_result to accept, defer or reject it. """ return {"peer_returns": read_turn_peer_returns( root, registry, goal_id, agent_id, - turn_instance_id=turn_instance_id, caller_goal_ref=caller_goal_ref, cursor=cursor, - )} + turn_instance_id=turn_instance_id, caller_goal_ref=caller_goal_ref, cursor=cursor)} @server.tool() def assess_request( @@ -451,11 +449,12 @@ def consume_peer_result( request_id: str, disposition: Literal["accepted", "deferred", "rejected"], result_key: str = "conclusion", + read_token: str | None = None, ) -> dict: """Acknowledge a peer result supplied to this exact work Turn. - - Deferred results remain visible on the next Turn. Accepted or rejected - results are consumed idempotently and never change work state. + Pass the result's read_token when supplied. Deferred + results remain visible on the next Turn. Accepted or rejected results + are consumed idempotently and never change work state. """ check_scope() if turn_instance_id is None: @@ -468,6 +467,7 @@ def consume_peer_result( result_key=result_key, turn_instance_id=turn_instance_id, disposition=disposition, + read_token=read_token, registry=registry, caller_goal_ref=caller_goal_ref, ) diff --git a/loopx/control_plane/collaboration/inbox_read.ts b/loopx/control_plane/collaboration/inbox_read.ts index 5385c9840a..22329287f0 100644 --- a/loopx/control_plane/collaboration/inbox_read.ts +++ b/loopx/control_plane/collaboration/inbox_read.ts @@ -1,6 +1,6 @@ import deliveryContract from "./return_delivery_contract.json" with {type: "json"}; /** Local Inbox read transactions; provider observations remain explicit Host IO. */ -import {createHash} from "node:crypto"; +import {createHash, randomBytes} from "node:crypto"; import {constants, closeSync, fstatSync, openSync, readSync, readdirSync, statSync} from "node:fs"; import {basename, dirname, isAbsolute, join, resolve, toNamespacedPath} from "node:path"; import {setImmediate as yieldToRuntime} from "node:timers/promises"; @@ -466,6 +466,7 @@ async function recordReads(source: InboxSource, params: JsonObject): Promise = {}; for (const raw of params.deliveries) { const delivered = requireJsonObject(raw, "supplied peer result"), key = requireNonEmptyString(delivered.key, "result key"); if (!RESULT_KEY.test(key)) fail("invalid peer result key"); @@ -474,9 +475,10 @@ async function recordReads(source: InboxSource, params: JsonObject): Promise { + const id = requestId(row.request_id); + const path = join(source.root, "replies", id, key + ".delivery.json"); + const lock = source.exact ? join(source.root, "request-locks", id) : join(dirname(path), key + ".lock"); + const readToken = await withFileMutationLock(lock, async () => { const stored = conversation ? entry({...source, recipient: normalizeOriginalConversationRecipient(row.recipient)}, String(row.request_id)) : entry(source, String(row.request_id), requireNonEmptyString(row.agent_id, "peer Agent")); if (stored.source_agent_id !== source.agent) fail("peer return scope mismatch"); @@ -490,13 +492,24 @@ async function recordReads(source: InboxSource, params: JsonObject): Promise"] if peer_result.get("result_key"): command.extend(["--result-key", peer_result["result_key"]]) + read_token = read_tokens.get(f"{peer_result['request_id']}:{peer_result.get('result_key', 'conclusion')}") + if read_token is not None: + peer_result["read_token"] = read_token + command.extend(["--read-token", read_token]) peer_result["acknowledge_command"] = render_host_cli_command(command) if request_id is None and not native_continuation: result["unfinished_delegations"] = final["context"]["unfinished_delegations"] @@ -789,7 +803,7 @@ def read_inbox( else: result["followthrough"] += ( " Peer conclusions stay pending after this read. In a bound work Turn, use " - "read_peer_returns and then consume_peer_result after evaluating each result." + "read_peer_returns and then consume_peer_result with each evaluated result's read_token." ) if result.get("native_child_results", {}).get("items"): result["followthrough"] += ( diff --git a/tests/test_collaboration_mcp.py b/tests/test_collaboration_mcp.py index 09956297b9..2fc54fdf3e 100644 --- a/tests/test_collaboration_mcp.py +++ b/tests/test_collaboration_mcp.py @@ -121,25 +121,40 @@ async def exercise(): delivery = _root(tmp_path) / "replies" / rid / "conclusion.delivery.json" receipt = delivery.read_bytes() assert json.loads(receipt)["model_turn"]["turn_instance_id"] == turn_key + refused = await session.call_tool("consume_peer_result", disposition) + assert refused.isError and "read_token" in refused.content[0].text + cli_acknowledge = [sys.executable, "-m", "loopx.entrypoint", "--format", "json", + "--registry", str(registry), "--runtime-root", str(tmp_path), "manager-inbox", + "acknowledge-return", "--goal-id", "delivery", "--agent-id", "worker", + "--request-id", rid, "--turn-instance-id", turn_key, "--disposition", "accepted"] + refused_cli = subprocess.run(cli_acknowledge, capture_output=True, timeout=15) + assert refused_cli.returncode == 1 and "read_token" in json.loads(refused_cli.stdout)["error"] + assert not list((_root(tmp_path) / "replies").rglob("*.consumed.json")) recovered_peer = await session.call_tool("read_peer_returns", {}) assert not recovered_peer.isError result, = json.loads(recovered_peer.content[0].text)["peer_returns"]["items"] assert result["request_id"] == rid and result["text"] == "Private peer conclusion" + read_token = result["read_token"] + assert read_token not in failed_peer_read.content[0].text assert delivery.read_bytes() == receipt assert [_receipt(tmp_path, "reads", row)[0] for row in tail] == receipts recovered = await session.call_tool("read_context", {"cursor": cursor}) assert not recovered.isError - assert {row["request_id"] for row in json.loads(recovered.content[0].text)["items"]} == {row["request_id"] for row in tail} + recovered_page = json.loads(recovered.content[0].text) + assert {row["request_id"] for row in recovered_page["items"]} == {row["request_id"] for row in tail} + full_result, = recovered_page["peer_returns"]["items"] + assert full_result["read_token"] == read_token + assert read_token in full_result["acknowledge_command"] assert all(path.read_bytes() == data for path, data in before.items()) delivery = _root(tmp_path) / "replies" / rid / "conclusion.delivery.json" assert json.loads(delivery.read_text())["model_turn"]["turn_instance_id"] == turn_key assert not list((_root(tmp_path) / "replies").rglob("*.consumed.json")) - for replay in (False, True): - result = await session.call_tool("consume_peer_result", disposition) - assert not result.isError - acknowledgement = json.loads(result.content[0].text) - assert acknowledgement["status"] == "consumed" - assert acknowledgement.get("replay", False) is replay + consumed = await session.call_tool("consume_peer_result", {**disposition, "read_token": read_token}) + assert not consumed.isError + assert json.loads(consumed.content[0].text)["status"] == "consumed" + replay = subprocess.run([*cli_acknowledge, "--read-token", read_token], capture_output=True, + timeout=15, check=True) + assert json.loads(replay.stdout)["replay"] is True with source_session_registry_transaction(registry, operation="revoke_fixture_agent") as transaction: changed = transaction.payload_copy() changed["goals"][0]["coordination"]["registered_agents"] = ["source"] @@ -234,7 +249,7 @@ async def exercise(): read_tool = next(tool for tool in tools.tools if tool.name == "read_context") consume_tool = next(tool for tool in tools.tools if tool.name == "consume_peer_result") assert set(read_tool.inputSchema["properties"]) == {"cursor"} - assert set(consume_tool.inputSchema["properties"]) == {"request_id", "disposition", "result_key"} + assert set(consume_tool.inputSchema["properties"]) == {"request_id", "disposition", "result_key", "read_token"} assert set(consume_tool.inputSchema["required"]) == {"request_id", "disposition"} for tool in tools.tools: assert not { @@ -363,7 +378,7 @@ async def exercise(): narrow = json.loads(result.content[0].text) assert set(narrow) == {"peer_returns"} peer, = narrow["peer_returns"]["items"] - assert peer == opening_view["peer_returns"]["items"][0] + assert {key: value for key, value in peer.items() if key != "read_token"} == opening_view["peer_returns"]["items"][0] assert peer["request_id"] == rid and peer["text"] == "One finding needs a follow-up." assert json.loads(delivery.read_text())["model_turn"]["turn_instance_id"] == turn assert not list((_root(root) / "replies" / rid).glob("*.consumed.json")) @@ -375,7 +390,7 @@ async def exercise(): previous_peer, = full_view["peer_returns"]["items"] assert {key: value for key, value in previous_peer.items() if key != "acknowledge_command"} == peer - consumed = await session.call_tool("consume_peer_result", args) + consumed = await session.call_tool("consume_peer_result", {**args, "read_token": peer["read_token"]}) assert not consumed.isError and json.loads(consumed.content[0].text)["status"] == "consumed" empty = await session.call_tool("read_peer_returns", {}) assert not empty.isError @@ -441,7 +456,8 @@ async def exercise(): for row in first["items"]: request_id, key = result_id(row) - disposition = {"request_id": request_id, "result_key": key, "disposition": "deferred"} + disposition = {"request_id": request_id, "result_key": key, "disposition": "deferred", + "read_token": row["read_token"]} reply = await session.call_tool("consume_peer_result", disposition) assert not reply.isError and json.loads(reply.content[0].text)["status"] == "deferred" assert await page(session) == first @@ -457,7 +473,10 @@ async def exercise(): assert {result_id(row) for row in tail["items"]} == results.keys() - first_ids assert {result_id(row): row["text"] for row in first["items"] + tail["items"]} == results assert json.loads(delivery.read_text())["model_turn"]["turn_instance_id"] == first_turn - accepted = await session.call_tool("consume_peer_result", disposition) + foreign = await session.call_tool("consume_peer_result", {**disposition, "read_token": first["items"][0]["read_token"]}) + assert foreign.isError and "read_token" in foreign.content[0].text + read_token = next(row["read_token"] for row in tail["items"] if result_id(row) == (later_id, later_key)) + accepted = await session.call_tool("consume_peer_result", {**disposition, "read_token": read_token}) assert not accepted.isError and json.loads(accepted.content[0].text)["status"] == "consumed" async with stdio_client(launch(later_turn)) as (read, write), ClientSession(read, write) as session: @@ -466,6 +485,11 @@ async def exercise(): assert rejected.isError and "cursor scope mismatch" in rejected.content[0].text reopened = await page(session) assert {result_id(row) for row in reopened["items"]} == first_ids + prior = first["items"][0] + stale = await session.call_tool("consume_peer_result", {"request_id": prior["request_id"], + "result_key": prior.get("result_key", "conclusion"), "disposition": "accepted", + "read_token": prior["read_token"]}) + assert stale.isError and "read_token" in stale.content[0].text remaining = await page(session, cursor=reopened["next_cursor"]) assert {result_id(row) for row in remaining["items"]} == results.keys() - first_ids - {(later_id, later_key)}