diff --git a/loopx/capabilities/manager_context/README.md b/loopx/capabilities/manager_context/README.md index ac38d7bf00..b080e0940f 100644 --- a/loopx/capabilities/manager_context/README.md +++ b/loopx/capabilities/manager_context/README.md @@ -250,9 +250,12 @@ 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. +and priority-control paths keep their immediate handling. Use the invocation-bound +`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. @@ -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. @@ -1153,9 +1157,15 @@ 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 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. 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 \ @@ -1171,8 +1181,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 @@ -1224,9 +1234,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/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 75ad729df6..2cc80304f9 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,18 @@ 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(cursor: str | None = None) -> dict: + """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)} + @server.tool() def assess_request( request_id: str, @@ -436,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: @@ -453,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 df8a4db1a3..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"; @@ -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)); @@ -444,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"); @@ -452,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"); @@ -468,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"] @@ -764,8 +802,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 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 e84c39b779..2fc54fdf3e 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,19 +114,47 @@ 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 + 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"] @@ -129,6 +162,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()) @@ -214,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 { @@ -286,6 +321,181 @@ 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 {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")) + + 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, "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 + assert json.loads(empty.content[0].text) == {"peer_returns": {"items": [], "has_more": False}} + + asyncio.run(exercise()) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_bound_peer_return_pages_keep_deferred_results_for_the_next_turn(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"} + results = {} + for index, count in enumerate((21, 2)): + rid = request(root, registry, "goal-a", "agent-a", "agent-b", f"review-{index}", brief)["request_id"] + acknowledge(root, "goal-a", "agent-b", rid, "adopt", "Review the artifact", registry=registry) + for number in range(count): + reply = f"Finding {index}-{number} needs independent validation." + result = return_result(root, "goal-a", "agent-b", rid, reply, registry=registry, + update_id=f"finding-{number}" if number else None) + results[rid, result.get("result_key", "conclusion")] = reply + + def launch(turn): + env = 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, + ) + return 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, **env}) + + def result_id(row): + return row["request_id"], row.get("result_key", "conclusion") + + async def page(session, **args): + response = await session.call_tool("read_peer_returns", args) + assert not response.isError, response + return json.loads(response.content[0].text)["peer_returns"] + + async def exercise(): + first_turn, later_turn = "sha256:" + "a" * 64, "sha256:" + "b" * 64 + async with stdio_client(launch(first_turn)) as (read, write), ClientSession(read, write) as session: + await session.initialize() + first = await page(session) + assert first["has_more"] and len(first["items"]) == 20 + first_ids = {result_id(row) for row in first["items"]} + cursor = first.get("next_cursor") + assert cursor, "the pending tail has no continuation" + + for row in first["items"]: + request_id, key = result_id(row) + 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 + + later_id, later_key = min(results.keys() - first_ids) + disposition = {"request_id": later_id, "result_key": later_key, "disposition": "accepted"} + assert (await session.call_tool("consume_peer_result", disposition)).isError + delivery = _root(root) / "replies" / later_id / (later_key + ".delivery.json") + assert not delivery.exists() + tail = await page(session, cursor=cursor) + assert await page(session, cursor=cursor) == tail + assert not tail["has_more"] + 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 + 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: + await session.initialize() + rejected = await session.call_tool("read_peer_returns", {"cursor": cursor}) + 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)} + + 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