diff --git a/loopx/capabilities/manager_context/README.md b/loopx/capabilities/manager_context/README.md index 06a3d4c6bb..3e625bdf2a 100644 --- a/loopx/capabilities/manager_context/README.md +++ b/loopx/capabilities/manager_context/README.md @@ -226,6 +226,11 @@ so a separate Chat store cannot split it from the recipient policy and inbox. The exact execution catalog and handoff dispatch use that same resolved root; private Session/Turn files remain in the existing Chat store. Controllers predating that root retain the existing Chat-parent layout. +Scheduled native Steward text results can complete in the original App +conversation after the host verifies the saved message identity, Turn and body. +That receipt records the App transcript delivery. An external provider attempt +keeps its own verification, including an unavailable transport or a pending +provider message locator. External on-demand context retries one invalidated local inventory snapshot when the exact Goal instances and current audience scope remain unchanged. This is a fresh read in the same Turn, without another model thread or request replay. diff --git a/loopx/capabilities/manager_context/roundtrip.py b/loopx/capabilities/manager_context/roundtrip.py index ab841426f1..25c5d4879a 100644 --- a/loopx/capabilities/manager_context/roundtrip.py +++ b/loopx/capabilities/manager_context/roundtrip.py @@ -677,7 +677,7 @@ def _return_transaction(host, path, phase, request): observed = dict(request["facts"]) for field, keys in { "session": ("session_id", "goal_id", "channel_id", "status", "project_context", "steward_context"), - "turn": ("turn_id", "client_turn_id", "status"), + "turn": ("turn_id", "client_turn_id", "status", "origin"), "grant": ("source_id", "targets"), }.items(): if isinstance(observed.get(field), dict): @@ -790,11 +790,13 @@ def transact(phase, **payload): record_attempt = _ReturnAttemptRecorder(transact, checkpoint, host["exact"]) try: - store.append_message(source["route"]["session_id"], role="agent", text=plan["text"], + original_message = store.append_message(source["route"]["session_id"], role="agent", text=plan["text"], turn_id=source["turn"]["turn_id"], origin="manager_followup", message_id=plan["message_id"]) if cancelled(): return 0 outcome = _return_provider(plan, source, sender, record_attempt) + if outcome["kind"] == "private" and source["turn"].get("origin") == "native_loopx": + outcome["original_message"] = original_message except ChatMessagePayloadConflictError as exc: logging.getLogger(__name__).warning("Manager return payload conflict on %s: %s", plan["message_id"], exc.field) outcome = {"kind": "conflict"} diff --git a/loopx/control_plane/collaboration/return_delivery.ts b/loopx/control_plane/collaboration/return_delivery.ts index 28f1e4ffbc..0e04a4bea4 100644 --- a/loopx/control_plane/collaboration/return_delivery.ts +++ b/loopx/control_plane/collaboration/return_delivery.ts @@ -454,6 +454,23 @@ function returnAuthorityBlocker(command: ReturnCommand): string | null { return null; } +function sourceChatReturnKind(command: ReturnCommand, state: JsonObject, reply: JsonObject): "private" | "native_loopx" | null { + const session = requireJsonObject(command.facts.session, "source session"); + const scope = resolveConversationScope(session); + if (scope.private_conversation) return "private"; + const priorStatus = (state.admission as JsonObject | undefined)?.prior_status ?? state.status; + if (!scope.bound_steward || state.attempt != null || state.provider_receipt != null + || priorStatus === "verification_required" || state.reply_verified === true + || Array.isArray(reply.attachments) && reply.attachments.length > 0) return null; + const turn = requireJsonObject(command.facts.turn, "source turn"); + const route = requireJsonObject(command.facts.route, "source route"); + // The source grant verifies the registered ingress against this Turn's + // origin and bound owner. Scheduled native work has the original App + // transcript as its return destination even when the Session is bound to Lark. + return turn.origin === "native_loopx" && route.kind !== "peer" && session.session_id === route.session_id + && turn.client_turn_id === route.client_turn_id && !returnAuthorityBlocker(command) ? "native_loopx" : null; +} + async function reconcilePrivateReturn(command: ReturnCommand, state: JsonObject): Promise { if (!privateReadbackCandidate(command, state) || command.facts.error) return returnResponse(); try { @@ -462,7 +479,7 @@ async function reconcilePrivateReturn(command: ReturnCommand, state: JsonObject) 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 + || !sourceChatReturnKind(command, state, reply) || 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 @@ -511,10 +528,10 @@ async function prepareReturn(command: ReturnCommand, state: JsonObject): Promise const previous = reply.previous_result_key == null ? null : await readReturnRecord(join(command.folder, "replies", String(reply.request_id), `${reply.previous_result_key}.delivery.json`)); if (!collaborationResultDeliveryReady({ result: reply, previous_delivery: previous }).ready) return returnResponse(); - const privateConversation = resolveConversationScope(requireJsonObject(command.facts.session, "session")).private_conversation; + const sourceChatReturn = sourceChatReturnKind(command, state, reply); const admission = state.admission == null ? null : requireJsonObject(state.admission, "return admission"); if (command.exact) { - if (state.status === "admitted" && state.attempt == null && !privateConversation) { + if (state.status === "admitted" && state.attempt == null && !sourceChatReturn) { await writeDeliveryState(command, { status: "explicit_unverified", error: "provider_delivery_unverified", goal_ref: reply.goal_ref }); return returnResponse(); } @@ -533,7 +550,7 @@ async function prepareReturn(command: ReturnCommand, state: JsonObject): Promise await writeDeliveryState(command, state); } const verify = priorStatus === "verification_required" || command.exact && state.attempt != null; - return returnResponse({ action: privateConversation ? "private" : verify ? "verify" : "send", + return returnResponse({ action: sourceChatReturn ? "private" : verify ? "verify" : "send", 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 }); @@ -610,7 +627,7 @@ async function finishReturn(command: ReturnCommand, state: JsonObject): Promise< if (command.exact || !available || !pendingDelivery(command, state) || state.attempt != null || source.inspected.interim_superseded || requireJsonObject(command.facts.route, "route").kind === "peer" || returnAuthorityBlocker(command) - || resolveConversationScope(requireJsonObject(command.facts.session, "session")).private_conversation) { + || sourceChatReturnKind(command, state, source.reply)) { throw new EffectRuntimeRequestError("external return dispatch is unavailable"); } // A restarted worker must not POST again without a provider locator. @@ -629,16 +646,25 @@ async function finishReturn(command: ReturnCommand, state: JsonObject): Promise< return returnResponse({ revision: deliveryRevision(checkpoint), token: command.request.token }); } if (command.request.phase !== "settle") throw new EffectRuntimeRequestError("unsupported return delivery phase"); + const outcome = requireJsonObject(command.request.outcome, "return outcome"); const settled = deliveryOutcome(command, state); - if (requireJsonObject(command.request.outcome, "return outcome").kind === "private" - && !resolveConversationScope(requireJsonObject(command.facts.session, "source session")).private_conversation) { - throw new EffectRuntimeRequestError("external return requires a provider outcome"); + if (outcome.kind === "private") { + const local = sourceChatReturnKind(command, state, source.reply); + if (!local) throw new EffectRuntimeRequestError("external return requires a provider outcome"); + if (local === "native_loopx") { + const turn = requireJsonObject(command.facts.turn, "original Turn"); + const route = requireJsonObject(command.facts.route, "original route"); + const message = requireJsonObject(outcome.original_message, "original App return"); + const proof = observeTerminalReturn(message, String(settled.message_id), turn.turn_id, + state, source.reply, route, command.exact); + if (!proof) throw new EffectRuntimeRequestError("original App return readback does not match"); + settled.delivered_at = proof.delivered_at; + } } if (settled.status === "explicit_unverified" && state.attempt != null) settled.attempt = state.attempt; if (command.exact) settled.goal_ref = requireJsonObject(command.facts.entry, "request").goal_ref; if (source.reply.result_key !== undefined) settled.result_key = source.reply.result_key; if (!isDeepStrictEqual(settled, state)) await writeDeliveryState(command, settled); - const outcome = requireJsonObject(command.request.outcome, "return outcome"); return returnResponse({ processed: command.exact || settled.status === "delivered" || ["error", "conflict", "sender_unavailable"].includes(String(outcome.kind)) ? 1 : 0, observe_verified: command.exact && settled.status === "delivered" && settled.reply_verified === true }); diff --git a/tests/extensions/test_lark_private_manager_returns.py b/tests/extensions/test_lark_private_manager_returns.py index ba179ea181..7049522420 100644 --- a/tests/extensions/test_lark_private_manager_returns.py +++ b/tests/extensions/test_lark_private_manager_returns.py @@ -211,10 +211,11 @@ def test_production_pump_returns_to_original_private_source_after_restart(privat assert capture.read_bytes() == before_host_calls -def test_scheduled_native_return_retains_original_chat_when_provider_transport_is_unavailable(private_return): +@pytest.mark.parametrize("case", ["new", "recover", "conflict", "revoked"]) +def test_scheduled_native_return_verifies_original_app_transcript(private_return, case): sender, session, _, original_route, _, provider, transport, replies = private_return - from loopx.capabilities.manager_context import register_ingress - from loopx.capabilities.manager_context.roundtrip import project_chat_return_deliveries + from loopx.capabilities.manager_context import _hash, register_ingress + from loopx.capabilities.manager_context.roundtrip import ReturnTransportUnavailable, project_chat_return_deliveries controller = transport.core.controller store = controller.store @@ -238,22 +239,60 @@ def test_scheduled_native_return_retains_original_chat_when_provider_transport_i acknowledge(sender.root, target["goal_id"], target["agent_id"], rid, "adopt", "Check the original request") conclusion = "The result remains available in the original Chat conversation." report(sender.root, target["goal_id"], target["agent_id"], rid, "conclusion", conclusion) + result_folder = _root(sender.root) / "replies" / rid + message_id = f"handoff.{_hash([rid, 'conclusion'])}" + saved = None + if case in {"recover", "conflict"}: + # Model the old pump stopping after the original append, when the + # provider adapter could not deliver a scheduled result. + adapter_text = f"{conclusion}\n\n协作回复 · {target['agent_id']} · 委托 {rid[:8]}" + saved = store.append_message(session_id, role="agent", turn_id=turn["turn_id"], + text=adapter_text if case == "recover" else "A different result", + origin="manager_followup", message_id=message_id) + _write(result_folder / "conclusion.delivery.json", { + "status": "retry_pending", "error": "return_transport_unavailable", "attempts": 1, + }) + if case == "revoked": + _write(_root(sender.root) / "policy.json", {"schema_version": POLICY_SCHEMA, "sources": {}}) + else: + adapter_route = _read_json(_root(sender.root) / "roundtrips" / f"{rid}.json") + with pytest.raises(ReturnTransportUnavailable): + sender(adapter_route, session, turn, conclusion) provider_count = len(provider.calls) - drain(sender.root, controller.registry_path, store, sender) - drain(sender.root, controller.registry_path, store, sender, - now=datetime.now(timezone.utc) + timedelta(minutes=10)) + wrong_host = ChatSessionStore(store.root.parent / "unrelated-chat") + assert drain(sender.root, controller.registry_path, wrong_host, sender) == 0 + assert wrong_host.messages(session_id) == [] + assert drain(sender.root, controller.registry_path, store, sender) == 1 state = reply_status(sender.root, route)[0] - assert state["status"] == "retry_pending" and state["error"] == "return_transport_unavailable", state + restarted = ChatSessionStore(store.root.parent) + assert drain(sender.root, controller.registry_path, restarted, sender, + now=datetime.now(timezone.utc) + timedelta(minutes=10)) == (1 if case == "revoked" else 0) assert replies == [] and len(provider.calls) == provider_count - messages = project_chat_return_deliveries(sender.root, session_id, store.messages(session_id), source_store=store) + messages = project_chat_return_deliveries(sender.root, session_id, restarted.messages(session_id), source_store=restarted) followups = [item for item in messages if item.get("origin") == "manager_followup"] + if case == "revoked": + assert state["status"] == "retry_pending" + assert state["error"] == "return_authorization_unavailable" + assert not followups + return + if case == "conflict": + assert state["status"] == "explicit_unverified" + assert state["error"] == "manager_return_payload_conflict" + assert len(followups) == 1 and followups[0]["text"] == saved["text"] + return + assert state["status"] == "delivered" + delivery = _read_json(result_folder / "conclusion.delivery.json") + assert delivery["message_id"] == message_id + assert "provider_receipt" not in delivery and "reply_verified" not in delivery assert len(followups) == 1 assert followups[0]["turn_id"] == turn["turn_id"] assert conclusion in followups[0]["text"] - assert followups[0]["return_delivery"]["status"] == "retry_pending" - assert followups[0]["return_delivery"]["error"] == "return_transport_unavailable" + assert followups[0]["return_delivery"]["status"] == "delivered" + assert delivery["delivered_at"] == followups[0]["created_at"] + if saved is not None: + assert followups[0]["created_at"] == saved["created_at"] @pytest.mark.parametrize("revoke_before_recovery", [False, True]) diff --git a/tests/test_collaboration_goal_instance.py b/tests/test_collaboration_goal_instance.py index dc3359231c..af67c2277f 100644 --- a/tests/test_collaboration_goal_instance.py +++ b/tests/test_collaboration_goal_instance.py @@ -216,6 +216,70 @@ def _manager_request(root: Path, registry: Path, *, channel="manager", complete= return store, session, receipt +def test_exact_scheduled_steward_return_recovers_in_original_app(tmp_path, monkeypatch): + from tests.control_plane.canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + from loopx.capabilities.manager_context import _hash + from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection + + isolate_sqlite_runtime(tmp_path, monkeypatch) + registry = _create_source_registry(tmp_path) + state_file = tmp_path / "active.md" + state_file.write_text("# Isolated delivery Goal\n") + initialize_canonical_authority(tmp_path, "delivery", + build_todo_runtime_shadow_projection(goal_id="delivery", todos=[], handoff_mode="soft_claim"), + state_path=state_file, provider="sqlite") + context = { + "kind": "bound_steward", "project_ref": "a" * 24, "workspace_path": str(tmp_path), + "audience": "bound_owner", "grant": "portfolio_read", "binding_id": "b" * 24, "source_ref": "c" * 24, + "provider_ref": "d" * 24, "operator_ref": "e" * 24, "goal_ids": [], + } + store = ChatSessionStore(tmp_path) + channel = f"manager.external.native.{context['binding_id']}.{context['source_ref']}" + session = store.create_session(goal_id="loopx-manager", agent_id="codex", adapter_kind="codex_app_server", + upstream_thread_id="fixture", channel_id=channel, steward_context=context) + session_id = session["session_id"] + accepted = store.accept_managed_turn(session_id, client_turn_id="native-advance", + message="Advance the currently admitted native LoopX work.", origin="native_loopx", loopx_execution=True) + turn = accepted.turn + target = {"goal_id": "delivery", "agent_id": "builder"} + _write(_root(tmp_path) / "policy.json", {"schema_version": POLICY_SCHEMA, "sources": { + channel: {"sender_ids": [context["operator_ref"]], "targets": [target]}, + }}) + register_ingress(tmp_path, session_id=session_id, client_turn_id=turn["client_turn_id"], channel=channel, + sender_id=context["operator_ref"], message=turn["message"], + source_id="native_steward:steward:advance", origin="native_loopx") + receipt = deliver(tmp_path, registry, session=session, turn=turn, request=target, source_store=store) + turn_id, rid, goal_ref = turn["turn_id"], receipt["request_id"], receipt["goal_ref"] + store.update_turn(session_id, turn_id, status="completing", + response={"message": "Delegated", "context_handoff_receipt": receipt}) + store.finalize_managed_turn_completion(session_id, turn_id) + acknowledge(tmp_path, "delivery", "builder", rid, "adopt", "Accepted", + registry=registry, caller_goal_ref=goal_ref) + report(tmp_path, "delivery", "builder", rid, "conclusion", "Verified the original delivery.", + registry=registry, caller_goal_ref=goal_ref) + message_id = f"handoff.{_hash([rid, 'conclusion'])}" + saved = store.append_message(session_id, role="agent", turn_id=turn_id, origin="manager_followup", + text=f"Verified the original delivery.\n\n处理结论 · builder · 委托 {rid[:8]}", message_id=message_id) + state_path = _root(tmp_path) / "replies" / rid / "conclusion.delivery.json" + _write(state_path, {"status": "retry_pending", "attempts": 1, + "error": "return_transport_unavailable", "goal_ref": goal_ref}) + + restarted = ChatSessionStore(tmp_path) + assert drain(tmp_path, registry, restarted, None) == 1 + after = state_path.read_bytes() + state = json.loads(after) + assert state["status"] == "delivered" and state["goal_ref"] == goal_ref + assert state["message_id"] == message_id and state["delivered_at"] == saved["created_at"] + assert "provider_receipt" not in state and "reply_verified" not in state + snapshot = _http_snapshot(tmp_path, registry, session_id) + returned = [row for row in snapshot["messages"] if row.get("origin") == "manager_followup"] + assert len(returned) == 1 and returned[0]["message_id"] == saved["message_id"] + assert returned[0]["text"] == saved["text"] and returned[0]["turn_id"] == turn_id + assert returned[0]["return_delivery"]["status"] == "delivered" + assert drain(tmp_path, registry, restarted, None) == 0 + assert state_path.read_bytes() == after + + def _external_manager_request(root: Path, registry: Path): store = ChatSessionStore(root) session = store.create_session(