From 3028214bf9517f1b862cf098f986e910b481a49e Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:40:58 +0800 Subject: [PATCH] feat(collaboration,lark): add private steward topic-level concurrent lanes Extend bound Steward private conversations to address child topic lanes under (binding_id, source_ref, topic_ref) while preserving parent conversation-binding authentication, portfolio grants, and disconnect revocation. - Derive manager.external.native...topic. channel identity in conversation_scope.ts and conversation_binding.ts, keeping Desktop App steward entry and managed Steward preparation pinned to the primary Lobby session. - Extend manager_context channel validation and revokeConversationSources so child topic lane grants are authorized and revoked atomically with their parent Steward binding. - Route explicit Lark thread replies to their topic lane and automatically fork a threaded topic lane (replying via --reply-in-thread) when an ordinary top-level message arrives while the primary Lobby session is busy, preserving top-level slash commands and @bot live steering on Lobby. - Add a bounded concurrency semaphore (default 4 concurrent active Steward lanes, configurable via LOOPX_STEWARD_MAX_CONCURRENT_LANES) in session_queue.py. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../capabilities/manager_context/__init__.py | 10 +- .../native_chat/conversation_bindings.py | 19 +- .../native_chat/external_conversations.py | 3 +- .../capabilities/native_chat/session_queue.py | 75 ++++- .../native_chat/steward_managed_mode.py | 5 +- .../collaboration/conversation_binding.ts | 20 +- .../collaboration/conversation_scope.ts | 19 +- .../collaboration/source_grants.ts | 2 +- loopx/extensions/lark/inbox_reply.py | 8 +- .../extensions/lark/private_conversations.py | 36 ++- loopx/extensions/lark/private_ingress.py | 7 +- loopx/extensions/lark/private_progress.py | 1 + loopx/extensions/lark/private_topic_lanes.py | 146 ++++++++++ .../steward_topic_lanes.test.ts | 265 ++++++++++++++++++ tests/test_steward_topic_lanes.py | 232 +++++++++++++++ 15 files changed, 796 insertions(+), 52 deletions(-) create mode 100644 loopx/extensions/lark/private_topic_lanes.py create mode 100644 tests/control_plane_ts/steward_topic_lanes.test.ts create mode 100644 tests/test_steward_topic_lanes.py diff --git a/loopx/capabilities/manager_context/__init__.py b/loopx/capabilities/manager_context/__init__.py index 2b6a5c3a3d..36335ad65c 100644 --- a/loopx/capabilities/manager_context/__init__.py +++ b/loopx/capabilities/manager_context/__init__.py @@ -350,7 +350,10 @@ def evidence_goal_scope(runtime_root: Path, channel: str, *, registry_path: Path def _require_external_channel(channel: str) -> None: # Legacy manager connections and native App/source bindings both identify # one exact audience. Never accept a prefix or a partially specified binding. - if not re.fullmatch(r"manager\.external\.(?:[a-f0-9]{24}|native\.[a-f0-9]{24}\.[a-f0-9]{24})", channel): + if not re.fullmatch( + r"manager\.external\.(?:[a-f0-9]{24}|native\.[a-f0-9]{24}\.[a-f0-9]{24}(?:\.topic\.[a-f0-9]{24})?)", + channel, + ): raise ValueError("an exact external manager channel is required") @@ -474,7 +477,10 @@ def configure_delivery_scope(runtime_root: Path, *, channel: str, local_delivery_scope: str, sender_id: str | None = None, execute: bool = False, if_absent: bool = False) -> dict: """One owner policy for current/future registered recipients, not execution.""" - if not re.fullmatch(r"manager\.external\.(?:[a-f0-9]{24}|native\.[a-f0-9]{24}\.[a-f0-9]{24})", channel): + if not re.fullmatch( + r"manager\.external\.(?:[a-f0-9]{24}|native\.[a-f0-9]{24}\.[a-f0-9]{24}(?:\.topic\.[a-f0-9]{24})?)", + channel, + ): raise ValueError("an exact external manager channel is required") path = _root(runtime_root) / "policy.json" diff --git a/loopx/capabilities/native_chat/conversation_bindings.py b/loopx/capabilities/native_chat/conversation_bindings.py index 28d10f60d4..c31276f147 100644 --- a/loopx/capabilities/native_chat/conversation_bindings.py +++ b/loopx/capabilities/native_chat/conversation_bindings.py @@ -212,9 +212,11 @@ def _reconcile_steward_executor(self, row: dict[str, Any], defaults: Mapping[str binding_id = row["binding_id"] endpoint = defaults["executor_endpoint"] channel_prefix = f"manager.external.native.{binding_id}." - candidates = [s for s in store.list_sessions() - if s.get("channel_id", "").startswith(channel_prefix) and s.get("status") != "closed"] - if len(candidates) != 1 or candidates[0].get("agent_id") != endpoint or candidates[0].get("status") != "ready": + all_open = [s for s in store.list_sessions() + if s.get("channel_id", "").startswith(channel_prefix) and s.get("status") != "closed"] + candidates = [s for s in all_open if not (s.get("steward_context") or {}).get("topic_ref")] + if (len(candidates) != 1 or candidates[0].get("agent_id") != endpoint or candidates[0].get("status") != "ready" + or any(s.get("status") != "ready" or s.get("active_turn_id") is not None for s in all_open)): return # Defaults alone do not retarget an existing session. observation = self.observe(row["transport_ref"]) with exclusive_file_lock(self.path, operation="reconcile_steward_executor"): @@ -369,8 +371,9 @@ def resolve(self, *, binding_id: str, source_ref: str, sender_ref: str, **({"origin": origin} if origin is not None else {}), **({"session_context": session_context} if session_context is not None else {}), **({"session": self._session_observation(session)} if session is not None else {}), - **({"group_ref": group_ref, "topic_ref": topic_ref, - "group_human_message": group_human_message} if group_ref is not None or topic_ref is not None or group_human_message else {}), + **({"group_ref": group_ref} if group_ref is not None else {}), + **({"topic_ref": topic_ref} if topic_ref is not None else {}), + **({"group_human_message": group_human_message} if group_ref is not None or group_human_message else {}), }) # Presentation may need the name from this exact verified read. Keep it # outside the persisted context and opt-in; it is never a cached grant @@ -395,7 +398,8 @@ def input_context(self, saved: dict[str, Any], *, origin: str, session: dict[str """ if origin == "web": source = {"source_ref": saved["source_ref"], "sender_ref": saved["operator_ref"], - "private_human_message": False, "origin": "web", "session_context": saved} + "private_human_message": False, "origin": "web", "session_context": saved, + **({"topic_ref": saved["topic_ref"]} if saved.get("topic_ref") else {})} elif origin in {"lark", "external"}: source = self._session_source(saved) else: @@ -539,7 +543,8 @@ def _session_source(saved: dict[str, Any]) -> dict[str, Any]: "private_human_message": False, "group_ref": saved["group_ref"], "topic_ref": saved["topic_ref"], "group_human_message": True, "session_context": saved} return {"source_ref": saved["source_ref"], "sender_ref": saved["operator_ref"], - "private_human_message": True, "session_context": saved} + "private_human_message": True, "session_context": saved, + **({"topic_ref": saved["topic_ref"]} if saved.get("topic_ref") else {})} def session_context(self, saved: dict[str, Any], *, session: dict[str, Any] | None = None) -> dict[str, Any]: return self.resolve(binding_id=saved["binding_id"], session=session, **self._session_source(saved)) diff --git a/loopx/capabilities/native_chat/external_conversations.py b/loopx/capabilities/native_chat/external_conversations.py index cd587e8d5c..e76181e6f6 100644 --- a/loopx/capabilities/native_chat/external_conversations.py +++ b/loopx/capabilities/native_chat/external_conversations.py @@ -1453,6 +1453,7 @@ def capture_native_mention(self, binding: dict[str, Any], source: dict[str, Any] allocation = session.get("manager_executor_allocation") or {} if (saved.get("binding_id") == binding["binding_id"] and saved.get("source_ref") == source["source_ref"] + and (saved.get("topic_ref") or None) == (source.get("topic_ref") or None) and session.get("status") in RESUMABLE_SESSION_STATES and (session.get("agent_id") == binding["executor_endpoint_id"] or binding["context_kind"] == "steward" and allocation.get("selection_policy") == "flexible")): @@ -1482,7 +1483,7 @@ def admit(self, *, binding_id: str, source: dict[str, Any], request_ref: str, # These references enter the lock path before authority is resolved. # Check path-safe shape here; the typed owner checks current grants # and provider identity after both fences are acquired. - for ref in (binding_id, source.get("source_ref")): + for ref in (binding_id, source.get("source_ref"), *([source["topic_ref"]] if "topic_ref" in source else ())): if not isinstance(ref, str) or not _REQUEST_JOURNAL_STEM.fullmatch(ref): raise ValueError("invalid external conversation source reference") path = self.root / f"{request_ref}.json" diff --git a/loopx/capabilities/native_chat/session_queue.py b/loopx/capabilities/native_chat/session_queue.py index ac7c9adef9..9239761f60 100644 --- a/loopx/capabilities/native_chat/session_queue.py +++ b/loopx/capabilities/native_chat/session_queue.py @@ -1,10 +1,63 @@ """The existing same-Session FIFO, preparation and recovery consumer.""" +from collections.abc import Iterator +from contextlib import contextmanager +import os from pathlib import Path from typing import Any import threading from ...chat_store import CHAT_SESSION_MODE_ATTACHED, TERMINAL_TURN_STATES +STEWARD_MAX_CONCURRENT_LANES_DEFAULT = 4 + + +def _resolve_steward_max_concurrent_lanes(controller: Any) -> int: + configured = getattr(controller, "max_steward_concurrent_lanes", None) + if isinstance(configured, int) and not isinstance(configured, bool) and 1 <= configured <= 32: + return configured + raw_env = os.environ.get("LOOPX_STEWARD_MAX_CONCURRENT_LANES", "").strip() + if raw_env.isdigit(): + parsed = int(raw_env) + if 1 <= parsed <= 32: + return parsed + return STEWARD_MAX_CONCURRENT_LANES_DEFAULT + + +def _steward_lane_semaphore(controller: Any) -> tuple[threading.BoundedSemaphore, int]: + limit = _resolve_steward_max_concurrent_lanes(controller) + with controller.lock: + current = getattr(controller, "_steward_lane_semaphore_state", None) + if current is None or current[1] != limit: + current = (threading.BoundedSemaphore(limit), limit) + controller._steward_lane_semaphore_state = current + return current + + +@contextmanager +def _acquire_steward_lane_slot(controller: Any, session: dict[str, Any] | None, turn: dict[str, Any] | None) -> Iterator[None]: + """Bound concurrent active upstream model Turns across Steward Topic Lanes.""" + channel_id = str((session or {}).get("channel_id") or "") + if ( + not session + or not isinstance(session.get("steward_context"), dict) + or not channel_id.startswith("manager.external.native.") + or _is_observation_only_monitor_turn(turn) + ): + yield + return + semaphore, _ = _steward_lane_semaphore(controller) + acquired = False + while not controller.closed.is_set(): + if semaphore.acquire(timeout=0.05): + acquired = True + break + if not acquired: + raise RuntimeError("chat runtime closed before steward lane slot acquisition") + try: + yield + finally: + semaphore.release() + def _is_observation_only_monitor_turn(turn: dict[str, Any] | None) -> bool: """Return True only for native no-model monitor turns.""" @@ -163,14 +216,20 @@ def _drain_session_queue_events(controller: Any, *, session_id: str, work_dir: P with controller.lock: controller.turn_done_events[(session_id, turn_id)] = done_event try: - controller._run_turn( - session_id=session_id, - turn_id=turn_id, - message=str(turn.get("message") or ""), - attachments=turn.get("attachments") or [], - adapter=adapter, - done_event=done_event, - ) + with _acquire_steward_lane_slot(controller, current, turn): + controller._run_turn( + session_id=session_id, + turn_id=turn_id, + message=str(turn.get("message") or ""), + attachments=turn.get("attachments") or [], + adapter=adapter, + done_event=done_event, + ) + except RuntimeError as exc: + if str(exc) == "chat runtime closed before steward lane slot acquisition": + controller._release_done_event((session_id, turn_id), done_event, drop_event=True) + return + raise except OSError: # _run_turn has released its execution fence/done event. # A failed error checkpoint must not kill this queue worker; diff --git a/loopx/capabilities/native_chat/steward_managed_mode.py b/loopx/capabilities/native_chat/steward_managed_mode.py index 42a9ba9049..2688f099c7 100644 --- a/loopx/capabilities/native_chat/steward_managed_mode.py +++ b/loopx/capabilities/native_chat/steward_managed_mode.py @@ -43,7 +43,10 @@ def _session(self, binding_id: str, session_id: str | None) -> dict[str, Any]: session = self.store.load_session(actor["session_id"]) else: candidates = self.bindings.local_sessions(binding_id) - candidates = [row for row in candidates if row.get("status") != "closed"] + candidates = [ + row for row in candidates + if row.get("status") != "closed" and not (row.get("steward_context") or {}).get("topic_ref") + ] channels = {row.get("channel_id") for row in candidates} if len(channels) != 1 or not candidates: raise ValueError("select the original private steward conversation first") diff --git a/loopx/control_plane/collaboration/conversation_binding.ts b/loopx/control_plane/collaboration/conversation_binding.ts index 9796619396..15f4221e7d 100644 --- a/loopx/control_plane/collaboration/conversation_binding.ts +++ b/loopx/control_plane/collaboration/conversation_binding.ts @@ -42,8 +42,10 @@ const hasConflictingRecoveryKey = (obj: JsonObject, allowed: string): boolean => const fieldsMatch = (left: JsonObject, right: JsonObject, keys: readonly string[]): boolean => keys.every(key => left[key] === right[key]); const isStewardEndpoint = (v: unknown): boolean => v === "antigravity" || v === "codex"; -const boundChannelId = (steward: boolean, bindingId: unknown, sourceRef: unknown): string => - `${steward ? "manager.external.native" : "project.external"}.${bindingId}.${sourceRef}`; +const boundChannelId = (steward: boolean, bindingId: unknown, sourceRef: unknown, topicRef?: unknown): string => + steward && isNonEmptyStr(topicRef) + ? `manager.external.native.${bindingId}.${sourceRef}.topic.${topicRef}` + : `${steward ? "manager.external.native" : "project.external"}.${bindingId}.${sourceRef}`; const recoveryClientBase = (row: JsonObject, version: number): string => `external-${ref(row.request_ref, "original request")}-recovery-${version}`; const reviewClientId = (row: JsonObject, version: number): string => `${recoveryClientBase(row, version)}-review-1`; @@ -72,6 +74,7 @@ const matchesAttachedSession = (current: JsonObject | null, target: JsonObject): const matchesPrivateOwnerSource = (selected: JsonObject, row: JsonObject, source: JsonObject, context: JsonObject): boolean => row.binding_id === selected.binding_id && source.private_human_message === true && source.sender_ref === selected.operator_ref && context.source_ref === source.source_ref + && (source.topic_ref ?? null) === (context.topic_ref ?? null) && fieldsMatch(context, selected, ["binding_id", "provider_ref", "operator_ref", "project_ref"]); const matchesNativeProofBase = (proof: JsonObject, current: JsonObject, row: JsonObject, failed: JsonObject): boolean => proof.thread_id === current.upstream_thread_id && proof.request_ref === row.request_ref @@ -395,8 +398,9 @@ export function resolveBoundConversation(params: JsonObject): JsonObject { topic = {group_ref: groupRef, topic_ref: topicRef, filesystem_scope: "workspace_only"}; } else { ensure(params.sender_ref === row.operator_ref && params.private_human_message === !local - && params.group_ref === undefined && params.topic_ref === undefined && params.group_human_message !== true, + && params.group_ref === undefined && (steward || params.topic_ref === undefined) && params.group_human_message !== true, "message audience is outside the binding grant"); + if (steward && params.topic_ref !== undefined) topic = {topic_ref: ref(params.topic_ref, "topic reference")}; } const project = boundProject(params, row); const goals = steward && row.goal_scope === "all_registered" @@ -414,7 +418,7 @@ export function resolveBoundConversation(params: JsonObject): JsonObject { const matches = steward ? matchesStewardContext(saved, context, row) : isDeepStrictEqual(saved, context); ensure(matches, "bound Session context changed"); } - const channel = boundChannelId(steward, id, source); + const channel = boundChannelId(steward, id, source, steward ? topic.topic_ref : undefined); if (params.session !== undefined) { const session = requireJsonObject(params.session, "canonical bound Session"); sessionIdentity(session.session_id, "bound Session identity"); @@ -453,7 +457,9 @@ export function listLocalBoundSessions(params: JsonObject): JsonObject { if (![session.project_context, session.steward_context].some(v => jsonObject(v)?.binding_id === id) || session.status === "closed") continue; const saved = requireJsonObject(steward ? session.steward_context : session.project_context, "bound Session context"); + if (params.app_steward_entry === true && steward && saved.topic_ref !== undefined) continue; resolveBoundConversation({...params, source_ref: saved.source_ref, session, + ...(steward && saved.topic_ref !== undefined ? {topic_ref: saved.topic_ref} : {}), sender_ref: row.operator_ref, private_human_message: false, origin: "web", session_context: saved}); ids.push(sessionIdentity(session.session_id, "bound Session identity")); } @@ -671,7 +677,7 @@ function planStewardBindingAdoptionHold(params: JsonObject, request: JsonObject) ensure(matchesPrivateOwnerSource(row, request, source, context) && context.audience === "bound_owner" && context.grant === "portfolio_read" && original.goal_id === "loopx-manager" && original.session_mode === "managed_runtime" - && original.project_context == null && original.channel_id === boundChannelId(true, row.binding_id, source.source_ref) + && original.project_context == null && original.channel_id === boundChannelId(true, row.binding_id, source.source_ref, context.topic_ref) && matchesStewardContext(saved, context, row), "the original steward Session belongs to another source"); return {operation: "hold_steward_binding", session_id: sessionIdentity(original.session_id, "original steward Session")}; } @@ -823,7 +829,7 @@ function planContextRecovery(params: JsonObject, row: JsonObject, current: JsonO const source = requireJsonObject(row.source, "original conversation source"); if (!matchesPrivateOwnerSource(selected, row, source, saved) || (!steward && saved.grant !== selected.grant) - || current.channel_id !== boundChannelId(steward, selected.binding_id, saved.source_ref)) return NO_RECOVERY; + || current.channel_id !== boundChannelId(steward, selected.binding_id, saved.source_ref, saved.topic_ref)) return NO_RECOVERY; const failed = requireJsonObject(recovery.failed_turn, "original failed Turn"); if (recovery.retained_result_review != null) { return (row.context_recovery as JsonObject | undefined)?.legacy_result_review === true @@ -1679,7 +1685,7 @@ function boundConversationStatus(params: JsonObject, current: JsonObject | null) ensure(fieldsMatch(context, selected, ["binding_id", "project_ref", "provider_ref", "operator_ref"]), "status context belongs to another binding"); const source = ref(context.source_ref, "status source identity"); - const channel = boundChannelId(steward, selected.binding_id, source); + const channel = boundChannelId(steward, selected.binding_id, source, context.topic_ref); const recipient = params.agent_target ? agentTarget(params.agent_target) : null; if (recipient) { ensure(matchesAttachedSession(current, recipient), "status Agent Session changed"); diff --git a/loopx/control_plane/collaboration/conversation_scope.ts b/loopx/control_plane/collaboration/conversation_scope.ts index 553cf75fcd..3037c8496c 100644 --- a/loopx/control_plane/collaboration/conversation_scope.ts +++ b/loopx/control_plane/collaboration/conversation_scope.ts @@ -111,21 +111,30 @@ export function normalizeStewardGoalScope(value: unknown): string[] { export function normalizeStewardContext(value: unknown): Record { if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("steward context unavailable"); const row = value as Record; - const workspace = normalizeProjectContext({...row, kind: "project_workspace", grant: "workspace_read"}); + const topicRef = row.topic_ref; + if (topicRef !== undefined && (typeof topicRef !== "string" || !/^[a-f0-9]{24}$/.test(topicRef))) { + throw new Error("invalid steward topic identity"); + } + const {topic_ref: _ignoredTopic, ...baseRow} = row; + const workspace = normalizeProjectContext({...baseRow, kind: "project_workspace", grant: "workspace_read"}); if (row.kind !== "bound_steward" || row.audience !== "bound_owner" || row.grant !== "portfolio_read" ) throw new Error("invalid bounded steward context"); - return {...workspace, kind: "bound_steward", grant: "portfolio_read", goal_ids: normalizeStewardGoalScope(row.goal_ids)}; + return {...workspace, ...(topicRef !== undefined ? {topic_ref: topicRef} : {}), + kind: "bound_steward", grant: "portfolio_read", goal_ids: normalizeStewardGoalScope(row.goal_ids)}; } export function stewardConversationIdentity(input: Record): Record { const context = normalizeStewardContext(input.context); + const channel_id = typeof context.topic_ref === "string" + ? `manager.external.native.${context.binding_id}.${context.source_ref}.topic.${context.topic_ref}` + : `manager.external.native.${context.binding_id}.${context.source_ref}`; if (input.metadata_review === true && input.answer_review === true) throw new Error("steward review modes are exclusive"); if (input.metadata_review === true || input.answer_review === true) { // Reuse the narrower native result-review policy without turning a // portfolio grant into project execution authority. Default to the existing // workspace-only frozen reads. The host may retain its already-authorized // trusted-owner read subset below; no writes or network are permitted. - const review = projectConversationIdentity({context: {...context, + const review = projectConversationIdentity({context: {...context, topic_ref: undefined, kind: "project_workspace", grant: "workspace_read"}, read_only_review: true}); const config = review.host_config as Record; config.features = {...config.features as object, shell_tool: false, @@ -143,9 +152,9 @@ export function stewardConversationIdentity(input: Record): Rec config.permissions = {[profile]: {...narrow, filesystem: {...narrow.filesystem as object, ":root": "read"}, network: {enabled: false}}}; } - return {...review, context, channel_id: `manager.external.native.${context.binding_id}.${context.source_ref}`}; + return {...review, context, channel_id}; } - return {context, channel_id: `manager.external.native.${context.binding_id}.${context.source_ref}`}; + return {context, channel_id}; } type ConversationScope = Record & ( diff --git a/loopx/control_plane/collaboration/source_grants.ts b/loopx/control_plane/collaboration/source_grants.ts index 1d4fe964c0..eabff98d59 100644 --- a/loopx/control_plane/collaboration/source_grants.ts +++ b/loopx/control_plane/collaboration/source_grants.ts @@ -80,7 +80,7 @@ export function revokeConversationSources(params: JsonObject): JsonObject { const sources = requireJsonObject(policy.sources, "context sources"); let changed = false; const retired = Object.fromEntries(Object.entries(sources).map(([key, value]) => { - const sourceBinding = /^manager\.external\.native\.([a-f0-9]{24})\.[a-f0-9]{24}$/.exec(key)?.[1]; + const sourceBinding = /^manager\.external\.native\.([a-f0-9]{24})\.[a-f0-9]{24}(?:\.topic\.[a-f0-9]{24})?$/.exec(key)?.[1]; if (sourceBinding !== id) return [key, value]; const source = requireJsonObject(value, "conversation source"); // Keep an explicit empty read scope: removing the row would restore the diff --git a/loopx/extensions/lark/inbox_reply.py b/loopx/extensions/lark/inbox_reply.py index dbe0fcd87f..c65ea0dec3 100644 --- a/loopx/extensions/lark/inbox_reply.py +++ b/loopx/extensions/lark/inbox_reply.py @@ -368,7 +368,7 @@ def _deliver_lark_inbox_outbound( "lark inbox reply source message is not captured by this inbox" ) if reply_placement is not None and ( - reply_placement != "chat_root" or source_event is None + reply_placement not in {"chat_root", "source_thread"} or source_event is None ): raise ValueError("a new result requires its captured authorization source") if content_format not in {"text", "markdown"}: @@ -409,7 +409,9 @@ def _deliver_lark_inbox_outbound( source_event and (source_event.get("parent_id") or source_event.get("root_id")) ) placement = ( - "chat_root" + "source_thread" + if reply_placement == "source_thread" + else "chat_root" if reply_placement == "chat_root" or source_event is None or ( reply_config["placement_policy"] == "source_context" @@ -750,7 +752,7 @@ def verify_source() -> tuple[bool, bool]: verified = bool( readback.get("returncode") == 0 and readback_message is not None - and (reply_placement is None or _private_root_readback_matches(readback_message, chat_id)) + and (reply_placement != "chat_root" or _private_root_readback_matches(readback_message, chat_id)) and (lark_markdown_readback_matches(text=reply_text, message=readback_message, attachment_keys=attachment_keys, attachment_names=attachment_names, image_keys=image_keys) if markdown else lark_readback_matches_outbound( diff --git a/loopx/extensions/lark/private_conversations.py b/loopx/extensions/lark/private_conversations.py index ecdbf67f57..4c41feb3ad 100644 --- a/loopx/extensions/lark/private_conversations.py +++ b/loopx/extensions/lark/private_conversations.py @@ -55,6 +55,7 @@ from .private_ingress import PrivateSourceUnavailable, private_source_text, recovery_source_matches, steward_source_preflight from .private_ingress import project_private_reply_history as project_private_reply_history from . import private_steward_triage as triage +from .private_topic_lanes import expected_private_source, finalize_private_steward_lane, resolve_private_steward_lane from .return_files import read_answer_images, uploaded_chat_images, verify_chat_images from .private_progress import (PROGRESS_EDIT_BUDGET as PROGRESS_EDIT_BUDGET, PrivateProgressMixin, presentation_phase, presentation_stream) @@ -775,21 +776,22 @@ def admit(self, profile: str, event: dict[str, Any], *, or binding.get("audience", "owner") != "owner" or event.get("chat_type") != "p2p"): return {"status": "history_answer_held"} request = identity_ref(binding["provider_ref"], event["message_id"]) - control_root = self._admitted_control_root({"request_ref": request, "source": source, - "event": event}, binding) + control_root = self._admitted_control_root({"request_ref": request, "source": source, "event": event}, binding) except (KeyError, StopIteration, ValueError): return {"status": "audience_rejected"} - path = self.root / f"{request}.json" + path, base_source = self.root / f"{request}.json", source record_event_timing(profile, event["message_id"], "binding_hint_ready") - def new_capture() -> dict[str, Any]: + def new_capture(resolved_source: dict[str, Any], auto_lane: bool) -> dict[str, Any]: return {"schema_version": "lark_private_chat_delivery_v0", "request_ref": request, "profile": profile, - "binding_id": binding["binding_id"], "source": source, "event": event, "deliveries": {}, "status": "captured", - **({"capture_origin": "provider_history"} if history_review else {})} + "binding_id": binding["binding_id"], "source": resolved_source, "event": event, "deliveries": {}, "status": "captured", + **({"auto_topic_lane": True} if auto_lane else {}), **({"capture_origin": "provider_history"} if history_review else {})} with exclusive_file_lock(path, operation="capture_private_chat_request"): record_event_timing(profile, event["message_id"], "capture_lock_acquired") fresh_capture = not path.exists() + source, auto_topic_lane = resolve_private_steward_lane(controller=self.core.controller, binding=binding, base_source=base_source, + event=event, existing_record=None if fresh_capture else _read_json(path), history_review=history_review, allow_auto_fork=False) # Retain a candidate from the locally bound owner before provider # identity IO can fail. This private receipt grants no execution: # recovery still verifies the App, current owner, source and Core @@ -797,7 +799,7 @@ def new_capture() -> dict[str, Any]: # existing pre-capture privacy boundary. if (fresh_capture and binding.get("enabled") is True and binding.get("audience", "owner") == "owner" and source.get("private_human_message") is True and source["sender_ref"] == binding["operator_ref"]): - _atomic_write_json(path, new_capture()) + _atomic_write_json(path, new_capture(source, auto_topic_lane)) mention_capture = self.core.capture_native_mention(binding, source) if fresh_capture else None if fresh_capture and path.exists(): captured = _read_json(path) @@ -825,7 +827,7 @@ def new_capture() -> dict[str, Any]: not omitted_private_thread and saved_event.get("thread_id") != event.get("thread_id")): return {"status": "source_conflict"} else: - record = new_capture() + record = new_capture(source, auto_topic_lane) if binding.get("audience") != "group": _atomic_write_json(path, record) # Verified transport-only replies have no Core Turn to recover. @@ -952,6 +954,9 @@ def read(tail: list[str]) -> Mapping[str, Any] | None: preflight = (steward_source_preflight(selected["binding"], source_message, lambda fresh: self._source_message(record, selected=fresh)) if command is None else None) native_mention = command is None and source_message.get("_native_mention") is True + source, selected = finalize_private_steward_lane(transport=self, path=path, record=record, binding=binding, + base_source=base_source, current_source=source, selected=selected, event=event, request_ref=request, + fresh_capture=fresh_capture, history_review=history_review, is_control_or_mention=(command is not None or native_mention)) if native_mention: previous_preflight = preflight @@ -1025,8 +1030,8 @@ def return_inbox(self, *, route: dict[str, Any], session: dict[str, Any], or turn.get("session_id") != session["session_id"] or record.get("profile") != selected["binding"]["transport_ref"] or record.get("request_ref") != request - or record.get("source") != lark_private_source( - provider_ref=selected["binding"]["provider_ref"], event=record["event"]) + or record.get("source") != expected_private_source( + provider_ref=selected["binding"]["provider_ref"], event=record["event"], saved_context=saved) or record["source"]["source_ref"] != saved["source_ref"] or any(row.get("binding_id") != saved["binding_id"] or row.get("source") != record["source"] @@ -1172,6 +1177,7 @@ def before_send(_intent: str) -> dict[str, bool]: save_phase(text=text, started=True) return {"continue_delivery": True} + effective_placement = "source_thread" if reply_placement is None and record.get("auto_topic_lane") is True else reply_placement if edit: result = update_lark_inbox_reply(**kwargs, previous_text=edit["text"], attempt=edit["attempt"], before_send=before_send, delivery_attempt_recorder=lambda value: save_phase(attempt=dict(value)), @@ -1197,8 +1203,8 @@ def before_send(_intent: str) -> dict[str, bool]: save_phase() return self._deliver(path, record, phase, text, inbox=inbox, finalize_source=finalize_source) elif phase_state.get("attempt"): - result = verify_lark_inbox_reply(**kwargs, attempt=phase_state["attempt"], resume_parts=True, - before_send=before_send) + result = verify_lark_inbox_reply(**{**kwargs, "reply_placement": effective_placement}, + attempt=phase_state["attempt"], resume_parts=True, before_send=before_send) elif phase_state.get("started"): # A crash between provider write and its receipt is ambiguous. Keep # the original source recoverable; never resend blindly or churn disk. @@ -1210,7 +1216,7 @@ def attempt(value: Any) -> None: phase_state["attempt"] = dict(value) _atomic_write_json(path, record) - result = reply_lark_event_inbox(**kwargs, execute=True, before_send=before_send, + result = reply_lark_event_inbox(**{**kwargs, "reply_placement": effective_placement}, execute=True, before_send=before_send, delivery_attempt_recorder=attempt, short_message_limit=None, content_format="markdown", overlap_source_preflight=bool(kind == "terminal" and self._completed_stop_root( @@ -1678,8 +1684,8 @@ def _received_during_recovery(self, path: Path) -> None: or turn.get("client_turn_id") != (record.get("context_recovery", {}).get("client_turn_id") or f"external-{record['request_ref']}") or identity_ref(saved["provider_ref"], record["event"]["message_id"]) != record["request_ref"] - or record["source"] != lark_private_source( - provider_ref=saved["provider_ref"], event=record["event"])): + or record["source"] != expected_private_source( + provider_ref=saved["provider_ref"], event=record["event"], saved_context=saved)): return selected = self.bindings.resolve(binding_id=record["binding_id"], session_context=saved, include_observation=True, **record["source"]) diff --git a/loopx/extensions/lark/private_ingress.py b/loopx/extensions/lark/private_ingress.py index ddcb3fcffd..69dffd8312 100644 --- a/loopx/extensions/lark/private_ingress.py +++ b/loopx/extensions/lark/private_ingress.py @@ -19,7 +19,8 @@ from ...capabilities.native_chat.file_discovery import FileChatDiscovery from ...file_lock import try_exclusive_file_lock from ...chat_store import _read_json -from .conversation_identity import identity_ref, lark_private_source +from .conversation_identity import identity_ref +from .private_topic_lanes import expected_private_source from .goal_channel_transport import call, json_payload, lark_args from .group_history import _provider_page from .inbox_reply import _message @@ -230,7 +231,9 @@ def project_private_reply_history(store: Any, session: dict[str, Any], native = _read_json(store.root / "external-requests" / f"{request}.json") if not isinstance(record.get("event"), dict): raise ValueError("unreadable original event") - source = lark_private_source(provider_ref=saved["provider_ref"], event=record["event"]) + source = expected_private_source( + provider_ref=saved["provider_ref"], event=record["event"], saved_context=saved + ) # Recovery moves the correlation journal forward, retaining its # original failed Turn. Read those exact recorded identities. recoveries = [native.get("context_recovery") or {}, *native.get("context_recovery_history", [])] diff --git a/loopx/extensions/lark/private_progress.py b/loopx/extensions/lark/private_progress.py index 50bb80047b..87762f7e44 100644 --- a/loopx/extensions/lark/private_progress.py +++ b/loopx/extensions/lark/private_progress.py @@ -260,6 +260,7 @@ def _retire_progress_parts(self: LarkPrivateConversations, path: Path, record: d return False result = verify_lark_inbox_reply(project=self.runtime_root, config_path=inbox(), message_id=record["event"]["message_id"], text=stream.get("confirmed_text") or progress["text"], attempt=attempt, runner=self._reply_runner, + reply_placement="source_thread" if record.get("auto_topic_lane") is True else None, finalize_reactions=False, source_authority_verifier=partial(self._source_authority, record)) stream["blocker"] = result.get("blocker") verified = result.get("reply_verified") is True and result.get("ok") is True diff --git a/loopx/extensions/lark/private_topic_lanes.py b/loopx/extensions/lark/private_topic_lanes.py new file mode 100644 index 0000000000..8615b1f5d0 --- /dev/null +++ b/loopx/extensions/lark/private_topic_lanes.py @@ -0,0 +1,146 @@ +"""Topic-lane routing helpers for private Steward Lark conversations. + +Parent conversation bindings retain sole identity and portfolio authority. +Child topic lanes isolate concurrent session queues and upstream threads under +``(binding_id, source_ref, topic_ref)`` without creating a second binding or +mutating historical non-threaded request provenance. +""" +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from .conversation_identity import identity_ref, lark_private_source +from .identity_shapes import LARK_MESSAGE_ID_PATTERN + + +def expected_private_source( + *, + provider_ref: str, + event: Mapping[str, Any], + saved_context: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Return canonical private provenance, preserving an admitted Steward topic_ref.""" + base = lark_private_source(provider_ref=provider_ref, event=event) + topic_ref = (saved_context or {}).get("topic_ref") if isinstance(saved_context, Mapping) else None + if isinstance(topic_ref, str) and topic_ref: + return {**base, "topic_ref": topic_ref} + return base + + +def _has_open_session(store: Any, channel_id: str) -> bool: + return any( + row.get("status") != "closed" + for row in store.list_sessions(channel_id=channel_id) + ) + + +def _lobby_session_busy(store: Any, channel_id: str) -> bool: + for row in store.list_sessions(channel_id=channel_id): + if row.get("status") == "closed": + continue + session = store.load_session(str(row["session_id"])) + if session is None or session.get("status") == "closed": + continue + if session.get("active_turn_id") or store.queued_turns(str(session["session_id"])): + return True + return False + + +def resolve_private_steward_lane( + *, + controller: Any, + binding: Mapping[str, Any], + base_source: dict[str, Any], + event: Mapping[str, Any], + existing_record: Mapping[str, Any] | None = None, + history_review: bool = False, + allow_auto_fork: bool = True, + is_control_or_mention: bool = False, +) -> tuple[dict[str, Any], bool]: + """Resolve ``(source, auto_topic_lane)`` for one p2p Steward admission.""" + if existing_record is not None and isinstance(existing_record.get("source"), Mapping): + frozen = dict(existing_record["source"]) + if all(frozen.get(k) == base_source.get(k) for k in ("source_ref", "sender_ref", "private_human_message")): + return frozen, bool(existing_record.get("auto_topic_lane")) + if ( + history_review + or binding.get("context_kind") != "steward" + or binding.get("audience", "owner") != "owner" + or event.get("chat_type") != "p2p" + or base_source.get("private_human_message") is not True + ): + return base_source, False + + store = controller.store + binding_id = str(binding["binding_id"]) + provider_ref = str(binding["provider_ref"]) + chat_id = str(event.get("chat_id") or "") + message_id = str(event.get("message_id") or "") + raw_content = str(event.get("content") or "").strip() + is_slash_command = is_control_or_mention or raw_content.startswith("/") + has_mentions = is_control_or_mention or bool(event.get("mentions")) + ancestry_root = str(event.get("root_id") or event.get("parent_id") or "").strip() + + if ancestry_root and LARK_MESSAGE_ID_PATTERN.fullmatch(ancestry_root): + topic_ref = identity_ref(provider_ref, chat_id, ancestry_root) + topic_channel = f"manager.external.native.{binding_id}.{base_source['source_ref']}.topic.{topic_ref}" + if is_slash_command or has_mentions: + if _has_open_session(store, topic_channel): + return {**base_source, "topic_ref": topic_ref}, False + return base_source, False + auto_thread = not bool(event.get("root_id") or event.get("thread_id")) + return {**base_source, "topic_ref": topic_ref}, auto_thread + + if ( + not allow_auto_fork + or is_slash_command + or has_mentions + or str(event.get("message_type") or "") not in {"text", "image", "post"} + or not LARK_MESSAGE_ID_PATTERN.fullmatch(message_id) + ): + return base_source, False + + lobby_channel = f"manager.external.native.{binding_id}.{base_source['source_ref']}" + if not _lobby_session_busy(store, lobby_channel): + return base_source, False + + topic_ref = identity_ref(provider_ref, chat_id, message_id) + return {**base_source, "topic_ref": topic_ref}, True + + +def finalize_private_steward_lane( + *, + transport: Any, + path: Any, + record: dict[str, Any], + binding: Mapping[str, Any], + base_source: dict[str, Any], + current_source: dict[str, Any], + selected: dict[str, Any], + event: Mapping[str, Any], + request_ref: str, + fresh_capture: bool, + history_review: bool, + is_control_or_mention: bool, +) -> tuple[dict[str, Any], dict[str, Any]]: + """Upgrade a fresh top-level Steward capture to a Topic Lane when Lobby is busy.""" + from ...chat_store import _atomic_write_json + + if not fresh_capture or (transport.core.root / f"{request_ref}.json").exists() or current_source != base_source: + return current_source, selected + resolved_source, auto_topic_lane = resolve_private_steward_lane( + controller=transport.core.controller, + binding=binding, + base_source=base_source, + event=event, + history_review=history_review, + is_control_or_mention=is_control_or_mention, + ) + if resolved_source != record["source"] or auto_topic_lane != bool(record.get("auto_topic_lane")): + record["source"] = resolved_source + if auto_topic_lane: + record["auto_topic_lane"] = True + _atomic_write_json(path, record) + selected = transport.bindings.resolve(binding_id=str(binding["binding_id"]), **resolved_source, include_observation=True) + return resolved_source, selected diff --git a/tests/control_plane_ts/steward_topic_lanes.test.ts b/tests/control_plane_ts/steward_topic_lanes.test.ts new file mode 100644 index 0000000000..fc9a22a2f0 --- /dev/null +++ b/tests/control_plane_ts/steward_topic_lanes.test.ts @@ -0,0 +1,265 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + listLocalBoundSessions, + planBoundConversationRequest, + resolveBoundConversation, +} from "../../loopx/control_plane/collaboration/conversation_binding.ts"; +import { + normalizeStewardContext, + resolveConversationScope, + stewardConversationIdentity, +} from "../../loopx/control_plane/collaboration/conversation_scope.ts"; +import { revokeConversationSources } from "../../loopx/control_plane/collaboration/source_grants.ts"; + +const BINDING_ID = "e0e2226022a24adf9209cbe7"; +const PROVIDER_REF = "111111111111111111111111"; +const OPERATOR_REF = "222222222222222222222222"; +const SOURCE_REF = "333333333333333333333333"; +const PROJECT_REF = "444444444444444444444444"; +const TOPIC_REF = "555555555555555555555555"; +const REQUEST_REF = "666666666666666666666666"; + +function baseFixtures() { + const stewardBinding = { + schema_version: "loopx_chat_conversation_binding_v0", + binding_id: BINDING_ID, + transport_ref: "personal-steward", + provider_ref: PROVIDER_REF, + operator_ref: OPERATOR_REF, + context_kind: "steward", + project_ref: PROJECT_REF, + executor_endpoint_id: "codex", + grant: "portfolio_read", + enabled: true, + goal_ids: ["goal-alpha"], + goal_scope: "all_registered", + }; + const projectBinding = { + schema_version: "loopx_chat_conversation_binding_v0", + binding_id: "777777777777777777777777", + transport_ref: "project-bot", + provider_ref: "888888888888888888888888", + operator_ref: OPERATOR_REF, + context_kind: "project", + project_ref: PROJECT_REF, + executor_endpoint_id: "codex", + grant: "workspace_read", + enabled: true, + }; + const current = { + schema_version: "loopx_chat_conversation_bindings_v0", + revision: 3, + app_steward_binding_id: BINDING_ID, + bindings: [stewardBinding, projectBinding], + }; + const observation = { + verified: true, + transport_ref: "personal-steward", + provider_ref: PROVIDER_REF, + operator_ref: OPERATOR_REF, + }; + const availableProjects = [ + { + kind: "project_workspace", + project_ref: PROJECT_REF, + workspace_path: "/workspace/steward-home", + audience: "local_owner", + grant: "workspace_read", + }, + ]; + return { stewardBinding, projectBinding, current, observation, availableProjects }; +} + +test("steward topic_ref derives child topic channel and preserves bound_steward scope", () => { + const context = normalizeStewardContext({ + kind: "bound_steward", + project_ref: PROJECT_REF, + workspace_path: "/workspace/steward-home", + audience: "bound_owner", + grant: "portfolio_read", + binding_id: BINDING_ID, + source_ref: SOURCE_REF, + provider_ref: PROVIDER_REF, + operator_ref: OPERATOR_REF, + topic_ref: TOPIC_REF, + goal_ids: ["goal-alpha"], + }); + assert.equal(context.topic_ref, TOPIC_REF); + const identity = stewardConversationIdentity({ context }); + const expectedChannel = `manager.external.native.${BINDING_ID}.${SOURCE_REF}.topic.${TOPIC_REF}`; + assert.equal(identity.channel_id, expectedChannel); + + const scope = resolveConversationScope({ + goal_id: "loopx-manager", + channel_id: expectedChannel, + steward_context: context, + origin: "lark", + }); + assert.equal(scope.kind, "external_audience"); + assert.equal(scope.bound_steward, true); + assert.equal(scope.private_conversation, false); + + assert.throws( + () => + normalizeStewardContext({ + ...context, + topic_ref: "not-a-valid-24-hex-ref", + }), + /invalid steward topic identity/, + ); +}); + +test("resolveBoundConversation admits private steward topic lanes while rejecting private project topic_ref", () => { + const { current, observation, availableProjects } = baseFixtures(); + const resolved = resolveBoundConversation({ + current, + binding_id: BINDING_ID, + observation, + available_projects: availableProjects, + available_goal_ids: ["goal-alpha", "goal-beta"], + source_ref: SOURCE_REF, + sender_ref: OPERATOR_REF, + private_human_message: true, + topic_ref: TOPIC_REF, + }); + assert.equal( + resolved.channel_id, + `manager.external.native.${BINDING_ID}.${SOURCE_REF}.topic.${TOPIC_REF}`, + ); + assert.equal((resolved.context as Record).topic_ref, TOPIC_REF); + assert.equal(resolved.owner_manager_audience, true); + + assert.throws( + () => + resolveBoundConversation({ + current, + binding_id: "777777777777777777777777", + observation: { + verified: true, + transport_ref: "project-bot", + provider_ref: "888888888888888888888888", + operator_ref: OPERATOR_REF, + }, + available_projects: availableProjects, + source_ref: SOURCE_REF, + sender_ref: OPERATOR_REF, + private_human_message: true, + topic_ref: TOPIC_REF, + }), + /message audience is outside the binding grant/, + ); +}); + +test("listLocalBoundSessions keeps app_steward_entry pinned to primary lobby session", () => { + const { current, observation, availableProjects } = baseFixtures(); + const lobbyContext = { + kind: "bound_steward", + project_ref: PROJECT_REF, + workspace_path: "/workspace/steward-home", + audience: "bound_owner", + grant: "portfolio_read", + binding_id: BINDING_ID, + source_ref: SOURCE_REF, + provider_ref: PROVIDER_REF, + operator_ref: OPERATOR_REF, + goal_ids: ["goal-alpha"], + }; + const topicContext = { ...lobbyContext, topic_ref: TOPIC_REF }; + const sessions = [ + { + session_id: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + goal_id: "loopx-manager", + agent_id: "codex", + executor_endpoint_id: "codex", + channel_id: `manager.external.native.${BINDING_ID}.${SOURCE_REF}`, + session_mode: "managed_runtime", + status: "ready", + project_context: null, + steward_context: lobbyContext, + }, + { + session_id: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + goal_id: "loopx-manager", + agent_id: "codex", + executor_endpoint_id: "codex", + channel_id: `manager.external.native.${BINDING_ID}.${SOURCE_REF}.topic.${TOPIC_REF}`, + session_mode: "managed_runtime", + status: "ready", + project_context: null, + steward_context: topicContext, + }, + ]; + + const allLocal = listLocalBoundSessions({ + current, + binding_id: BINDING_ID, + observation, + available_projects: availableProjects, + available_goal_ids: ["goal-alpha"], + sessions, + }); + assert.deepEqual(allLocal.session_ids, [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ]); + + const appEntry = listLocalBoundSessions({ + current, + binding_id: BINDING_ID, + observation, + available_projects: availableProjects, + available_goal_ids: ["goal-alpha"], + sessions, + app_steward_entry: true, + }); + assert.deepEqual(appEntry.session_ids, ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]); + + const statusPlan = planBoundConversationRequest({ + request: { + request_ref: REQUEST_REF, + binding_id: BINDING_ID, + source: { + source_ref: SOURCE_REF, + sender_ref: OPERATOR_REF, + private_human_message: true, + topic_ref: TOPIC_REF, + }, + command: "status", + message: "/status", + }, + binding: current.bindings[0], + current_session: sessions[1], + context: topicContext, + observed_at: "2026-11-23T11:00:00Z", + queued_count: 0, + active_turn: null, + }); + assert.equal(statusPlan.operation, "reply"); + assert.equal(statusPlan.session_id, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); + + const revoked = revokeConversationSources({ + binding_id: BINDING_ID, + policy: { + schema_version: "loopx_manager_context_policy_v1", + sources: { + [`manager.external.native.${BINDING_ID}.${SOURCE_REF}`]: { + sender_ids: [OPERATOR_REF], + local_delivery_scope: "all_registered", + }, + [`manager.external.native.${BINDING_ID}.${SOURCE_REF}.topic.${TOPIC_REF}`]: { + sender_ids: [OPERATOR_REF], + local_delivery_scope: "all_registered", + }, + }, + }, + }); + assert.equal(revoked.would_change, true); + const sources = (revoked.policy as Record>>).sources; + assert.deepEqual(sources[`manager.external.native.${BINDING_ID}.${SOURCE_REF}`].sender_ids, []); + assert.deepEqual( + sources[`manager.external.native.${BINDING_ID}.${SOURCE_REF}.topic.${TOPIC_REF}`].sender_ids, + [], + ); +}); diff --git a/tests/test_steward_topic_lanes.py b/tests/test_steward_topic_lanes.py new file mode 100644 index 0000000000..ba75c26f0f --- /dev/null +++ b/tests/test_steward_topic_lanes.py @@ -0,0 +1,232 @@ +from __future__ import annotations + +import threading +import time +from typing import Any + +from loopx.extensions.lark.conversation_identity import identity_ref +from test_native_steward_private import finish, steward # noqa: F401 + + +def _wait_turn_running(store: Any, session_id: str, turn_id: str, timeout: float = 8.0) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + turn = store.load_turn(session_id, turn_id) + if turn and turn.get("status") in {"starting", "running"} and turn.get("upstream_turn_id"): + return + time.sleep(0.02) + raise AssertionError(f"Turn {turn_id} in session {session_id} did not reach running state") + + +def test_steward_explicit_topic_runs_concurrently_without_waiting_on_busy_lobby(steward): # noqa: F811 + store, runtime, provider, transport, binding, _, _ = steward + try: + lobby_event = provider.event("steward-app", "lobby-slow", "wait for interrupt") + assert transport.admit("steward-app", lobby_event)["status"] == "durably_accepted" + lobby_ref = identity_ref(binding["provider_ref"], lobby_event["message_id"]) + lobby_req = transport.core.read_request(lobby_ref) + _wait_turn_running(store, lobby_req["session_id"], lobby_req["turn_id"]) + + # Explicit Feishu topic message arrives while Lobby is blocked on a long turn. + root = provider.event("steward-app", "topic-anchor", "Earlier topic root") + topic_event = provider.event("steward-app", "topic-question", "Quick read-only check in topic") + topic_event.update( + root_id=root["message_id"], + parent_id=root["message_id"], + thread_id=f"omt_{root['message_id']}", + ) + provider.messages[topic_event["message_id"]].update( + root_id=root["message_id"], + parent_id=root["message_id"], + thread_id=f"omt_{root['message_id']}", + ) + assert transport.admit("steward-app", topic_event)["status"] == "durably_accepted" + topic_ref_id = identity_ref(binding["provider_ref"], topic_event["message_id"]) + topic_req = transport.core.read_request(topic_ref_id) + + assert topic_req["session_id"] != lobby_req["session_id"] + expected_topic_ref = identity_ref(binding["provider_ref"], topic_event["chat_id"], root["message_id"]) + assert topic_req["source"]["topic_ref"] == expected_topic_ref + + # Topic lane finishes immediately even while Lobby turn is still running! + completed_topic = finish(runtime, topic_req) + assert completed_topic["status"] == "completed" + assert store.load_turn(lobby_req["session_id"], lobby_req["turn_id"])["status"] == "running" + + transport.reconcile() + assert any(root_id == root["message_id"] for _, root_id, _ in provider.topic_writes) + + # Cleanly stop the busy Lobby turn. + stop_lobby = provider.event("steward-app", "stop-lobby", "/stop") + assert transport.admit("steward-app", stop_lobby)["status"] == "command_recorded" + assert finish(runtime, lobby_req)["status"] == "interrupted" + finally: + runtime.close() + + +def test_busy_lobby_auto_forks_new_topic_lane_and_preserves_followup_continuity(steward): # noqa: F811 + store, runtime, provider, transport, binding, _, _ = steward + try: + # Select App steward so we can verify Desktop App stays pinned to Lobby. + transport.bindings.select_app_steward( + binding["binding_id"], expected_revision=transport.bindings.read()["revision"] + ) + + # 1. Start a long-running turn in Lobby. + lobby_event = provider.event("steward-app", "lobby-busy", "wait for interrupt") + assert transport.admit("steward-app", lobby_event)["status"] == "durably_accepted" + lobby_req = transport.core.read_request(identity_ref(binding["provider_ref"], lobby_event["message_id"])) + _wait_turn_running(store, lobby_req["session_id"], lobby_req["turn_id"]) + + # 2. Send a top-level independent message while Lobby is busy -> auto-forks new Topic Lane! + top_followup = provider.event("steward-app", "auto-fork-msg", "Independent question while lobby busy") + assert transport.admit("steward-app", top_followup)["status"] == "durably_accepted" + fork_ref = identity_ref(binding["provider_ref"], top_followup["message_id"]) + fork_req = transport.core.read_request(fork_ref) + fork_delivery = transport.root / f"{fork_ref}.json" + + assert fork_req["session_id"] != lobby_req["session_id"] + expected_lane = identity_ref(binding["provider_ref"], top_followup["chat_id"], top_followup["message_id"]) + assert fork_req["source"]["topic_ref"] == expected_lane + assert finish(runtime, fork_req)["status"] == "completed" + + # Reconcile delivers the reply in a new Feishu thread rooted at top_followup["message_id"]! + assert transport.reconcile_request(fork_delivery) == 1 + assert any( + root_id == top_followup["message_id"] + for _, root_id, _ in provider.topic_writes + ) + + # 3. User replies inside that newly created Feishu thread -> hits the EXACT SAME child session! + in_thread = provider.event("steward-app", "thread-continuation", "Follow-up inside the forked thread") + in_thread.update( + root_id=top_followup["message_id"], + parent_id=top_followup["message_id"], + thread_id=f"omt_{top_followup['message_id']}", + ) + provider.messages[in_thread["message_id"]].update( + root_id=top_followup["message_id"], + parent_id=top_followup["message_id"], + thread_id=f"omt_{top_followup['message_id']}", + ) + assert transport.admit("steward-app", in_thread)["status"] == "durably_accepted" + cont_req = transport.core.read_request(identity_ref(binding["provider_ref"], in_thread["message_id"])) + assert cont_req["session_id"] == fork_req["session_id"] + assert finish(runtime, cont_req)["status"] == "completed" + + # 4. Desktop App steward target still points to primary Lobby session, never hijacked by child lane! + assert transport.bindings.app_steward_session()["session_id"] == lobby_req["session_id"] + + # Stop Lobby cleanly. + transport.admit("steward-app", provider.event("steward-app", "stop-lobby-2", "/stop")) + assert finish(runtime, lobby_req)["status"] == "interrupted" + finally: + runtime.close() + + +def test_steward_topic_lanes_enforce_bounded_concurrency_limit(steward, monkeypatch): # noqa: F811 + store, runtime, provider, transport, binding, _, _ = steward + runtime.max_steward_concurrent_lanes = 2 + + active_lock = threading.Lock() + active_count = 0 + peak_active = 0 + two_running = threading.Event() + release_turns = threading.Event() + original_run_turn = runtime._run_turn + + def tracked_run_turn(**kwargs: Any) -> Any: + nonlocal active_count, peak_active + with active_lock: + active_count += 1 + peak_active = max(peak_active, active_count) + if active_count >= 2: + two_running.set() + try: + release_turns.wait(timeout=8.0) + return original_run_turn(**kwargs) + finally: + with active_lock: + active_count -= 1 + + monkeypatch.setattr(runtime, "_run_turn", tracked_run_turn) + try: + requests = [] + for idx in range(4): + root = provider.event("steward-app", f"root-{idx}", f"Topic root {idx}") + ev = provider.event("steward-app", f"msg-{idx}", f"Parallel topic message {idx}") + ev.update( + root_id=root["message_id"], + parent_id=root["message_id"], + thread_id=f"omt_{root['message_id']}", + ) + provider.messages[ev["message_id"]].update( + root_id=root["message_id"], + parent_id=root["message_id"], + thread_id=f"omt_{root['message_id']}", + ) + assert transport.admit("steward-app", ev)["status"] == "durably_accepted" + requests.append(transport.core.read_request(identity_ref(binding["provider_ref"], ev["message_id"]))) + + assert len({r["session_id"] for r in requests}) == 4 + assert two_running.wait(timeout=5.0) + # Give the 3rd and 4th queue workers a window to contend on the semaphore. + time.sleep(0.15) + assert peak_active == 2 + + release_turns.set() + for req in requests: + assert finish(runtime, req)["status"] == "completed" + assert peak_active == 2 + finally: + release_turns.set() + runtime.close() + + +def test_topic_lane_stop_and_status_are_lane_scoped_without_stopping_lobby(steward): # noqa: F811 + store, runtime, provider, transport, binding, _, _ = steward + try: + # Start a slow turn in Lobby. + lobby_ev = provider.event("steward-app", "lobby-keep-alive", "wait for interrupt") + assert transport.admit("steward-app", lobby_ev)["status"] == "durably_accepted" + lobby_req = transport.core.read_request(identity_ref(binding["provider_ref"], lobby_ev["message_id"])) + _wait_turn_running(store, lobby_req["session_id"], lobby_req["turn_id"]) + + # Start a slow turn in a distinct Topic Lane. + root = provider.event("steward-app", "topic-stop-root", "Topic root") + topic_ev = provider.event("steward-app", "topic-slow", "wait for interrupt") + topic_ev.update( + root_id=root["message_id"], + parent_id=root["message_id"], + thread_id=f"omt_{root['message_id']}", + ) + provider.messages[topic_ev["message_id"]].update( + root_id=root["message_id"], + parent_id=root["message_id"], + thread_id=f"omt_{root['message_id']}", + ) + assert transport.admit("steward-app", topic_ev)["status"] == "durably_accepted" + topic_req = transport.core.read_request(identity_ref(binding["provider_ref"], topic_ev["message_id"])) + _wait_turn_running(store, topic_req["session_id"], topic_req["turn_id"]) + + # Send /stop inside the Topic Lane -> interrupts ONLY the Topic Lane, NOT Lobby! + stop_topic = provider.event("steward-app", "stop-topic-only", "/stop") + stop_topic.update( + root_id=root["message_id"], + parent_id=topic_ev["message_id"], + thread_id=f"omt_{root['message_id']}", + ) + provider.messages[stop_topic["message_id"]].update( + root_id=root["message_id"], + parent_id=topic_ev["message_id"], + thread_id=f"omt_{root['message_id']}", + ) + assert transport.admit("steward-app", stop_topic)["status"] == "command_recorded" + assert finish(runtime, topic_req)["status"] == "interrupted" + assert store.load_turn(lobby_req["session_id"], lobby_req["turn_id"])["status"] == "running" + + # Now stop Lobby cleanly. + assert transport.admit("steward-app", provider.event("steward-app", "stop-lobby-final", "/stop"))["status"] == "command_recorded" + assert finish(runtime, lobby_req)["status"] == "interrupted" + finally: + runtime.close()