From 0c2fb28ccfc0ff6b3dc80d8cda89b1024fbeee6a Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:50:16 +0800 Subject: [PATCH 1/3] fix(collaboration): verify terminal return receipt identity Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../collaboration/conversation_inventory.py | 7 +-- .../control_plane/collaboration/inbox_read.ts | 29 ++++++--- .../collaboration/result_publication.ts | 6 ++ .../collaboration/return_delivery.ts | 17 +++--- .../test_chat_request_inventory.py | 61 +++++++++++++++++++ .../inbox_read_transaction.test.ts | 10 ++- 6 files changed, 106 insertions(+), 24 deletions(-) diff --git a/loopx/control_plane/collaboration/conversation_inventory.py b/loopx/control_plane/collaboration/conversation_inventory.py index ba8131877a..e60032468e 100644 --- a/loopx/control_plane/collaboration/conversation_inventory.py +++ b/loopx/control_plane/collaboration/conversation_inventory.py @@ -12,7 +12,7 @@ from ..content_digest import BARE_SHA256_PATTERN from .goal_instance_scope import collaboration_goal_scope, inspect_original_request_batch -from .inbox import _entry, _now, _read, _receipt, _request_lock, _root, read_inbox_transaction, reply_status +from .inbox import _entry, _now, _read, _receipt, _request_lock, _root, read_inbox_transaction from .links import read_linked_work from .source_chat_observation import is_source_chat_host, original_delivery_facts, original_turn_reader from .source_grant_observation import source_context_target_authority @@ -58,7 +58,7 @@ def _read_receipt_batch(root, rows): return [] try: observed = read_inbox_transaction(root, {"operation": "receipt_states", "rows": rows, "include_agenda": True}) - states = list(zip(observed["items"], observed["agenda_items"], strict=True)) + states = list(zip(observed["items"], observed["agenda_items"], observed["return_items"], strict=True)) if len(states) != len(rows): raise ValueError("Inbox receipt count does not match requests") return states @@ -217,11 +217,10 @@ def read_conversation_requests(root, registry, store, session, *, goal_ids, core failed += 1 continue try: - state, agenda = observed + state, agenda, replies = observed controlled = state.get("readback") read, read_error = _receipt(root, "reads", row) decision, decision_error = _receipt(root, "decisions", row) - replies = reply_status(root, row) work_reads.append((row, source_session_id, source_turn, state, agenda, controlled, read, read_error, decision, decision_error, replies)) except (OSError, ValueError, KeyError, TypeError): diff --git a/loopx/control_plane/collaboration/inbox_read.ts b/loopx/control_plane/collaboration/inbox_read.ts index 22329287f0..bbb4d9ba33 100644 --- a/loopx/control_plane/collaboration/inbox_read.ts +++ b/loopx/control_plane/collaboration/inbox_read.ts @@ -13,7 +13,7 @@ import {jsonObject, requireJsonObject, requireNonEmptyString, requireStringLiter import {decideCollaborationLifecycle} from "./goal_instance_lifecycle.ts"; import {inspectCollaborationInboxReceipts, projectReceiverFollowthrough} from "./inbox_receipts.ts"; import {recordControlledRequestRead} from "./request_control.ts"; -import {planCollaborationResult} from "./result_publication.ts"; +import {planCollaborationResult, returnMessageId} from "./result_publication.ts"; import {CONVERSATION_ENTRY_SCHEMA, normalizeOriginalConversationRecipient, verifyOriginalConversationReturnRoute} from "./semantic_request.ts"; import {projectDelegationTurnContext, projectDelegationTurnItem, projectDelegationTurnItems} from "./turn_context.ts"; import {isNativeChildResultCursor, nativeChildResultInbox} from "../capabilities/native_child_result_inbox.ts"; @@ -362,14 +362,19 @@ function replyStatuses(root: string, row: JsonObject): JsonObject[] { || error !== null && (typeof error !== "string" || !DELIVERY_ERRORS.has(error))) { status = "explicit_unverified"; error = "delivery_state_unreadable"; } + if (status === "delivered" && phase === "conclusion" && row.source_kind !== "peer" + && state.message_id !== returnMessageId(requestId(row.request_id), key)) { + return {...identity, status: "explicit_unverified", created_at: reply.created_at ?? null, + delivered_at: null, error: "manager_return_payload_conflict"}; + } return {...identity, status, created_at: reply.created_at ?? null, delivered_at: typeof state.delivered_at === "string" && [...state.delivered_at].length <= 80 ? state.delivered_at : null, error, ...(state.verification === "reconciled_after_restart" ? {verification: state.verification} : {})}; }); } -function agendaResults(root: string, row: JsonObject): JsonObject[] { +function agendaResults(root: string, row: JsonObject, returns = replyStatuses(root, row)): JsonObject[] { const folder = join(root, "replies", requestId(row.request_id)); - const statuses = new Map(replyStatuses(root, row).map(status => [status.result_key ?? status.phase, status.status])); + const statuses = new Map(returns.map(status => [status.result_key ?? status.phase, status.status])); const replies = resultKeys(folder).map(key => ({key, reply: readRecord(join(folder, key + ".json"))})); // Reuse immutable request-local observations; each result still goes through // the publication validator and its current delivery/consumption readback. @@ -545,15 +550,23 @@ export async function readCollaborationInbox(params: JsonObject): Promise requireJsonObject(row, "inbox request")); const items = rows.map(row => receiptState(root, row)); if (params.include_agenda !== true) return {items}; - return {items, agenda_items: rows.map((request, index) => { + const returnItems: JsonObject[][] = []; + const agendaItems = rows.map((request, index) => { const links = linksReceipt(root, request); - let results: JsonObject[] = [], unavailable = links.unavailable; - try { results = agendaResults(root, request); } - catch (error) { if (!recordFailure(error)) throw error; unavailable = true; } + let returns: JsonObject[] = [], results: JsonObject[] = [], unavailable = links.unavailable; + try { + returns = replyStatuses(root, request); + results = agendaResults(root, request, returns); + } catch (error) { + if (!recordFailure(error)) throw error; + unavailable = true; + } + returnItems.push(returns); return projectDelegationTurnItem({direction: "outgoing", request: {...request, purpose: jsonObject(request.brief)?.purpose ?? ""}, receipt: items[index], todo_ids: links.value.todo_ids ?? [], evidence_unavailable: unavailable, results}); - })}; + }); + return {items, agenda_items: agendaItems, return_items: returnItems}; } const scope = requireJsonObject(params.scope, "Goal scope"); const conversation = scope.profile_id === "original_conversation_v0"; diff --git a/loopx/control_plane/collaboration/result_publication.ts b/loopx/control_plane/collaboration/result_publication.ts index 5625b5d344..b15e062cab 100644 --- a/loopx/control_plane/collaboration/result_publication.ts +++ b/loopx/control_plane/collaboration/result_publication.ts @@ -17,6 +17,12 @@ function decisionKey(revision: number): string { } const UPDATE_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,119}$/; +export function returnMessageId(requestId: string, resultKey: string): string { + // Retain Python json.dumps' spaces in the existing ASCII-only message identity. + const identity = JSON.stringify([requestId, resultKey]).replace(",", ", "); + return "handoff." + createHash("sha256").update(identity).digest("hex"); +} + /** Receiver-authored scope on an immutable result, not a completion verdict or scheduler. */ export function resultRemainingWork(value: unknown): JsonObject | null { if (value === undefined || value === null) return null; diff --git a/loopx/control_plane/collaboration/return_delivery.ts b/loopx/control_plane/collaboration/return_delivery.ts index 26abd9a4d7..498e359445 100644 --- a/loopx/control_plane/collaboration/return_delivery.ts +++ b/loopx/control_plane/collaboration/return_delivery.ts @@ -16,7 +16,7 @@ import { atomicWriteJson, withFileMutationLock } from "../effect_runtime_io.ts"; import { parseTodoTimestampMicros } from "../runtime_timestamp.ts"; import { decideCollaborationLifecycle } from "./goal_instance_lifecycle.ts"; import { resolveConversationScope } from "./conversation_scope.ts"; -import { planCollaborationResult, collaborationResultDeliveryReady, collaborationResultText, usesReaderReturnFormat } from "./result_publication.ts"; +import { planCollaborationResult, collaborationResultDeliveryReady, collaborationResultText, returnMessageId, usesReaderReturnFormat } from "./result_publication.ts"; export const MANAGER_RETURN_DELIVERY_ATTEMPT_SCHEMA = "manager_return_delivery_attempt_v0"; @@ -470,22 +470,18 @@ async function prepareReturn(command: ReturnCommand, state: JsonObject): Promise const text = usesReaderReturnFormat(reply) ? `${body}\n\n${provenance}` : `${provenance}\n\n${body}`; return returnResponse({ action: privateConversation ? "private" : verify ? "verify" : "send", - text, message_id: returnMessageId(command), attempt: verify ? savedAttempt(state.attempt) : null, attachments: reply.attachments ?? [], + text, message_id: returnMessageId(String(command.request.request_id), command.key), + attempt: verify ? savedAttempt(state.attempt) : null, attachments: reply.attachments ?? [], revision: deliveryRevision(state), token: (state.admission as JsonObject | undefined)?.token ?? null }); } -function returnMessageId(command: ReturnCommand): string { - // Retain Python json.dumps' spaces in the existing ASCII-only message identity. - const identity = JSON.stringify([command.request.request_id, command.key]).replace(",", ", "); - return "handoff." + createHash("sha256").update(identity).digest("hex"); -} - function deliveryOutcome(command: ReturnCommand, state: JsonObject): JsonObject { const outcome = requireJsonObject(command.request.outcome, "return provider outcome"); requireStringLiteral(outcome.kind, ["private", "sent", "conflict", "verify_unavailable", "locator_unavailable", "verified", "error", "verification_error", "sender_unavailable"], "return outcome kind"); if (outcome.kind === "private" || outcome.kind === "sent" && outcome.reply_verified === true) { - return { status: "delivered", delivered_at: command.now, message_id: returnMessageId(command), + return { status: "delivered", delivered_at: command.now, + message_id: returnMessageId(String(command.request.request_id), command.key), ...(outcome.kind === "sent" ? { provider_receipt: outcome.idempotency_key, reply_verified: true } : {}) }; } if (outcome.kind === "conflict") return { status: "explicit_unverified", error: "manager_return_payload_conflict" }; @@ -502,7 +498,8 @@ function deliveryOutcome(command: ReturnCommand, state: JsonObject): JsonObject status: command.exact ? "retry_pending" : "verification_required" }; } return checked.status === "delivered" - ? { status: "delivered", delivered_at: command.now, message_id: returnMessageId(command), + ? { status: "delivered", delivered_at: command.now, + message_id: returnMessageId(String(command.request.request_id), command.key), provider_receipt: normalizeManagerReturnDeliveryAttempt(state.attempt).provider_receipt, reply_verified: true, verification: checked.verification } : checked.status === "explicit_unverified" ? { status: checked.status, error: checked.error } diff --git a/tests/control_plane/test_chat_request_inventory.py b/tests/control_plane/test_chat_request_inventory.py index 64dab2df6f..9b4722bd26 100644 --- a/tests/control_plane/test_chat_request_inventory.py +++ b/tests/control_plane/test_chat_request_inventory.py @@ -228,6 +228,67 @@ def test_read_and_adoption_still_owe_conclusion_and_queued_return_stays_visible( assert historical["rows"][0]["request_id"] == rid and not historical["rows"][0]["unfinished"] + +def test_terminal_return_with_wrong_message_stays_unfinished_on_both_surfaces(api, capsys): + import json + + from loopx.cli import main + + _, _, route = _source(api) + _, fixture, server = api + request_id = route["request_id"] + root = _root(fixture["runtime"]) + session_id = route["session_id"] + acknowledge(fixture["runtime"], route["goal_id"], route["agent_id"], request_id, + "adopt", "Check the requested artifact", registry=fixture["registry"], caller_goal_ref=fixture["ref"]) + report(fixture["runtime"], route["goal_id"], route["agent_id"], request_id, + "conclusion", "The requested artifact passed.", registry=fixture["registry"], caller_goal_ref=fixture["ref"]) + drain(fixture["runtime"], fixture["registry"], server.chat_store, + lambda *_: pytest.fail("a local return must not use an external sender")) + + def cli_agenda(): + capsys.readouterr() + code = main(["--registry", str(fixture["registry"]), "--runtime-root", str(fixture["runtime"]), + "--format", "json", "manager-inbox", "read", "--goal-id", route["goal_id"], + "--agent-id", route["agent_id"]]) + assert code == 0 + return json.loads(capsys.readouterr().out)["unfinished_delegations"]["items"] + + receipt = root / "replies" / request_id / "conclusion.delivery.json" + original = receipt.read_bytes() + confirmed = _inventory(api, session_id, view="history")[1] + assert confirmed["pending_count"] == 0 and confirmed["rows"][0]["returns"][0]["status"] == "delivered" + assert cli_agenda() == [] + + message_id = json.loads(original)["message_id"] + messages = server.chat_store.messages(session_id) + assert next(row for row in messages if row["message_id"] == message_id)["turn_id"] == route["turn_id"] + turn, _ = server.chat_store.create_turn(session_id, client_turn_id="other-return", + message="Another original conversation Turn", origin="web") + unrelated = server.chat_store.append_message(session_id, role="assistant", text="Another result", + turn_id=turn["turn_id"], origin="manager_followup") + assert unrelated["message_id"] != message_id + for corrupted in ({"message_id": unrelated["message_id"]}, {}): + incorrect = {key: value for key, value in json.loads(original).items() if key != "message_id"} + receipt.write_text(json.dumps({**incorrect, **corrupted})) + unchanged = receipt.read_bytes() + http, pending = _inventory(api, session_id) + assert http == 200 and pending["pending_count"] == 1 + row, = pending["rows"] + assert row["request_id"] == request_id + assert row["returns"][0]["status"] == "explicit_unverified" + assert row["returns"][0]["error"] == "manager_return_payload_conflict" + agenda, = cli_agenda() + assert agenda["request_id"] == request_id and agenda["step"] == "await_return_delivery" + assert agenda["returns"][0]["status"] == "explicit_unverified" + assert receipt.read_bytes() == unchanged + receipt.write_bytes(original) + assert cli_agenda() == [] + restored = _inventory(api, session_id, view="history")[1] + assert restored["snapshot_digest"] == confirmed["snapshot_digest"] + assert restored["rows"] == confirmed["rows"] + + def test_revision_and_cancellation_reuse_current_control_and_preserve_history(api): control, _, route = _source(api) current = control()[1]["view"] diff --git a/tests/control_plane_ts/inbox_read_transaction.test.ts b/tests/control_plane_ts/inbox_read_transaction.test.ts index 254c42644a..51538ec925 100644 --- a/tests/control_plane_ts/inbox_read_transaction.test.ts +++ b/tests/control_plane_ts/inbox_read_transaction.test.ts @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; +import {createHash} from "node:crypto"; import {mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync} from "node:fs"; import {join} from "node:path"; import {tmpdir} from "node:os"; @@ -278,11 +279,16 @@ for (const profile of ["legacy", "exact"] as const) { writeFileSync(join(f.base, "roundtrips", row.request_id + ".json"), JSON.stringify(identity)); const remaining_work = {summary: "Validate the packaged repair", resume_when: "The isolated package is available"}; const key = (n: number) => n ? "conclusion-" + String(n).padStart(8, "0") : "conclusion"; + function confirmDelivery(n: number) { + const hash = createHash("sha256").update(`["${row.request_id}", "${key(n)}"]`).digest("hex"); + writeFileSync(join(replies, key(n) + ".delivery.json"), + JSON.stringify({status: "delivered", message_id: "handoff." + hash})); + } for (let n = 0; n < 4; n++) { writeFileSync(join(replies, key(n) + ".json"), JSON.stringify({...identity, phase: "conclusion", decision: "adopt", text: "Recorded evidence " + n + "😀".repeat(2000), remaining_work, ...(n ? {result_key: key(n), previous_result_key: key(n - 1), update_id: "evidence-" + n} : {})})); - writeFileSync(join(replies, key(n) + ".delivery.json"), JSON.stringify({status: "delivered"})); + confirmDelivery(n); } const original = sourceBytes(replies); const pending = (await f.call("pending")).result as JsonObject; @@ -307,7 +313,7 @@ for (const profile of ["legacy", "exact"] as const) { text: "The requested package passed validation.", result_key: key(4), previous_result_key: key(3), update_id: "validated"})); const queued = (await f.call("turn_context")).unfinished_delegations as JsonObject; assert.equal((queued.items as JsonObject[])[0].step, "await_return_delivery"); - writeFileSync(join(replies, key(4) + ".delivery.json"), JSON.stringify({status: "delivered"})); + confirmDelivery(4); assert.deepEqual(((await f.call("turn_context")).unfinished_delegations as JsonObject).items, []); }); } From 550dcad7da45fa0320b4a0d462fc2064fef95404 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:33:56 +0800 Subject: [PATCH 2/3] fix(collaboration): reconcile private terminal returns from saved messages Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../src/data/conversation-requests.ts | 3 +- .../conversation-requests.tsx | 13 ++- .../capabilities/manager_context/roundtrip.py | 12 ++- .../control_plane/collaboration/inbox_read.ts | 26 ++++-- .../collaboration/result_publication.ts | 9 ++ .../collaboration/return_delivery.ts | 82 ++++++++++++++++--- .../collaboration/terminal_return_readback.ts | 37 +++++++++ .../collaboration/turn_context.ts | 9 +- .../test_chat_request_inventory.py | 53 ++++++++++-- .../manager_return_transaction.test.ts | 21 ++++- 10 files changed, 231 insertions(+), 34 deletions(-) create mode 100644 loopx/control_plane/collaboration/terminal_return_readback.ts diff --git a/apps/presentation/dashboard/src/data/conversation-requests.ts b/apps/presentation/dashboard/src/data/conversation-requests.ts index 20238d59ee..c674dfecfe 100644 --- a/apps/presentation/dashboard/src/data/conversation-requests.ts +++ b/apps/presentation/dashboard/src/data/conversation-requests.ts @@ -9,7 +9,8 @@ const rowSchema = z.object({request_id: z.string(), goal_id: z.string(), agent_i control_state: z.string().nullable(), brief: requestBriefSchema.nullable().optional(), source_question: z.string(), request_revision: z.number().int().positive().nullable(), read_status: z.string(), decision: z.string(), decision_reason: z.string().nullable().optional(), - returns: z.array(z.object({phase: z.string(), status: z.string(), request_revision: z.number().nullable().optional()})), + returns: z.array(z.object({phase: z.string(), status: z.string(), request_revision: z.number().nullable().optional(), + error: z.string().nullable().optional()})), linked_todos: z.array(z.object({todo_id: z.string(), title: z.string().nullable().optional(), status: z.string().optional()})), evidence_refs: z.array(z.string()), warnings: z.array(z.string()), source_session_id: z.string(), source_turn_id: z.string(), last_event_at: z.string().nullable()}); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/conversation-requests.tsx b/apps/presentation/dashboard/src/features/personal-workspace/conversation-requests.tsx index 611ccdaffb..65fe4750b8 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/conversation-requests.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/conversation-requests.tsx @@ -117,11 +117,18 @@ export function OriginalProjectRequests({sessionId, refreshKey}: {sessionId: str ; } +function returnNeedsVerification(row: ConversationRequest) { + return row.agenda?.step === "recover_evidence" + && row.returns.some(delivery => delivery.phase === "conclusion" && delivery.error === "manager_return_payload_conflict"); +} + function requestStage(row: ConversationRequest, zh: boolean) { if (!row.unfinished) return row.control_state === "cancelled" ? (zh ? "已取消" : "Cancelled") : (zh ? "已回传" : "Returned"); switch (row.agenda?.step) { - case "recover_evidence": return zh ? "待恢复" : "Readback unavailable"; + case "recover_evidence": return returnNeedsVerification(row) + ? (zh ? "回传待核对" : "Return needs verification") + : (zh ? "待恢复" : "Readback unavailable"); case "reconcile_reservation": return zh ? "取消待收尾" : "Cancellation settling"; case "await_return_delivery": return zh ? "待送达" : "Awaiting delivery"; case "consume_peer_result": case "await_peer_consumption": return zh ? "结果待核对" : "Result awaiting readback"; @@ -182,7 +189,9 @@ function OriginalRequest({row, zh, revision, active}: {row: ConversationRequest; }).catch(() => {if (!abort.signal.aborted) {setMessages(null); setError(true);}}); return () => abort.abort(); }, [open, active, row.source_session_id, row.source_turn_id, revision]); - return
{focusOnRead.current = event.currentTarget.open; setOpen(event.currentTarget.open);}}>{zh ? "原对话" : "Original conversation"} + return
{focusOnRead.current = event.currentTarget.open; setOpen(event.currentTarget.open);}}>{returnNeedsVerification(row) + ? (zh ? "核对原对话" : "Check original conversation") + : (zh ? "原对话" : "Original conversation")}
{error ?

{zh ? "原对话暂时无法读取,请重新打开重试。" : "Original conversation unavailable. Reopen to retry."}

: messages ? messages.map(message =>
{message.role === "user" ? (zh ? "你" : "You") : "LoopX"} diff --git a/loopx/capabilities/manager_context/roundtrip.py b/loopx/capabilities/manager_context/roundtrip.py index 48947565f4..b6fc977f99 100644 --- a/loopx/capabilities/manager_context/roundtrip.py +++ b/loopx/capabilities/manager_context/roundtrip.py @@ -692,7 +692,7 @@ def _return_transaction(host, path, phase, request): "exact": exact, "facts": observed, **payload, }, retry_safe=False) if (not isinstance(result, dict) or result.get("schema_version") != RETURN_DELIVERY_TRANSACTION - or result.get("action") not in {"skip", "private", "verify", "send"} + or result.get("action") not in {"skip", "private", "verify", "send", "reconcile_private"} or type(result.get("processed")) is not int or result["processed"] not in {0, 1}): raise RuntimeError("return delivery transaction result shape mismatch") return result @@ -753,6 +753,16 @@ def transact(phase, **payload): return _return_transaction(host, path, phase, {"facts": current, **checkpoint, **payload}) + if plan["action"] == "reconcile_private": + try: + original = store.read_history_message(source["route"]["session_id"], plan["message_id"]) + except (OSError, ValueError, KeyError): + return 0 + if cancelled(): + return 0 + recovered = transact("settle", private_readback=original) + return recovered["processed"] + def record_attempt(attempt): saved = transact("attempt", attempt=dict(attempt)) checkpoint.update({key: saved[key] for key in ("revision", "token")}) diff --git a/loopx/control_plane/collaboration/inbox_read.ts b/loopx/control_plane/collaboration/inbox_read.ts index bbb4d9ba33..669f74f40f 100644 --- a/loopx/control_plane/collaboration/inbox_read.ts +++ b/loopx/control_plane/collaboration/inbox_read.ts @@ -13,7 +13,8 @@ import {jsonObject, requireJsonObject, requireNonEmptyString, requireStringLiter import {decideCollaborationLifecycle} from "./goal_instance_lifecycle.ts"; import {inspectCollaborationInboxReceipts, projectReceiverFollowthrough} from "./inbox_receipts.ts"; import {recordControlledRequestRead} from "./request_control.ts"; -import {planCollaborationResult, returnMessageId} from "./result_publication.ts"; +import {planCollaborationResult} from "./result_publication.ts"; +import {confirmedTerminalReturn, terminalReturnIdentityConflict, TERMINAL_RETURN_READBACK_SUFFIX} from "./terminal_return_readback.ts"; import {CONVERSATION_ENTRY_SCHEMA, normalizeOriginalConversationRecipient, verifyOriginalConversationReturnRoute} from "./semantic_request.ts"; import {projectDelegationTurnContext, projectDelegationTurnItem, projectDelegationTurnItems} from "./turn_context.ts"; import {isNativeChildResultCursor, nativeChildResultInbox} from "../capabilities/native_child_result_inbox.ts"; @@ -362,10 +363,19 @@ function replyStatuses(root: string, row: JsonObject): JsonObject[] { || error !== null && (typeof error !== "string" || !DELIVERY_ERRORS.has(error))) { status = "explicit_unverified"; error = "delivery_state_unreadable"; } - if (status === "delivered" && phase === "conclusion" && row.source_kind !== "peer" - && state.message_id !== returnMessageId(requestId(row.request_id), key)) { - return {...identity, status: "explicit_unverified", created_at: reply.created_at ?? null, - delivered_at: null, error: "manager_return_payload_conflict"}; + if (status === "delivered" && row.source_kind !== "peer" + && terminalReturnIdentityConflict(state, requestId(row.request_id), key)) { + let deliveredAt: string | null = null; + try { + const readback = observe(join(folder, key + TERMINAL_RETURN_READBACK_SUFFIX)); + if (readback.state === "read") { + const route = readRecord(join(root, "roundtrips", requestId(row.request_id) + ".json")); + deliveredAt = confirmedTerminalReturn(readback.value as JsonObject, state, reply, route); + } + } catch (failure) { if (!recordFailure(failure)) throw failure; } + return {...identity, status: deliveredAt === null ? "explicit_unverified" : "delivered", + created_at: reply.created_at ?? null, delivered_at: deliveredAt, + error: deliveredAt === null ? "manager_return_payload_conflict" : null}; } return {...identity, status, created_at: reply.created_at ?? null, delivered_at: typeof state.delivered_at === "string" && [...state.delivered_at].length <= 80 ? state.delivered_at : null, @@ -374,7 +384,7 @@ function replyStatuses(root: string, row: JsonObject): JsonObject[] { } function agendaResults(root: string, row: JsonObject, returns = replyStatuses(root, row)): JsonObject[] { const folder = join(root, "replies", requestId(row.request_id)); - const statuses = new Map(returns.map(status => [status.result_key ?? status.phase, status.status])); + const statuses = new Map(returns.map(status => [status.result_key ?? status.phase, status])); const replies = resultKeys(folder).map(key => ({key, reply: readRecord(join(folder, key + ".json"))})); // Reuse immutable request-local observations; each result still goes through // the publication validator and its current delivery/consumption readback. @@ -382,7 +392,9 @@ function agendaResults(root: string, row: JsonObject, returns = replyStatuses(ro return replies.flatMap(({key, reply}) => { if (reply.phase !== "conclusion") return []; if (!inspectResult(root, row, key, reply, observations)) fail("delegation result identity unavailable"); - return [{result_key: key, request_revision: reply.request_revision ?? 1, status: statuses.get(key), + const delivery = statuses.get(key); + return [{result_key: key, request_revision: reply.request_revision ?? 1, status: delivery?.status, + ...(delivery?.error === "manager_return_payload_conflict" ? {error: delivery.error} : {}), consumed: row.source_kind === "peer" && returnConsumed(root, key, row, reply, row.source_agent_id)}]; }); } diff --git a/loopx/control_plane/collaboration/result_publication.ts b/loopx/control_plane/collaboration/result_publication.ts index b15e062cab..9b45769f24 100644 --- a/loopx/control_plane/collaboration/result_publication.ts +++ b/loopx/control_plane/collaboration/result_publication.ts @@ -70,6 +70,15 @@ export function resultAttachmentRefs(params: JsonObject): JsonObject { return {refs}; } +/** Match the exact bytes normal publication writes to the original Chat. */ +export function returnTranscriptText(reply: JsonObject, exact: boolean): string { + const prefix = exact ? (reply.phase === "conclusion" ? "处理结论" : "处理进展") + : (reply.phase === "conclusion" ? "协作回复" : "协作进展"); + const provenance = `${prefix} · ${reply.agent_id} · 委托 ${String(reply.request_id).slice(0, 8)}`; + const body = collaborationResultText(reply); + return usesReaderReturnFormat(reply) ? `${body}\n\n${provenance}` : `${provenance}\n\n${body}`; +} + /** Explicit result files are content-bound observations, never new grants. */ export function resultAttachments(value: unknown): JsonObject[] { if (value === undefined || value === null) return []; diff --git a/loopx/control_plane/collaboration/return_delivery.ts b/loopx/control_plane/collaboration/return_delivery.ts index 498e359445..18256738f4 100644 --- a/loopx/control_plane/collaboration/return_delivery.ts +++ b/loopx/control_plane/collaboration/return_delivery.ts @@ -16,7 +16,9 @@ import { atomicWriteJson, withFileMutationLock } from "../effect_runtime_io.ts"; import { parseTodoTimestampMicros } from "../runtime_timestamp.ts"; import { decideCollaborationLifecycle } from "./goal_instance_lifecycle.ts"; import { resolveConversationScope } from "./conversation_scope.ts"; -import { planCollaborationResult, collaborationResultDeliveryReady, collaborationResultText, returnMessageId, usesReaderReturnFormat } from "./result_publication.ts"; +import { planCollaborationResult, collaborationResultDeliveryReady, returnMessageId, returnTranscriptText } from "./result_publication.ts"; +import {confirmedTerminalReturn, observeTerminalReturn, terminalReturnIdentityConflict, + TERMINAL_RETURN_READBACK_SUFFIX} from "./terminal_return_readback.ts"; export const MANAGER_RETURN_DELIVERY_ATTEMPT_SCHEMA = "manager_return_delivery_attempt_v0"; @@ -257,6 +259,30 @@ async function scanPredecessorReady(command: ReturnCommand): Promise { } } +function privateReadbackCandidate(command: ReturnCommand, state: JsonObject): boolean { + return deliveryProfileMatches(command, state) + && terminalReturnIdentityConflict(state, String(command.request.request_id), command.key) + && state.provider_receipt == null && state.attempt == null && state.reply_verified !== true; +} + +function readbackPath(command: ReturnCommand): string { + return join(command.folder, "replies", String(command.request.request_id), command.key + TERMINAL_RETURN_READBACK_SUFFIX); +} + +async function terminalReadback(command: ReturnCommand): Promise { + try { return await readReturnRecord(readbackPath(command)); } + catch (error) { if (!unavailableRecord(error)) throw error; return null; } +} + +async function scanPrivateReadback(command: ReturnCommand, state: JsonObject): Promise { + const id = String(command.request.request_id); + const route = await readReturnRecord(join(command.folder, "roundtrips", id + ".json")); + if (!route || route.kind === "peer" || resolveConversationScope(route).kind === "external_audience") return false; + const reply = await readReturnRecord(join(command.folder, "replies", id, command.key + ".json")); + return reply?.phase === "conclusion" + && confirmedTerminalReturn(await terminalReadback(command), state, reply, route) === null; +} + async function scanReturns(request: JsonObject): Promise { if (request.schema_version !== RETURN_DELIVERY_TRANSACTION) { throw new EffectRuntimeRequestError("return delivery transaction schema mismatch"); @@ -280,7 +306,9 @@ async function scanReturns(request: JsonObject): Promise { const command = returnCommand({...request, ...address, phase: "prepare", facts: {}}); try { const state = deliveryState(await readReturnRecord(command.path, {})); - if (TERMINAL.has(String(state.status))) terminalCandidates.push(address); + if (privateReadbackCandidate(command, state)) { + if (await scanPrivateReadback(command, state)) candidates.push(address); + } else if (TERMINAL.has(String(state.status))) terminalCandidates.push(address); else if (pendingDelivery(command, state) && await scanPredecessorReady(command)) candidates.push(address); } catch (error) { if (!unavailableRecord(error)) throw error; unavailable += 1; } } @@ -418,6 +446,40 @@ function returnAuthorityBlocker(command: ReturnCommand): string | null { return null; } +async function reconcilePrivateReturn(command: ReturnCommand, state: JsonObject): Promise { + if (!privateReadbackCandidate(command, state) || command.facts.error) return returnResponse(); + try { + const {reply} = await inspectReturnPublication(command); + const session = requireJsonObject(command.facts.session, "original session"); + const turn = requireJsonObject(command.facts.turn, "original Turn"); + const route = requireJsonObject(command.facts.route, "original route"); + if (reply.phase !== "conclusion" || route.kind === "peer" + || !resolveConversationScope(session).private_conversation + || session.session_id !== route.session_id || turn.client_turn_id !== route.client_turn_id + || !isDeepStrictEqual(state.goal_ref, reply.goal_ref) + || state.result_key !== undefined && state.result_key !== command.key + || returnAuthorityBlocker(command)) return returnResponse(); + + admitReturnLifetime(command, "original_return_settle"); + if (confirmedTerminalReturn(await terminalReadback(command), state, reply, route) !== null) return returnResponse(); + const revision = deliveryRevision(state); + const messageId = returnMessageId(String(command.request.request_id), command.key); + if (command.request.phase === "prepare") { + return returnResponse({action: "reconcile_private", revision, token: null, message_id: messageId}); + } + + if (command.request.revision !== revision) throw new EffectRuntimeRequestError("return delivery state changed"); + const message = requireJsonObject(command.request.private_readback, "original return readback"); + const proof = observeTerminalReturn(message, messageId, turn.turn_id, state, reply, route, command.exact); + if (!proof) return returnResponse(); + await atomicWriteJson(readbackPath(command), proof); + return returnResponse({processed: 1}); + } catch (error) { + if (!unavailableRecord(error)) throw error; + return returnResponse(); + } +} + async function prepareReturn(command: ReturnCommand, state: JsonObject): Promise { if (command.facts.error) return sourceFailure(command, state); let source: Awaited>; @@ -463,14 +525,8 @@ async function prepareReturn(command: ReturnCommand, state: JsonObject): Promise await writeDeliveryState(command, state); } const verify = priorStatus === "verification_required" || command.exact && state.attempt != null; - const prefix = command.exact ? (reply.phase === "conclusion" ? "处理结论" : "处理进展") - : (reply.phase === "conclusion" ? "协作回复" : "协作进展"); - const provenance = `${prefix} · ${reply.agent_id} · 委托 ${String(reply.request_id).slice(0, 8)}`; - const body = collaborationResultText(reply); - const text = usesReaderReturnFormat(reply) ? `${body}\n\n${provenance}` : `${provenance}\n\n${body}`; - return returnResponse({ action: privateConversation ? "private" : verify ? "verify" : "send", - text, message_id: returnMessageId(String(command.request.request_id), command.key), + text: returnTranscriptText(reply, command.exact), message_id: returnMessageId(String(command.request.request_id), command.key), attempt: verify ? savedAttempt(state.attempt) : null, attachments: reply.attachments ?? [], revision: deliveryRevision(state), token: (state.admission as JsonObject | undefined)?.token ?? null }); } @@ -572,7 +628,9 @@ export async function transactManagerReturnDelivery(value: unknown): Promise 0)) + || message.goal_draft != null || typeof deliveredAt !== "string" || deliveredAt.length > 64 + || parseTodoTimestampMicros(deliveredAt) === null) return null; + return {schema_version: SCHEMA, basis_sha256: basis(state, reply, route), delivered_at: deliveredAt}; +} diff --git a/loopx/control_plane/collaboration/turn_context.ts b/loopx/control_plane/collaboration/turn_context.ts index 6440f83ed1..c5ee3ee4e4 100644 --- a/loopx/control_plane/collaboration/turn_context.ts +++ b/loopx/control_plane/collaboration/turn_context.ts @@ -31,6 +31,7 @@ export function projectDelegationTurnItem(value: unknown): JsonObject | null { // Peer returns require their requester acknowledgement. An original Chat // return has a delivery receipt. const unconsumed = request.source_kind === "peer" ? results.filter(result => result.consumed !== true) : []; + const returnConflict = incomplete.find(result => result.error === "manager_return_payload_conflict"); let step: string; if (kind === "receipt_unavailable" || row.evidence_unavailable === true) step = "recover_evidence"; else if (cancelled) step = "reconcile_reservation"; @@ -38,13 +39,16 @@ export function projectDelegationTurnItem(value: unknown): JsonObject | null { else if (kind !== "settled") step = direction === "outgoing" ? "await_peer_result" : receipt.recorded_decision == null ? "assess_request" : receipt.recorded_decision === "adopt" ? "review_request_work" : "return_answer"; + else if (returnConflict) step = "recover_evidence"; else if (incomplete.length) step = "await_return_delivery"; else if (request.source_kind === "peer" && unconsumed.length) step = "await_peer_consumption"; else return null; const purpose = String(control?.brief && (control.brief as JsonObject).purpose || request.purpose || "").replace(/\s+/g, " ").trim(); const todos = Array.isArray(row.todo_ids) ? row.todo_ids : []; - const visibleReturns = (step === "consume_peer_result" ? unconsumed : results).slice(-3); + const recentReturns = (step === "consume_peer_result" ? unconsumed : results).slice(-3); + const visibleReturns = returnConflict && !recentReturns.includes(returnConflict) + ? [returnConflict, ...recentReturns.slice(-2)] : recentReturns; return { request_id: request.request_id, direction, ...(request.goal_ref ? {goal_ref: request.goal_ref} : {}), @@ -59,7 +63,8 @@ export function projectDelegationTurnItem(value: unknown): JsonObject | null { ...(todos.length ? {todo_ids: todos.slice(0, 4), additional_todo_count: Math.max(0, todos.length - 4)} : {}), ...(results.length ? {pending_return_count: incomplete.length, unconsumed_return_count: unconsumed.length, returns: visibleReturns.map(result => ({result_key: result.result_key, - request_revision: result.request_revision, status: result.status, consumed: result.consumed})), + request_revision: result.request_revision, status: result.status, consumed: result.consumed, + ...(result === returnConflict ? {error: returnConflict.error} : {})})), additional_return_count: results.length - visibleReturns.length} : {}), }; } diff --git a/tests/control_plane/test_chat_request_inventory.py b/tests/control_plane/test_chat_request_inventory.py index 9b4722bd26..56b5f33374 100644 --- a/tests/control_plane/test_chat_request_inventory.py +++ b/tests/control_plane/test_chat_request_inventory.py @@ -229,7 +229,7 @@ def test_read_and_adoption_still_owe_conclusion_and_queued_return_stays_visible( -def test_terminal_return_with_wrong_message_stays_unfinished_on_both_surfaces(api, capsys): +def test_terminal_return_reconciles_only_matching_original_message(api, capsys): import json from loopx.cli import main @@ -243,8 +243,11 @@ def test_terminal_return_with_wrong_message_stays_unfinished_on_both_surfaces(ap "adopt", "Check the requested artifact", registry=fixture["registry"], caller_goal_ref=fixture["ref"]) report(fixture["runtime"], route["goal_id"], route["agent_id"], request_id, "conclusion", "The requested artifact passed.", registry=fixture["registry"], caller_goal_ref=fixture["ref"]) - drain(fixture["runtime"], fixture["registry"], server.chat_store, - lambda *_: pytest.fail("a local return must not use an external sender")) + def drain_returns(): + return drain(fixture["runtime"], fixture["registry"], server.chat_store, + lambda *_: pytest.fail("a local return must not use an external sender")) + + assert drain_returns() == 1 def cli_agenda(): capsys.readouterr() @@ -268,20 +271,52 @@ def cli_agenda(): unrelated = server.chat_store.append_message(session_id, role="assistant", text="Another result", turn_id=turn["turn_id"], origin="manager_followup") assert unrelated["message_id"] != message_id - for corrupted in ({"message_id": unrelated["message_id"]}, {}): - incorrect = {key: value for key, value in json.loads(original).items() if key != "message_id"} - receipt.write_text(json.dumps({**incorrect, **corrupted})) - unchanged = receipt.read_bytes() + journal = server.chat_store.root / "sessions" / session_id / "messages.jsonl" + original_journal = journal.read_bytes() + + def assert_recovery(): http, pending = _inventory(api, session_id) assert http == 200 and pending["pending_count"] == 1 row, = pending["rows"] assert row["request_id"] == request_id + assert row["agenda"]["step"] == "recover_evidence" assert row["returns"][0]["status"] == "explicit_unverified" assert row["returns"][0]["error"] == "manager_return_payload_conflict" agenda, = cli_agenda() - assert agenda["request_id"] == request_id and agenda["step"] == "await_return_delivery" - assert agenda["returns"][0]["status"] == "explicit_unverified" + assert agenda["request_id"] == request_id and agenda["step"] == "recover_evidence" + assert agenda["returns"][0]["error"] == "manager_return_payload_conflict" + + def change_message(**changes): + modified = [] + for line in original_journal.splitlines(keepends=True): + row = json.loads(line) + if row["message_id"] == message_id: + line = (json.dumps({**row, **changes}) + "\n").encode() + modified.append(line) + return b"".join(modified) + + for corrupted, mismatch in (({"message_id": unrelated["message_id"]}, {"turn_id": turn["turn_id"]}), + ({}, {"text": "A different result in the correct Turn"})): + incorrect = {key: value for key, value in json.loads(original).items() if key != "message_id"} + receipt.write_text(json.dumps({**incorrect, **corrupted})) + unchanged = receipt.read_bytes() + assert_recovery() + changed_journal = change_message(**mismatch) + journal.write_bytes(changed_journal) + assert drain_returns() == 0 + assert_recovery() + assert journal.read_bytes() == changed_journal + assert receipt.read_bytes() == unchanged + + journal.write_bytes(original_journal) + assert drain_returns() == 1 + assert drain_returns() == 0 + assert cli_agenda() == [] + recovered = _inventory(api, session_id, view="history")[1] + assert recovered["pending_count"] == 0 + assert recovered["rows"][0]["returns"][0]["status"] == "delivered" assert receipt.read_bytes() == unchanged + assert journal.read_bytes() == original_journal receipt.write_bytes(original) assert cli_agenda() == [] restored = _inventory(api, session_id, view="history")[1] diff --git a/tests/control_plane_ts/manager_return_transaction.test.ts b/tests/control_plane_ts/manager_return_transaction.test.ts index 87abde9ed5..7b10f1e336 100644 --- a/tests/control_plane_ts/manager_return_transaction.test.ts +++ b/tests/control_plane_ts/manager_return_transaction.test.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import assert from "node:assert/strict"; import test from "node:test"; import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; @@ -7,6 +8,7 @@ import type { JsonObject } from "../../loopx/control_plane/effect_program.ts"; import { RETURN_DELIVERY_TRANSACTION, transactManagerReturnDelivery } from "../../loopx/control_plane/collaboration/return_delivery.ts"; const id = "a".repeat(64); +const conclusionMessageId = "handoff." + createHash("sha256").update(`["${id}", "conclusion"]`).digest("hex"); const now = "2026-01-02T03:04:05.123456+00:00"; const ref = { goal_id: "research", goal_instance_id: "ginst_" + "b".repeat(32) }; const attempt = { schema_version: "manager_return_delivery_attempt_v0", provider: "lark", @@ -61,6 +63,20 @@ for (const exact of [false, true]) { } finally { await f.close(); } }); + test(`a local transcript cannot confirm an external terminal return (${exact})`, async () => { + const f = await fixture(exact, true); + try { + await f.put(f.statePath, {status: "delivered", delivered_at: now, ...(exact ? {goal_ref: ref} : {})}); + const damaged = await readFile(f.statePath); + const plan = await f.run("prepare"); + assert.equal(plan.action, "skip"); + const attempted = await f.run("settle", {private_readback: {message_id: conclusionMessageId, + turn_id: "turn", role: "agent", origin: "manager_followup", created_at: now}}); + assert.equal(attempted.processed, 0); + assert.deepEqual(await readFile(f.statePath), damaged); + } finally { await f.close(); } + }); + test(`provider acceptance survives response loss and resumes by verification (${exact})`, async () => { const f = await fixture(exact, true); try { @@ -268,7 +284,7 @@ test("scan skips terminal and corrupt records but locked admission rechecks ever transactManagerReturnDelivery({ ...f.command, phase: "scan", candidates }); try { assert.deepEqual((await scan()).candidates, [{ request_id: id, result_key: "conclusion" }]); - await f.put(f.statePath, { status: "delivered" }); + await f.put(f.statePath, { status: "delivered", message_id: conclusionMessageId }); assert.deepEqual((await scan()).candidates, []); assert.equal((await f.run("prepare")).action, "skip"); await writeFile(f.statePath, "{broken"); @@ -441,7 +457,8 @@ test("scan emits terminal_candidates strictly for immutable terminal states", as for (const status of ["delivered", "superseded", "explicit_unverified"]) { const f = await fixture(exact, true); try { - await f.put(f.statePath, { status, ...(exact ? { goal_ref: ref } : {}) }); + await f.put(f.statePath, { status, ...(status === "delivered" ? { message_id: conclusionMessageId } : {}), + ...(exact ? { goal_ref: ref } : {}) }); const result = await f.run("scan", { candidates: [{ request_id: id, result_key: "conclusion" }] }); assert.deepEqual(result.candidates, []); assert.deepEqual(result.terminal_candidates, [{ request_id: id, result_key: "conclusion" }]); From 7f5a657f768732d1afc2d49b5fd92335d2a09a69 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:25:29 +0800 Subject: [PATCH 3/3] Read detailed delegation returns from the Inbox projection Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../capabilities/manager_context/tracking.py | 14 +++++++-- loopx/control_plane/collaboration/inbox.py | 4 ++- .../control_plane/collaboration/inbox_read.ts | 3 ++ .../test_chat_request_inventory.py | 30 +++++++++++++++---- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/loopx/capabilities/manager_context/tracking.py b/loopx/capabilities/manager_context/tracking.py index 3a9a5c861f..b9e9d66df3 100644 --- a/loopx/capabilities/manager_context/tracking.py +++ b/loopx/capabilities/manager_context/tracking.py @@ -15,6 +15,7 @@ _receipt as _receipt, record_read as record_read, controlled_request_readback, + read_inbox_transaction, ) from ...control_plane.collaboration.goal_instance_scope import ( CollaborationGoalScope, @@ -228,7 +229,15 @@ def _legacy_channels() -> dict[Any, set[Any]]: ) projected, todos_cache = [], {} core_read_goals = set(evidence_goal_scope(root, channel_id, registry_path=registry_path) or []) if not owner_scope else set() - for row in rows[offset : offset + limit]: + page = rows[offset : offset + limit] + returns = [] + if page: + returns = read_inbox_transaction(root, { + "operation": "receipt_states", + "rows": [{"request_id": row["request_id"], "source_kind": row.get("source_kind")} for row in page], + "return_statuses_only": True, + })["return_items"] + for row, return_statuses in zip(page, returns, strict=True): read, read_error = _receipt(root, "reads", row) decision, decision_error = _receipt(root, "decisions", row) work = read_linked_work(root, registry_path, row, todos_cache, @@ -262,8 +271,7 @@ def _legacy_channels() -> dict[Any, set[Any]]: evidence_verification="receiver_linked_reference_not_independent_verification", warnings=warnings, ) - from .roundtrip import reply_status - item["return_replies"] = reply_status(root, row) + item["return_replies"] = return_statuses if owner_scope: item["decision"]["reason"] = decision.get("reason") else: diff --git a/loopx/control_plane/collaboration/inbox.py b/loopx/control_plane/collaboration/inbox.py index 4acd4ad2f2..5e6a668a32 100644 --- a/loopx/control_plane/collaboration/inbox.py +++ b/loopx/control_plane/collaboration/inbox.py @@ -56,7 +56,9 @@ def read_inbox_transaction(root: Path, request: dict, *, scope=None) -> dict: ) if key in item} for item in request["items"]] # Full source pages may exceed the ordinary wire even when every record is legal. snapshot = request["operation"] in {"pending", "turn_start", "receiver_read", "returns"} - snapshot = snapshot or len(request.get("rows", [])) > 1 or request.get("include_agenda") is True + snapshot = snapshot or len(request.get("rows", [])) > 1 or any( + request.get(option) is True for option in ("include_agenda", "return_statuses_only") + ) try: result = effect_runtime_result("collaboration.inbox.read", facts, large_local_snapshot=snapshot) except EffectRuntimeRejected as exc: diff --git a/loopx/control_plane/collaboration/inbox_read.ts b/loopx/control_plane/collaboration/inbox_read.ts index 669f74f40f..ec760e2ed5 100644 --- a/loopx/control_plane/collaboration/inbox_read.ts +++ b/loopx/control_plane/collaboration/inbox_read.ts @@ -560,6 +560,9 @@ export async function readCollaborationInbox(params: JsonObject): Promise 128) fail("bounded inbox requests are required"); const rows = params.rows.map(row => requireJsonObject(row, "inbox request")); + if (params.return_statuses_only === true) { + return {return_items: rows.map(row => replyStatuses(root, row))}; + } const items = rows.map(row => receiptState(root, row)); if (params.include_agenda !== true) return {items}; const returnItems: JsonObject[][] = []; diff --git a/tests/control_plane/test_chat_request_inventory.py b/tests/control_plane/test_chat_request_inventory.py index 56b5f33374..e7615231ce 100644 --- a/tests/control_plane/test_chat_request_inventory.py +++ b/tests/control_plane/test_chat_request_inventory.py @@ -249,19 +249,29 @@ def drain_returns(): assert drain_returns() == 1 - def cli_agenda(): + def cli_inbox(operation, *selectors): capsys.readouterr() code = main(["--registry", str(fixture["registry"]), "--runtime-root", str(fixture["runtime"]), - "--format", "json", "manager-inbox", "read", "--goal-id", route["goal_id"], - "--agent-id", route["agent_id"]]) + "--format", "json", "manager-inbox", operation, "--goal-id", route["goal_id"], + "--agent-id", route["agent_id"], *selectors]) assert code == 0 - return json.loads(capsys.readouterr().out)["unfinished_delegations"]["items"] + return json.loads(capsys.readouterr().out) + + def cli_agenda(): + return cli_inbox("read")["unfinished_delegations"]["items"] + + def cli_return(): + row, = cli_inbox("status", "--request-id", request_id)["rows"] + assert row["request_id"] == request_id + conclusion, = row["return_replies"] + return conclusion receipt = root / "replies" / request_id / "conclusion.delivery.json" original = receipt.read_bytes() confirmed = _inventory(api, session_id, view="history")[1] assert confirmed["pending_count"] == 0 and confirmed["rows"][0]["returns"][0]["status"] == "delivered" assert cli_agenda() == [] + assert cli_return()["delivered_at"] == confirmed["rows"][0]["returns"][0]["delivered_at"] message_id = json.loads(original)["message_id"] messages = server.chat_store.messages(session_id) @@ -285,6 +295,9 @@ def assert_recovery(): agenda, = cli_agenda() assert agenda["request_id"] == request_id and agenda["step"] == "recover_evidence" assert agenda["returns"][0]["error"] == "manager_return_payload_conflict" + cli_return_state = cli_return() + for key in ("status", "delivered_at", "error"): + assert cli_return_state[key] == row["returns"][0][key] == agenda["returns"][0].get(key) def change_message(**changes): modified = [] @@ -298,6 +311,7 @@ def change_message(**changes): for corrupted, mismatch in (({"message_id": unrelated["message_id"]}, {"turn_id": turn["turn_id"]}), ({}, {"text": "A different result in the correct Turn"})): incorrect = {key: value for key, value in json.loads(original).items() if key != "message_id"} + incorrect["delivered_at"] = "2026-01-01T00:00:00Z" receipt.write_text(json.dumps({**incorrect, **corrupted})) unchanged = receipt.read_bytes() assert_recovery() @@ -314,7 +328,13 @@ def change_message(**changes): assert cli_agenda() == [] recovered = _inventory(api, session_id, view="history")[1] assert recovered["pending_count"] == 0 - assert recovered["rows"][0]["returns"][0]["status"] == "delivered" + return_state, = recovered["rows"][0]["returns"] + assert return_state["status"] == "delivered" + expected_delivery_time = next(row["created_at"] for row in messages if row["message_id"] == message_id) + assert return_state["delivered_at"] == expected_delivery_time != incorrect["delivered_at"] + detail = cli_return() + for key in ("status", "delivered_at", "error"): + assert detail[key] == return_state[key] assert receipt.read_bytes() == unchanged assert journal.read_bytes() == original_journal receipt.write_bytes(original)