The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): preserve conversation ownership for worker completions
Alex0b86710cefa1
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex ff0653db49d..0aa26773278 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -22,7 +22,7 @@ from agent.i18n import tfrom gateway.config import Platform, _BUILTIN_PLATFORM_VALUESfrom gateway.platforms.base import BasePlatformAdapter, _mark_notify_metadatafrom gateway.platforms.event import MessageEvent, MessageType-from gateway.session import SessionEntry, SessionSource+from gateway.session import SessionEntry, SessionSource, SessionStorefrom gateway.run_shutdown import _delivery_target_key, _log_suppressed, _notice_target_key, _send_error, _send_failed# Log-record parity with the origin module.@@ -263,6 +263,54 @@ class GatewayNotificationsMixin:return Nonereturn target_session_id+ async def _lookup_completion_owner(self, session_id: str, current_session_id: str = ""):+ """Nonmutating delegation proof shared by preflight and route resolution.++ A current route is an explicit ownership boundary, not a route to repair.+ Generic parent pointers also describe compression and branches; only+ ``_delegate_from`` authorizes walking out of an execution transcript.+ """+ from gateway.run import _USER_BOUNDARY_END_REASONS+ session_db = cast(Any, self)._session_db+ if session_db is None:+ return "retry", session_id, None+ seen = set()+ for hops in range(_MAX_DELEGATE_PROVENANCE_HOPS + 1):+ if session_id in seen:+ return "terminal", session_id, None+ seen.add(session_id)+ try:+ row = await session_db.get_session(session_id)+ except Exception:+ logger.debug("Completion ownership lookup failed for %s", session_id, exc_info=True)+ return "retry", session_id, None+ if row is None:+ return "terminal", session_id, None+ # User closure is a boundary at EVERY hop, including execution rows.+ # Ordinary delegate completion may still follow provenance to its owner.+ if row.get("ended_at") and row.get("end_reason") in _USER_BOUNDARY_END_REASONS:+ return "terminal", session_id, row+ if session_id == current_session_id:+ return "deliver", session_id, row+ config = row.get("model_config")+ try:+ if isinstance(config, str):+ config = json.loads(config)+ except (TypeError, ValueError):+ return "terminal", session_id, None+ if config is None:+ config = {}+ if not isinstance(config, dict):+ return "terminal", session_id, None+ if "_delegate_from" not in config:+ verdict = "terminal" if row.get("source") == "subagent" else "deliver"+ return verdict, session_id, row+ parent = config["_delegate_from"]+ if not isinstance(parent, str) or not parent.strip() or hops == _MAX_DELEGATE_PROVENANCE_HOPS:+ return "terminal", session_id, None+ session_id = parent+ return "terminal", session_id, None+async def _resolve_async_delegation_session(self, session_entry: SessionEntry, pinned_session_id: str,) -> Optional[SessionEntry]:@@ -288,76 +336,12 @@ class GatewayNotificationsMixin:"dropping injection (#55578 fail-closed).")return None- pinned_row = None- # Snapshot the run generation before the row lookup awaits: a /stop or /new landing while- # the lookup is pending must not let this completion re-point the route afterwards.+ # Snapshot before ownership awaits: a concurrent /stop or /new wins.run_generation = self._current_session_run_generation(session_entry.session_key)- try:- pinned_row = await session_db.get_session(pinned_session_id)- except Exception:- logger.debug("Async-delegation parent lookup failed for %s", pinned_session_id, exc_info=True)- if pinned_row is None:- logger.warning(- "Async-delegation completion has unknown spawning session %s; "- "dropping injection (#55578 fail-closed).", pinned_session_id,- )- return None- # Delegate rows are execution transcripts, not gateway route owners. A process completion can- # be stamped with the child session id even though the human-facing conversation belongs to- # `_delegate_from`. Follow that durable provenance before any route verification or mutation;- # otherwise switch_session() can end the real parent and rebind the platform chat to an- # internal child (#92611).- #- # Real nesting is bounded by delegation.max_spawn_depth (default 2), so the hop cap only- # guards a corrupt/hand-edited chain: without it a single completion event could fan out- # into hundreds of sequential get_session() reads before terminating.- delegate_chain: set[str] = set()- for _ in range(_MAX_DELEGATE_PROVENANCE_HOPS + 1):- if pinned_session_id in delegate_chain:- logger.warning(- "Async-delegation completion has cyclic delegate provenance at session %s; "- "dropping injection (#92611).", pinned_session_id,- )- return None- delegate_chain.add(pinned_session_id)- model_config = pinned_row.get("model_config")- if isinstance(model_config, str):- try:- model_config = json.loads(model_config)- except (TypeError, ValueError):- logger.warning(- "Async-delegation completion has malformed model_config for session %s; "- "dropping injection (#92611).", pinned_session_id,- )- return None- if model_config is not None and not isinstance(model_config, dict):- logger.warning(- "Async-delegation completion has non-object model_config for session %s; "- "dropping injection (#92611).", pinned_session_id,- )- return None- if not isinstance(model_config, dict):- model_config = {}- delegate_parent_id = str(model_config.get("_delegate_from") or "").strip()- if not delegate_parent_id:- break- try:- delegate_parent_row = await session_db.get_session(delegate_parent_id)- except Exception:- delegate_parent_row = None- if delegate_parent_row is None:- logger.warning(- "Async-delegation completion has missing delegate parent %s for child %s; "- "dropping injection (#92611).", delegate_parent_id, pinned_session_id,- )- return None- pinned_session_id = delegate_parent_id- pinned_row = delegate_parent_row- else:- logger.warning(- "Async-delegation completion exceeded %d delegate provenance hops (last session %s); "- "dropping injection (#92611).", _MAX_DELEGATE_PROVENANCE_HOPS, pinned_session_id,- )+ verdict, pinned_session_id, pinned_row = await self._lookup_completion_owner(+ pinned_session_id, session_entry.session_id,+ )+ if verdict != "deliver" or pinned_row is None:return Nonetarget_session_id = pinned_session_idfollows_compression = False@@ -1232,6 +1216,9 @@ class GatewayNotificationsMixin:watch_events = _drain_gateway_watch_events(completion_queue)for evt in watch_events:async with self._completion_event_scope(evt):+ from tools.process_registry_notifications import should_surface_notification+ if not should_surface_notification(evt):+ continueif self._load_background_notifications_mode() == "off":continuesynth_text = _format_gateway_process_notification(evt)@@ -1475,7 +1462,7 @@ class GatewayNotificationsMixin:self._completion_deliveries_inflight.add(identity)return seen- async def _classify_completion_target(self, parent_session_id: str) -> str:+ async def _classify_completion_target(self, parent_session_id: str, session_key: str = "") -> str:"""Classify an async-completion target before adapter acceptance: ``"deliver"`` (spawningsession live or compression-rotated with a live continuation; the resolver still retargets),``"terminal"`` (parent gone for good — unknown / user boundary like /new; drop the durable row@@ -1484,13 +1471,20 @@ class GatewayNotificationsMixin:session_db = getattr(self, "_session_db", None)if session_db is None:return "retry"- try:- parent = await session_db.get_session(parent_session_id)- except Exception:- logger.debug("Async-completion pre-flight parent lookup failed for %s", parent_session_id, exc_info=True)- return "retry"- if parent is None:- return "terminal"+ entry = None+ if session_key:+ try:+ session_store = cast(SessionStore, getattr(self, "session_store"))+ await asyncio.to_thread(session_store._ensure_loaded)+ entry = session_store._entries.get(session_key)+ except Exception:+ logger.debug("Completion route lookup failed for %s", session_key, exc_info=True)+ return "retry"+ verdict, parent_session_id, parent = await self._lookup_completion_owner(+ parent_session_id, entry.session_id if entry else "",+ )+ if verdict != "deliver" or parent is None:+ return verdictif not parent.get("ended_at"):return "deliver"end_reason = str(parent.get("end_reason") or "")@@ -1509,6 +1503,10 @@ class GatewayNotificationsMixin:return "retry"if tip is None or tip.get("ended_at"):return "retry"+ if entry is not None and await self._resolve_compression_lineage_target(+ session_db, entry, parent_session_id,+ ) is None:+ return "terminal"return "deliver"@staticmethod@@ -1527,7 +1525,7 @@ class GatewayNotificationsMixin:parent_session_id = str(evt.get("parent_session_id") or "").strip()if parent_session_id:- verdict = await self._classify_completion_target(parent_session_id)+ verdict = await self._classify_completion_target(parent_session_id, str(evt.get("session_key") or ""))if verdict != "deliver":# Definitively closed targets still need the normal terminal disposition.return verdict == "terminal"@@ -1590,7 +1588,7 @@ class GatewayNotificationsMixin:# can still fail closed inside the message pipeline AFTER the adapter accepted, which would falsely# acknowledge the durable row as delivered. Verify the target here, before acceptance, and give# drops an honest durable disposition.- verdict = await self._classify_completion_target(parent_session_id)+ verdict = await self._classify_completion_target(parent_session_id, str(evt.get("session_key") or ""))if verdict == "terminal":if evt_type == "async_delegation":logger.warning(@@ -1654,6 +1652,9 @@ class GatewayNotificationsMixin:self, synth_text: str, evt: dict, *, sibling_claims=(),) -> Optional[bool]:from gateway.wake import WakeNotAccepted+ from tools.process_registry_notifications import should_surface_notification+ if not should_surface_notification(evt):+ return None # Suppressed noise is terminal, not a consumed process result.identity = self._completion_delivery_identity(evt)claim = self._CompletionClaim()accepted = identity_claimed = refused = False@@ -1796,7 +1797,13 @@ class GatewayNotificationsMixin:getattr(self, "_completion_notification_batch_flush_tasks", set()).clear()async def _enqueue_process_completion_notification(self, synth_text: str, evt: dict) -> Optional[bool]:- """Fan in concurrent process completions that share one conversation."""+ """Fan in policy-admitted process completions with compatible pinned owners."""+ # Filter each event before it can contaminate (or suppress) a foreground batch.+ # The shared queue may be drained outside the owning profile's runtime scope.+ async with self._completion_event_scope(evt):+ from tools.process_registry_notifications import should_surface_notification+ if not should_surface_notification(evt):+ return None# Lazy defaults: lifecycle tests build GatewayRunner via object.__new__.for attr, default in (("_completion_notification_batches", dict), ("_completion_notification_batch_tasks", dict),@@ -1808,7 +1815,11 @@ class GatewayNotificationsMixin:setattr(self, attr, default())if self._completion_notification_batches_stopping:return False- key = self._event_route_key(evt, self._COMPLETION_BATCH_KEY_FIELDS)+ # A route key alone is not ownership: /new can leave old and new pins+ # in the same queue. Never settle one pin on another pin's acceptance.+ key = self._event_route_key(+ evt, (*self._COMPLETION_BATCH_KEY_FIELDS, "parent_session_id", "origin_session_id"),+ )future = asyncio.get_running_loop().create_future()self._completion_notification_batches.setdefault(key, []).append((synth_text, evt, future))if key not in self._completion_notification_batch_tasks:@@ -1863,6 +1874,10 @@ class GatewayNotificationsMixin:synth_text = _format_gateway_process_notification(evt)if not synth_text:continue+ parent = str(evt.get("parent_session_id") or "")+ if parent and await self._classify_completion_target(parent, str(evt.get("session_key") or "")) == "terminal":+ await self._deliver_completion_notification(synth_text, evt)+ continueidentity = self._completion_delivery_identity(evt)if identity is not None and self._completion_identity_seen(identity):continue@@ -2061,6 +2076,8 @@ class GatewayNotificationsMixin:"type": "completion","session_id": session_id,**{k: watcher.get(k, "") for k in _WATCHER_ROUTE_FIELDS},+ "owner_task_id": getattr(session, "owner_task_id", "") or "",+ "task_id": getattr(session, "task_id", "") or "","message_id": str(watcher.get("message_id") or "").strip() or None,"started_at": getattr(session, "started_at", None),"command": _redact_gateway_user_facing_secrets(_command),@@ -2118,7 +2135,7 @@ class GatewayNotificationsMixin:the output tail) / all (running updates + final raw) / result (final raw) / error (final rawif exit != 0) / off."""from tools.process_registry import process_registry- from tools.process_registry_notifications import format_process_notification+ from tools.process_registry_notifications import format_process_notification, should_surface_notificationsession_id = watcher["session_id"]interval = watcher["check_interval"]platform_name = watcher.get("platform", "")@@ -2138,6 +2155,16 @@ class GatewayNotificationsMixin:session = process_registry.get(session_id)if session is None:break+ async with self._completion_event_scope(watcher):+ surface = should_surface_notification({+ "owner_task_id": getattr(session, "owner_task_id", ""),+ "task_id": getattr(session, "task_id", ""),+ })+ if not surface:+ # Recheck live ownership next tick: handoff retains notification intent.+ if session.exited:+ break+ continueif silent:# Still wait for the process to exit so we can log it, but don't push any messages.if session.exited:diff --git a/tests/gateway/test_async_delegation_session_binding.py b/tests/gateway/test_async_delegation_session_binding.pyindex 1c392ca7729..74c8a457572 100644--- a/tests/gateway/test_async_delegation_session_binding.py+++ b/tests/gateway/test_async_delegation_session_binding.py@@ -115,173 +115,6 @@ class TestGatewayPinningFailsClosed:current.session_key, "sess_live", expected_session_id=current.session_id,)- @pytest.mark.asyncio- async def test_live_delegate_child_resolves_to_parent_without_rebinding_route(self):- current = self._entry("sess_parent")- runner = self._make_runner(- {- "sess_parent": {"id": "sess_parent", "ended_at": None},- "sess_child": {- "id": "sess_child",- "ended_at": None,- "model_config": {"_delegate_from": "sess_parent"},- },- },- )-- resolved = await runner._resolve_async_delegation_session(current, "sess_child")-- assert resolved is current- self._assert_no_route_change(runner)-- @pytest.mark.asyncio- async def test_nested_delegate_child_resolves_to_gateway_parent(self):- current = self._entry("sess_parent")- runner = self._make_runner(- {- "sess_parent": {"id": "sess_parent", "ended_at": None},- "sess_child": {- "id": "sess_child",- "ended_at": None,- "model_config": {"_delegate_from": "sess_parent"},- },- "sess_grandchild": {- "id": "sess_grandchild",- "ended_at": None,- "model_config": {"_delegate_from": "sess_child"},- },- },- )-- resolved = await runner._resolve_async_delegation_session(current, "sess_grandchild")-- assert resolved is current- self._assert_no_route_change(runner)-- @pytest.mark.asyncio- async def test_delegate_provenance_cycle_fails_closed_without_route_change(self):- current = self._entry("sess_current")- runner = self._make_runner(- {- "sess_a": {- "id": "sess_a",- "ended_at": None,- "model_config": {"_delegate_from": "sess_b"},- },- "sess_b": {- "id": "sess_b",- "ended_at": None,- "model_config": {"_delegate_from": "sess_a"},- },- },- )-- resolved = await runner._resolve_async_delegation_session(current, "sess_a")-- assert resolved is None- self._assert_no_route_change(runner)-- @pytest.mark.asyncio- async def test_self_referential_delegate_provenance_fails_closed(self):- current = self._entry("sess_current")- runner = self._make_runner(- {- "sess_self": {- "id": "sess_self",- "ended_at": None,- "model_config": {"_delegate_from": "sess_self"},- },- },- )-- resolved = await runner._resolve_async_delegation_session(current, "sess_self")-- assert resolved is None- self._assert_no_route_change(runner)-- @pytest.mark.asyncio- async def test_overlong_delegate_chain_fails_closed_without_route_change(self):- from gateway.run_notifications import _MAX_DELEGATE_PROVENANCE_HOPS-- # One acyclic hop past the cap: the cycle guard cannot catch this, so- # only the hop bound stops the walk (#92620 review).- depth = _MAX_DELEGATE_PROVENANCE_HOPS + 2- rows = {- f"sess_{i}": {- "id": f"sess_{i}",- "ended_at": None,- "model_config": {"_delegate_from": f"sess_{i + 1}"},- }- for i in range(depth)- }- rows[f"sess_{depth}"] = {"id": f"sess_{depth}", "ended_at": None}- current = self._entry("sess_current")- runner = self._make_runner(rows)-- resolved = await runner._resolve_async_delegation_session(current, "sess_0")-- assert resolved is None- self._assert_no_route_change(runner)-- @pytest.mark.asyncio- async def test_delegate_chain_at_the_hop_limit_still_resolves(self):- from gateway.run_notifications import _MAX_DELEGATE_PROVENANCE_HOPS-- # Exactly at the bound: the cap must not reject a resolvable chain.- depth = _MAX_DELEGATE_PROVENANCE_HOPS- rows = {- f"sess_{i}": {- "id": f"sess_{i}",- "ended_at": None,- "model_config": {"_delegate_from": f"sess_{i + 1}"},- }- for i in range(depth)- }- rows[f"sess_{depth}"] = {"id": f"sess_{depth}", "ended_at": None}- current = self._entry(f"sess_{depth}")- runner = self._make_runner(rows)-- resolved = await runner._resolve_async_delegation_session(current, "sess_0")-- assert resolved is current- self._assert_no_route_change(runner)-- @pytest.mark.asyncio- async def test_delegate_with_missing_parent_fails_closed_without_route_change(self):- current = self._entry("sess_current")- runner = self._make_runner(- {- "sess_child": {- "id": "sess_child",- "ended_at": None,- "model_config": {"_delegate_from": "sess_missing"},- },- },- )-- resolved = await runner._resolve_async_delegation_session(current, "sess_child")-- assert resolved is None- self._assert_no_route_change(runner)-- @pytest.mark.asyncio- async def test_malformed_delegate_config_fails_closed_without_route_change(self):- current = self._entry("sess_current")- runner = self._make_runner(- {- "sess_child": {- "id": "sess_child",- "ended_at": None,- "model_config": "{not-json}",- },- },- )-- resolved = await runner._resolve_async_delegation_session(current, "sess_child")-- assert resolved is None- self._assert_no_route_change(runner)-@pytest.mark.asyncioasync def test_non_compression_ended_parent_drops(self):current = self._entry("sess_old")@@ -418,3 +251,143 @@ async def test_pending_pin_respects_concurrent_boundary(tmp_path, boundary):assert result is not None and result.session_id == expectedelse:assert result is None+[email protected]("delivery", ["single", "group"])[email protected]("case", [+ "single", "nested", "relabeled", "limit", "over_limit", "missing", "cycle",+ "malformed", "nonobject", "invalid_marker", "empty_marker", "null_marker",+ "markerless", "null_config", "absent_config", "generic_parent", "foreground",+ "current", "current_malformed", "child_to_current", "current_boundary",+ "parent_boundary", "child_ended", "child_boundary", "intermediate_boundary",+ "compression", "compression_foreign", "idle",+])+async def test_delegate_completion_preserves_real_route_ownership(tmp_path, case, delivery):+ """Real durable admission and route resolution agree before any destructive switch."""+ import json+ import sqlite3+ from types import SimpleNamespace+ from typing import Any, cast++ from gateway.platforms.base import BasePlatformAdapter+ from gateway.config import GatewayConfig, Platform+ from gateway.run import GatewayRunner, _profile_runtime_scope+ from gateway.session import SessionSource+ from tools import async_delegation as ad++ with _profile_runtime_scope(tmp_path):+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ store = runner.session_store+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="owner-chat", chat_type="dm")+ entry = store.get_or_create_session(source)+ db = store._db+ parent = entry.session_id+ previous = parent+ children = []+ for index in range({"nested": 2, "intermediate_boundary": 2, "limit": 16, "over_limit": 17}.get(case, 1)):+ child = f"worker-{index}"+ db.create_session(child, source="telegram" if case == "relabeled" else "subagent",+ parent_session_id=previous, model_config={"_delegate_from": previous})+ children.append(child)+ previous = child+ pinned = children[-1]+ configs = {+ "missing": {"_delegate_from": "missing-parent"}, "cycle": {"_delegate_from": pinned},+ "malformed": "{broken", "nonobject": [], "invalid_marker": {"_delegate_from": 7},+ "empty_marker": {"_delegate_from": ""}, "null_marker": {"_delegate_from": None},+ "markerless": {}, "null_config": "null", "absent_config": None,+ "generic_parent": {}, "current_malformed": "{broken",+ }+ if case in configs:+ config = configs[case]+ raw = config if config is None or isinstance(config, str) else json.dumps(config)+ with sqlite3.connect(db.db_path) as conn:+ conn.execute("UPDATE sessions SET model_config=? WHERE id=?", (raw, pinned))+ if case == "generic_parent":+ with sqlite3.connect(db.db_path) as conn:+ conn.execute("UPDATE sessions SET source='telegram' WHERE id=?", (pinned,))+ if case == "foreground":+ pinned = parent+ if case in {"current", "current_malformed", "current_boundary", "child_to_current"}:+ entry = store.switch_session(entry.session_key, pinned)+ assert entry is not None+ if case == "child_to_current":+ db.create_session("grandchild", source="subagent", model_config={"_delegate_from": pinned})+ children.append("grandchild")+ pinned = "grandchild"+ if case == "current_boundary":+ db.end_session(pinned, end_reason="session_reset")+ if case == "parent_boundary":+ db.end_session(parent, end_reason="session_reset")+ if case == "child_ended":+ db.end_session(pinned, end_reason="agent_close")+ if case == "child_boundary":+ db.end_session(pinned, end_reason="session_reset")+ if case == "intermediate_boundary":+ db.end_session(children[0], end_reason="session_reset")+ if case in {"child_boundary", "intermediate_boundary"}:+ # The live ancestor must not override a newer user-selected route.+ entry = store.get_or_create_session(source, force_new=True)+ children.append(entry.session_id)+ if case == "idle":+ db.end_session(parent, end_reason="idle")+ if case in {"compression", "compression_foreign"}:+ db.create_session("continuation", source="telegram", parent_session_id=parent)+ db.end_session(parent, end_reason="compression")+ children.append("continuation")+ if case == "compression_foreign":+ entry = store.get_or_create_session(source, force_new=True)+ children.append(entry.session_id)+ before = {sid: db.get_session(sid) for sid in [parent, *children]}+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None+ route_before = current.session_id+ rejected = case in {+ "over_limit", "missing", "cycle", "malformed", "nonobject", "invalid_marker",+ "empty_marker", "null_marker", "markerless", "null_config", "absent_config",+ "current_boundary", "parent_boundary", "child_boundary", "intermediate_boundary", "compression_foreign",+ }+ resolved = []++ async def accept(event):+ current = store.lookup_by_session_key(event.metadata["gateway_session_key"])+ assert current is not None+ result = await runner._resolve_async_delegation_session(current, event.metadata["gateway_session_id"])+ resolved.append(result.session_id if result else None)+ event._gateway_accepted = True++ runner.adapters[Platform.TELEGRAM] = cast(+ BasePlatformAdapter, SimpleNamespace(handle_message=accept),+ )+ events = []+ for index in range(2 if delivery == "group" else 1):+ event: dict[str, Any] = {"type": "async_delegation", "delegation_id": f"deleg-{index}",+ "session_key": entry.session_key, "parent_session_id": pinned,+ "dispatched_at": 1.0, "summary": "completed result", "status": "completed"}+ ad._persist_dispatch(event)+ ad._persist_completion(event, {"status": "completed", "summary": event["summary"]})+ events.append(event)+ if delivery == "group":+ await runner._deliver_async_delegation_group(events)+ else:+ await runner._deliver_completion_notification("completed result", events[0])+ # This detects the deterministic false ack: live child accepted, resolver+ # rejects its provenance, yet the durable row previously became delivered.+ for event in events:+ row = ad.get_durable_delegation(event["delegation_id"])+ assert row is not None+ assert row["delivery_state"] == ("dropped" if rejected else "delivered")+ expected = "continuation" if case == "compression" else pinned if case == "generic_parent" else route_before+ assert resolved == ([] if rejected else [expected])+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None+ result = await runner._resolve_async_delegation_session(current, pinned)+ assert (result.session_id if result else None) == (None if rejected else expected)+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None+ assert current.session_id == (route_before if rejected else expected)+ if case not in {"generic_parent", "compression"}:+ for sid, row in before.items():+ after = db.get_session(sid)+ for field in ("ended_at", "end_reason", "source", "session_key", "model_config"):+ assert after[field] == row[field], (case, sid, field)diff --git a/tests/gateway/test_background_process_notifications.py b/tests/gateway/test_background_process_notifications.pyindex 51f5f39d784..e918bf723cb 100644--- a/tests/gateway/test_background_process_notifications.py+++ b/tests/gateway/test_background_process_notifications.py@@ -825,3 +825,214 @@ async def test_raw_output_modes_are_human_facing(monkeypatch, tmp_path):assert "proc_deadbeef" not in text and "[Background process" not in text and "~" not in textassert "\x1b[" not in textassert "make -j8 all" in text++[email protected]("surface_a", [True, False])[email protected]("owner", ["child", "handoff", "foreground", "live_handoff"])[email protected]("path,mode", [+ ("agent", "all"), ("agent", "off"), ("raw", "all"),+ ("raw", "result"), ("raw", "error"), ("raw", "concise"), ("raw", "off"),+ ("watch_match", "all"), ("heartbeat", "all"), ("registry", "all"),+ ("async_delegation", "all"), ("async_delegation_work_closeout", "all"),+ ("batch_child_first", "all"), ("batch_foreground_first", "all"),+ ("batch_boundary_first", "all"), ("batch_boundary_last", "all"),+])+async def test_profile_scoped_child_noise_and_handoff_admission(+ monkeypatch, tmp_path, surface_a, owner, path, mode,+):+ """Recovered A→B→A consumers use real policy and live ownership, not the stale child pin."""+ from typing import cast++ from gateway.platforms.base import BasePlatformAdapter+ from gateway.run import _async_profile_runtime_scope, _profile_runtime_scope+ from hermes_cli.profiles import get_profile_dir+ from hermes_constants import get_hermes_home+ import hermes_state+ from tools import process_registry as pr_module+ from tools.process_registry import ProcessRegistry, ProcessSession++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_BASE_HOME", str(tmp_path))+ # The global fixture pins the default DB; restore call-time profile resolution+ # within these explicitly private homes instead of sharing its root handle.+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", hermes_state._IMPORT_DEFAULT_DB_PATH)+ import gateway.run as gw+ monkeypatch.setattr(gw, "_hermes_home", tmp_path)+ registry = ProcessRegistry()+ monkeypatch.setattr(pr_module, "process_registry", registry)+ runner = GatewayRunner(GatewayConfig(multiplex_profiles=True, sessions_dir=tmp_path / "sessions"))+ runner._completion_notification_batch_window = 0+ admitted = []+ handed_off = owner in {"handoff", "live_handoff"}+ homes = {}+ for name, surface in (("a", surface_a), ("b", not surface_a)):+ home = get_profile_dir(name)+ home.mkdir(parents=True)+ (home / "config.yaml").write_text(+ f"delegation:\n surface_child_process_notifications: {str(surface).lower()}\n"+ f"display:\n background_process_notifications: {mode}\n",+ )+ homes[name] = home++ async def accept(event):+ async with _async_profile_runtime_scope(homes[event.source.profile]):+ key = event.metadata["gateway_session_key"]+ entry = runner.session_store.lookup_by_session_key(key)+ assert entry is not None+ pinned = event.metadata.get("gateway_session_id")+ if pinned:+ entry = await runner._resolve_async_delegation_session(entry, pinned)+ assert entry is not None+ admitted.append((event, entry.session_id, get_hermes_home()))+ event._gateway_accepted = True++ adapter = SimpleNamespace(send=AsyncMock(), handle_message=accept)+ transport = cast(BasePlatformAdapter, adapter)+ runner.adapters[Platform.TELEGRAM] = transport+ runner._profile_adapters = {name: {Platform.TELEGRAM: transport} for name in homes}+ runner._profile_configs = {name: GatewayConfig() for name in homes}+ for leg, name in enumerate(("a", "b", "a")):+ async with _async_profile_runtime_scope(homes[name]):+ from gateway.session import SessionSource+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="123", chat_type="dm", profile=name)+ entry = runner.session_store.get_or_create_session(source, force_new=True)+ db = runner.session_store._db_for_key(entry.session_key)+ assert db is not None+ assert db.db_path == homes[name] / "state.db"+ assert db.get_session(entry.session_id) is not None+ child = f"worker-{name}-{leg}"+ db.create_session(child, source="subagent", model_config={"_delegate_from": entry.session_id})+ before = {sid: db.get_session(sid) for sid in (entry.session_id, child)}+ proc = ProcessSession(+ id=f"proc_{name}{leg}abcd", command="build", owner_task_id="parent-owner" if owner == "foreground" else "sa-child",+ task_id="container-parent", session_key=entry.session_key,+ parent_session_id=child, notify_on_complete=True, output_buffer="READY\n", started_at=1.0,+ )+ registry._running[proc.id] = proc+ watcher = {+ **_watcher_dict(proc.id), "session_key": entry.session_key, "chat_type": "dm",+ "parent_session_id": child, "owner_task_id": "sa-child",+ "notify_on_complete": path == "agent",+ }+ async with runner._completion_event_scope(watcher):+ assert get_hermes_home() == homes[name], runner._primary_profile_name+ assert await runner._session_db.get_session(child) is not None+ if owner == "handoff":+ assert registry.transfer_ownership(+ proc.id, from_owner="sa-child", to_owner="parent-owner", to_task_id="parent-owner",+ to_session_key=entry.session_key, note="finish build",+ ) is proc+ assert registry.running_owned_by("sa-child") == []+ assert registry.kill_all("sa-child") == 0+ surfaced = handed_off or owner == "foreground" or (surface_a if name == "a" else not surface_a)+ exempt = path in {"async_delegation", "async_delegation_work_closeout"}+ adapter.send.reset_mock()+ admitted.clear()+ ticks = 0++ async def tick(*args, **kwargs):+ nonlocal ticks+ ticks += 1+ assert ticks <= 10, (path, mode, name, proc.exited, proc.owner_task_id)+ # all-mode raw consumers see both running output and an exit.+ if owner == "live_handoff" and ticks == 2:+ assert registry.transfer_ownership(+ proc.id, from_owner="sa-child", to_owner="parent-owner", to_task_id="parent-owner",+ to_session_key=entry.session_key, note="finish build",+ ) is proc+ if ticks >= 2 or (path == "agent" and owner != "live_handoff"):++ proc.mark_exited(2)++ if path.startswith("batch_"):+ runner._completion_notification_batch_window = 0.01+ if owner == "live_handoff":+ assert registry.transfer_ownership(+ proc.id, from_owner="sa-child", to_owner="parent-owner", to_task_id="parent-owner",+ to_session_key=entry.session_key, note="finish build",+ ) is proc+ proc.output_buffer = "PROCESS_RESULT"+ evt = runner._build_process_completion_event(watcher, proc, proc.id)+ companion = {**evt, "session_id": f"companion-{name}-{leg}",+ "owner_task_id": "parent-owner", "output": "COMPANION_RESULT"}+ boundary = path in {"batch_boundary_first", "batch_boundary_last"}+ if boundary:+ async with _async_profile_runtime_scope(homes[name]):+ stale = f"stale-{name}-{leg}"+ db.create_session(stale, source="telegram")+ db.end_session(stale, end_reason="session_reset")+ companion["parent_session_id"] = stale+ pair = [("PROCESS_RESULT", evt), ("COMPANION_RESULT", companion)]+ if path in {"batch_foreground_first", "batch_boundary_first"}:+ pair.reverse()+ outcomes = await asyncio.gather(*(+ runner._enqueue_process_completion_notification(text, event)+ for text, event in pair+ ))+ assert outcomes[pair.index(("PROCESS_RESULT", evt))] is (True if surfaced else None)+ assert outcomes[pair.index(("COMPANION_RESULT", companion))] is (None if boundary else True)+ texts = "\n".join(event.text for event, _sid, _home in admitted)+ assert ("PROCESS_RESULT" in texts) is surfaced+ assert ("COMPANION_RESULT" in texts) is (not boundary)+ assert len(admitted) == (int(surfaced) if boundary else 1)+ elif path in {"agent", "raw"}:+ with monkeypatch.context() as clock:+ clock.setattr(asyncio, "sleep", tick)+ await runner._run_process_watcher(watcher)+ expected_admissions = int(surfaced and path == "agent")+ expected_sends = ((1 if owner == "live_handoff" and not (surface_a if name == "a" else not surface_a) else 2) if mode == "all" else int(mode != "off")) if surfaced and path == "raw" else 0+ assert len(admitted) == expected_admissions+ assert adapter.send.await_count == expected_sends+ else:+ if owner == "live_handoff":+ assert registry.transfer_ownership(+ proc.id, from_owner="sa-child", to_owner="parent-owner", to_task_id="parent-owner",+ to_session_key=entry.session_key, note="finish build",+ ) is proc+ evt = {+ **watcher, "type": path, "owner_task_id": proc.owner_task_id, "task_id": proc.task_id,+ "pattern": "READY", "command": "build", "output": "READY\n",+ "elapsed_seconds": 10, "heartbeat_seq": 1,+ }+ if path == "registry":+ evt["type"] = "completion"+ evt["exit_code"] = 0+ registry.completion_queue.put(evt)+ with _profile_runtime_scope(homes[name]):+ drained = registry.drain_notifications(session_key=entry.session_key)+ assert len(drained) == int(surfaced)+ elif exempt:+ # The admission seam must not treat real delegation/closeout results as process noise.+ evt.pop("parent_session_id")+ async with runner._completion_event_scope(evt):+ assert await runner._deliver_completion_notification_scoped("result", evt) is True+ assert len(admitted) == 1+ else:+ registry.completion_queue.put(evt)+ await runner._drain_watch_notifications(registry.completion_queue)+ assert len(admitted) == int(surfaced)+ assert registry.completion_queue.empty()+ for event, resolved_id, home in admitted:+ assert event.source.profile == name and home == homes[name]+ assert resolved_id == entry.session_id+ if path == "agent":+ assert event.metadata["gateway_session_id"] == child+ completion = runner._build_process_completion_event(watcher, proc, proc.id)+ assert completion["owner_task_id"] == proc.owner_task_id+ assert completion["parent_session_id"] == child+ assert proc.notify_on_complete is True+ if not proc.exited:+ proc.mark_exited(2)+ registry._running.pop(proc.id)+ registry._finished[proc.id] = proc+ assert registry.unread_completions_owned_by(proc.owner_task_id) == [proc]+ registry._finished.pop(proc.id)+ with _profile_runtime_scope(homes[name]):+ current = runner.session_store.lookup_by_session_key(entry.session_key)+ assert current is not None+ assert current.session_id == entry.session_id+ for sid, row in before.items():+ after = db.get_session(sid)+ for field in ("ended_at", "end_reason", "source", "session_key", "model_config"):+ assert after[field] == row[field], (path, name, sid, field)diff --git a/tools/process_registry.py b/tools/process_registry.pyindex 18bebfa30c2..851c73c5232 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -1873,6 +1873,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):requeue: list[dict] = []# delegation.surface_child_process_notifications, read at most once per drain# and only when an sa- event shows up.+ from tools.process_registry_notifications import is_child_process_notification, should_surface_notificationsurface_child: bool | None = Nonewhile not self.completion_queue.empty():try:@@ -1896,10 +1897,10 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):# drain, so a requeue would pin the event forever. 'async_delegation'# is the result itself and is NEVER suppressed._evt_task_id = str(evt.get("owner_task_id") or evt.get("task_id") or "")- if not is_async_delegation and _evt_task_id.startswith("sa-"):+ if is_child_process_notification(evt):if surface_child is None:surface_child = self._surface_child_process_notifications()- if not surface_child:+ if not should_surface_notification(evt, surface_child=surface_child):logger.debug("Suppressed subagent-owned process notification ""(delegation.surface_child_process_notifications=false): "diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.pyindex 9bc316e70d1..757febc1ce9 100644--- a/tools/process_registry_notifications.py+++ b/tools/process_registry_notifications.py@@ -52,6 +52,23 @@ def group_process_notifications(notifications):+def is_child_process_notification(evt: dict) -> bool:+ """Raw child process noise, not a delegation or work-closeout deliverable."""+ if evt.get("type") in {"async_delegation", "async_delegation_work_closeout"}:+ return False+ return str(evt.get("owner_task_id") or evt.get("task_id") or "").startswith("sa-")+++def should_surface_notification(evt: dict, *, surface_child: bool | None = None) -> bool:+ """Shared policy; callers must first enter the event's owning profile scope."""+ if not is_child_process_notification(evt):+ return True+ if surface_child is None:+ from tools.process_registry import ProcessRegistry+ surface_child = ProcessRegistry._surface_child_process_notifications()+ return surface_child++def _format_age(seconds: float) -> str:"""Human-friendly elapsed string ('18m', '2h3m', '45s')."""try: