Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Let agents name room groups by path and refuse duplicate sibling names (#992)
Abel Dantas7d4a0a2fda72
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 097a82bc1..9f901ea4d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -63,6 +63,20 @@ version of their own to them without also giving them a release of their own.follow-up can, while other agents' chatter still does not. The chart liststhe flag and, while it is on, sets `FOLLOW_THE_CONVERSATION_WINDOW_SECONDS`from `switchCore.followTheConversation.windowSeconds` (default 300).+- **Agents name room groups by path.** `create_room` and `create_room_group`+ take a group as a path such as `Fraud/Incidents` (the top-level group, then+ each child), so two groups called `Incidents` under different parents no+ longer break every agent request that names one. A bare name still works+ when only one group has it; when several do, the error lists each match by+ its path so the agent can retry with the right one, and an unknown path+ names the first part that was not found. A group id is accepted too.+- **Room group names are unique among siblings.** Creating, renaming or moving+ a group next to one with the same name (ignoring case) is refused with an+ error naming the existing group, from the dashboard, the API and agents+ alike. The same name under different parents is still fine. Deleting a+ group whose subgroup would move up next to a namesake is refused too, and+ the dashboard now shows why. Names can no longer contain `/` or be blank.+ Existing duplicates are left as they are and can be reached by id.#### Fixed- **A request card posted in a thread now mentions the person who can answerdiff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex 3db588e31..a6de5b001 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -683,9 +683,21 @@ groups nest under a parent to form a tree.- **`get_room_group_detail`** — one group, the rooms directly in it(`member_rooms`), and its immediate `child_groups`.- **`create_room_group`** — provision a group. Required: `name`. Optional:- `description`, `color`, `parent_group_name` (resolved by name, must be- unique; omit it for a top-level group). Creating a group does not move any rooms into it — file rooms under- it later by passing `group_name` to `create_room`.+ `description`, `color`, `parent_group_name` (omit it for a top-level+ group). Creating a group does not move any rooms into it; file rooms under+ it later by passing `group_name` to `create_room`. Missing parents are not+ created for you: create each level first.++Name a group by its **path**: the top-level group, then each child, separated+by `/`, e.g. `Fraud/Incidents`. The `path` that `list_room_groups` returns+(`Fraud / Incidents`) works as it is. A bare name is fine when only one group+has it; when several do, the error lists each one's path, so retry with the+one the user means (ask if it is not clear). A group id also works. This holds+for `group_name` on `create_room` and `parent_group_name` on+`create_room_group`. Names are unique among siblings, ignoring case, and+cannot contain `/`: creating `Incidents` where one already exists under the+same parent is refused, while `Payments/Incidents` and `Fraud/Incidents` can+both exist.### Per-room agent aliasesdiff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 0fcd75474..1fc69c033 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -946,10 +946,13 @@ async def create_room(write_visibility: "public" (anyone may modify — invite, attach, edit)or "private" (owner/admin only). Defaults to "public". Must not be"public" while read_visibility is "private".- group_name: Optional name of an existing room group to file this room- under (a navigation/visualization layer surfaced in the room list- and graph). Must match an existing group exactly; errors if unknown- or ambiguous. Omit to leave the room standalone.+ group_name: Optional existing room group to file this room under (a+ navigation/visualization layer surfaced in the room list and+ graph). Give its path from the top level, e.g. "Fraud/Incidents",+ or a bare name when that name is unique; a group id also works.+ Names match exactly. An ambiguous bare name errors with the path+ of each match to retry with; an unknown path errors naming the+ first segment not found. Omit to leave the room standalone.roles: Optional room-roles to define at creation. Each entry is`{"name": "...", "instructions": "...", "exclusive": bool}`.Roles are assumable instruction bundles agents pick up with@@ -1481,14 +1484,17 @@ async def list_room_groups() -> list[dict[str, Any]]:Room groups are a navigation/organization layer: a room can belong to agroup (or be standalone), and groups can nest under a parent group. Use- this to discover the group names you can pass as `group_name` to- `create_room`, or to understand how rooms are organized.+ this to discover the groups you can pass as `group_name` to+ `create_room`, or to understand how rooms are organized. Group names are+ unique among siblings but may repeat under different parents, so name a+ group by its path.Returns:List of {id, name, description, parent_group_id, room_count, path}dicts, where `path` is the group's root-first ancestry (e.g.- "Parent / Child") and `room_count` is the number of rooms directly in- the group. Sorted by path.+ "Parent / Child", which can be passed as a group path as it is) and+ `room_count` is the number of rooms directly in the group. Sorted by+ path."""agent_id = get_agent_id()protocol = get_protocol()@@ -1506,15 +1512,20 @@ async def create_room_group(A room group is a named bucket that rooms can be filed under (via`create_room`'s `group_name`), and groups can nest under a parent group to- form a tree. Creating a group does not move any rooms into it.+ form a tree. Creating a group does not move any rooms into it, and does+ not create missing parents: create each level first.Args:- name: The group's display name.+ name: The group's display name. It cannot contain "/" (the path+ separator), and must differ from every group already under the+ same parent (or at the top level), ignoring case; the same name+ under a different parent is fine.description: Optional free-text description.color: Optional UI colour hint (e.g. a hex string).- parent_group_name: Optional name of an existing group to nest this one- under. Must match an existing group exactly; errors if unknown or- ambiguous. Omit to create a top-level group.+ parent_group_name: Optional existing group to nest this one under,+ given as a path such as "Fraud/Incidents", a bare name that is+ unique, or a group id. Resolved like `create_room`'s+ `group_name`. Omit to create a top-level group.Returns:{id, name, description, color, parent_group_id, room_count, path,diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 83ed09c57..875032961 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -2960,8 +2960,9 @@ class AgentCore:into that room's run (see `agent_runs`), and is refused if the run ispaused or stopped or the agent is already creating a room.- `group_name`, when given, files the room under an existing room group;- it is resolved to a group id here (agents work in names, not ids)."""+ `group_name`, when given, files the room under an existing room group.+ It may be a path, a bare name or an id, and is resolved to a group id+ here (see `_resolve_group_name`)."""from switch_core.room_service import (LinkedRoomSpec,RoleSpec,@@ -3032,24 +3033,15 @@ class AgentCore:async def _resolve_group_name(self, session: AsyncSession, group_name: str | None) -> str | None:- """Resolve a room-group name to its id. Returns None for no group.+ """Resolve what an agent passed as a group (a path such as+ "Fraud/Incidents", a bare name, or an id) to its id. Returns None for+ no group.- Raises ValueError if the name is unknown or ambiguous (group names are- not unique across the tree)."""+ Raises ValueError if it is unknown or ambiguous; an ambiguous bare name+ lists each match by path (see `RoomGroupStore.resolve`)."""if group_name is None:return None- result = await session.execute(- select(RoomGroup).where(RoomGroup.name == group_name)- )- matches = result.scalars().all()- if not matches:- raise ValueError(f"No room group named '{group_name}'")- if len(matches) > 1:- raise ValueError(- f"Multiple room groups named '{group_name}'; ask the user which "- "one to use"- )- return matches[0].id+ return await self.room_group_store.resolve(session, group_name)async def _group_labels(self, session: AsyncSession, group_id: str | None@@ -3861,9 +3853,10 @@ class AgentCore:parent_group_name: str | None,) -> dict[str, Any]:"""Create a room group, optionally nested under an existing parent- (resolved by name). Returns the new group's detail dict.+ (a path, bare name or id). Returns the new group's detail dict.- Raises ValueError if `parent_group_name` is unknown or ambiguous.+ Raises ValueError if `parent_group_name` is unknown or ambiguous, or if+ the parent already has a group with this name."""async with self.session_factory() as session:parent_group_id = await self._resolve_group_name(session, parent_group_name)diff --git a/core/switch_core/db/stores/room_group_store.py b/core/switch_core/db/stores/room_group_store.pyindex ad4ad56d7..d77117cb2 100644--- a/core/switch_core/db/stores/room_group_store.py+++ b/core/switch_core/db/stores/room_group_store.py@@ -1,7 +1,178 @@-from sqlalchemy import func, select, update+from collections.abc import Sequence+from typing import Protocol++from sqlalchemy import func, select, text, updatefrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.db.models import Room, RoomGroup+from switch_core.db.models import Room, RoomGroup, require_tenant_id++# Separates the groups in a path such as "Fraud/Incidents": the top-level group+# first, then each child by name. Group names may not contain it, so a path+# always means one thing.+GROUP_PATH_SEPARATOR = "/"+++class RoomGroupNameTaken(ValueError):+ """A group with the same name already sits under the same parent (or at+ the top level). Sibling names are unique so that a path names one group."""+++class _GroupNode(Protocol):+ @property+ def id(self) -> str: ...+ @property+ def name(self) -> str: ...+ @property+ def parent_group_id(self) -> str | None: ...+++def _same_name(a: str, b: str) -> bool:+ return a.strip().casefold() == b.strip().casefold()+++def group_path(group: _GroupNode, by_id: dict[str, _GroupNode]) -> str:+ """The group's root-first path, e.g. "Fraud/Incidents"."""+ names: list[str] = []+ cursor: _GroupNode | None = group+ seen: set[str] = set()+ while cursor is not None and cursor.id not in seen:+ seen.add(cursor.id)+ names.append(cursor.name)+ parent_id = cursor.parent_group_id+ cursor = by_id.get(parent_id) if parent_id is not None else None+ return GROUP_PATH_SEPARATOR.join(reversed(names))+++def _or_list(items: Sequence[str]) -> str:+ if len(items) == 1:+ return items[0]+ return f"{', '.join(items[:-1])} or {items[-1]}"+++def resolve_group_reference(groups: Sequence[_GroupNode], reference: str) -> str:+ """Resolve a group id, a bare group name, or a path to a group id.++ A path ("Fraud/Incidents") starts at a top-level group and names each child+ in turn; whitespace around each segment is ignored, so the displayed+ "Fraud / Incidents" form works too. A bare name must be unique in the+ tenant; when it is not, the error lists each match by its path, or by+ its id where the path cannot single it out, so the caller can retry with+ one. A path through an ambiguous ancestor is refused the same way, with+ the ids of the groups it could mean. Names match exactly (case-sensitive).++ Raises ValueError when nothing matches or the reference is ambiguous.+ """+ by_id: dict[str, _GroupNode] = {g.id: g for g in groups}+ if reference in by_id:+ return reference+ segments = [s.strip() for s in reference.split(GROUP_PATH_SEPARATOR)]+ if any(not s for s in segments):+ raise ValueError(+ f"Room group path '{reference}' has an empty segment; write a path "+ "as 'Parent/Child'"+ )++ if len(segments) == 1:+ matches = [g for g in groups if g.name.strip() == segments[0]]+ if not matches:+ raise ValueError(f"No room group named '{reference}'")+ if len(matches) > 1:+ raise ValueError(+ f"Ambiguous room group '{reference}': use "+ f"{_or_list(_ways_to_name(matches, by_id))}"+ )+ return matches[0].id++ # Every group the path so far could mean: one, unless a legacy duplicate+ # on the way has made an ancestor ambiguous.+ candidates: list[_GroupNode] = []+ ambiguous_ancestor: str | None = None+ for i, segment in enumerate(segments):+ parent_ids: set[str | None] = {g.id for g in candidates} if i else {None}+ children = [+ g+ for g in groups+ if g.parent_group_id in parent_ids and g.name.strip() == segment+ ]+ if not i:+ where = "at the top level"+ elif len(candidates) == 1:+ where = f"under '{group_path(candidates[0], by_id)}'"+ else:+ where = (+ f"under any of the {len(candidates)} groups at "+ f"'{group_path(candidates[0], by_id)}'"+ )+ if not children:+ raise ValueError(+ f"No room group '{reference}': there is no group named "+ f"'{segment}' {where}"+ )+ if len(children) > 1 and i < len(segments) - 1 and ambiguous_ancestor is None:+ ambiguous_ancestor = (+ f"{len(children)} groups are named '{segment}' {where}, so the "+ "path does not single out one group"+ )+ candidates = children++ if ambiguous_ancestor is not None:+ ways = _or_list([f"'{group_path(g, by_id)}' (id '{g.id}')" for g in candidates])+ which = "its id" if len(candidates) == 1 else "the id of the one you mean"+ raise ValueError(+ f"Ambiguous room group '{reference}': {ambiguous_ancestor}; pass "+ f"{which} instead: {ways}"+ )+ if len(candidates) > 1:+ ids = _or_list([f"'{g.id}'" for g in candidates])+ raise ValueError(+ f"Ambiguous room group '{reference}': {len(candidates)} groups are "+ f"named '{segments[-1]}' {where}; pass one of their ids instead: {ids}"+ )+ return candidates[0].id+++def _ways_to_name(+ matches: Sequence[_GroupNode], by_id: dict[str, _GroupNode]+) -> list[str]:+ """How to name each of several same-named groups: its path, or its id+ where the path cannot single it out (a sibling with the same name, or a+ name on the way that contains the separator, both left from before sibling+ names were unique). A top-level match is named by its id: its path is the+ bare name that was ambiguous in the first place."""+ paths = {g.id: group_path(g, by_id) for g in matches}+ out: list[str] = []+ for g in sorted(matches, key=lambda m: (paths[m.id] == m.name, paths[m.id])):+ path = paths[g.id]+ shared = sum(1 for p in paths.values() if p == path) > 1+ if path == g.name:+ out.append(f"id '{g.id}' for the top-level '{path}'")+ elif shared or _has_separator_on_path(g, by_id):+ out.append(f"'{path}' (id '{g.id}')")+ else:+ out.append(f"'{path}'")+ return out+++def _has_separator_on_path(group: _GroupNode, by_id: dict[str, _GroupNode]) -> bool:+ cursor: _GroupNode | None = group+ seen: set[str] = set()+ while cursor is not None and cursor.id not in seen:+ seen.add(cursor.id)+ if GROUP_PATH_SEPARATOR in cursor.name:+ return True+ parent_id = cursor.parent_group_id+ cursor = by_id.get(parent_id) if parent_id is not None else None+ return False+++def _check_new_name(name: str) -> None:+ if not name.strip():+ raise ValueError("A room group name cannot be empty")+ if GROUP_PATH_SEPARATOR in name:+ raise ValueError(+ f"A room group name cannot contain '{GROUP_PATH_SEPARATOR}': it "+ "separates the groups in a path such as 'Fraud/Incidents'"+ )class RoomGroupStore:@@ -13,6 +184,13 @@ class RoomGroupStore:promote-on-delete: deleting a group reparents its children to the deletedgroup's parent (member rooms become standalone via the `ON DELETE SET NULL`foreign key on `rooms.group_id`).++ It also keeps sibling names unique (case-insensitively, ignoring outer+ whitespace) and refuses names containing the path separator, so a path+ such as "Fraud/Incidents" names exactly one group. Both are checked here+ rather than by a database constraint, because tenants may already hold+ sibling duplicates from before the rule; those keep working and are+ reached by id."""async def create(@@ -24,10 +202,14 @@ class RoomGroupStore:color: str | None,parent_group_id: str | None,) -> RoomGroup:+ _check_new_name(name)if parent_group_id is not None:parent = await session.get(RoomGroup, parent_group_id)if parent is None:raise ValueError(f"Parent group not found: {parent_group_id}")+ await self._refuse_sibling_named(+ session, name, parent_group_id, moving_group_id=None+ )group = RoomGroup(name=name,description=description,@@ -45,6 +227,12 @@ class RoomGroupStore:result = await session.execute(select(RoomGroup).order_by(RoomGroup.created_at))return list(result.scalars().all())+ async def resolve(self, session: AsyncSession, reference: str) -> str:+ """Resolve a group id, bare name or path to a group id (see+ `resolve_group_reference`). Raises ValueError when unknown or+ ambiguous."""+ return resolve_group_reference(await self.get_all(session), reference)+async def update_fields(self,session: AsyncSession,@@ -63,9 +251,27 @@ class RoomGroupStore:reparent=True`) from "leave the parent unchanged" (`reparent=False`).Reparenting validates that the new parent does not create a cycle."""- group = await session.get(RoomGroup, group_id)+ # Lock before reading the group: a rename or reparent committed while+ # we wait would otherwise leave us checking sibling names under a+ # parent, or against a name, the group no longer has.+ await self._lock_names(session)+ group = await session.get(RoomGroup, group_id, populate_existing=True)if group is None:raise ValueError(f"Room group not found: {group_id}")+ renamed = name is not None and name != group.name+ if renamed:+ assert name is not None+ _check_new_name(name)+ if reparent:+ await self._validate_reparent(session, group_id, parent_group_id)+ new_parent = parent_group_id if reparent else group.parent_group_id+ if renamed or new_parent != group.parent_group_id:+ await self._refuse_sibling_named(+ session,+ name if name is not None else group.name,+ new_parent,+ moving_group_id=group_id,+ )if name is not None:group.name = nameif description is not None:@@ -73,7 +279,6 @@ class RoomGroupStore:if color is not None:group.color = colorif reparent:- await self._validate_reparent(session, group_id, parent_group_id)group.parent_group_id = parent_group_idawait session.flush()return group@@ -83,10 +288,17 @@ class RoomGroupStore:Member rooms become standalone automatically (`rooms.group_id` is`ON DELETE SET NULL`). Returns False if the group does not exist.+ Raises `RoomGroupNameTaken` when a child would land next to a group+ with its name."""- group = await session.get(RoomGroup, group_id)+ # Lock before reading the group: a rename or reparent committed while+ # we wait would otherwise leave us promoting children under a parent+ # the group no longer has.+ await self._lock_names(session)+ group = await session.get(RoomGroup, group_id, populate_existing=True)if group is None:return False+ await self._refuse_promotion_clash(session, group)# Promote direct children to this group's parent before deleting, so the# FK's SET NULL behaviour (which would orphan them to top-level) is# superseded by the parent we choose here.@@ -99,6 +311,85 @@ class RoomGroupStore:await session.flush()return True+ async def _lock_names(self, session: AsyncSession) -> None:+ """Serialise the tenant's group-name changes until the transaction+ ends, so two concurrent creates cannot both see a free name."""+ await session.execute(+ text("SELECT pg_advisory_xact_lock(hashtext(:key))"),+ {"key": f"room-group-names:{require_tenant_id()}"},+ )++ async def _siblings(+ self, session: AsyncSession, parent_group_id: str | None+ ) -> list[RoomGroup]:+ parent_clause = (+ RoomGroup.parent_group_id.is_(None)+ if parent_group_id is None+ else RoomGroup.parent_group_id == parent_group_id+ )+ # Names as committed, not as this session last loaded them: another+ # session may have renamed a sibling before we took the lock.+ result = await session.execute(+ select(RoomGroup)+ .where(parent_clause)+ .execution_options(populate_existing=True)+ )+ return list(result.scalars().all())++ async def _where(self, session: AsyncSession, parent_group_id: str | None) -> str:+ if parent_group_id is None:+ return "at the top level"+ by_id: dict[str, _GroupNode] = {g.id: g for g in await self.get_all(session)}+ parent = by_id.get(parent_group_id)+ if parent is None:+ return f"under group {parent_group_id}"+ return f"under '{group_path(parent, by_id)}'"++ async def _refuse_sibling_named(+ self,+ session: AsyncSession,+ name: str,+ parent_group_id: str | None,+ *,+ moving_group_id: str | None,+ ) -> None:+ """Raise `RoomGroupNameTaken` if a group other than `moving_group_id`+ already has `name` under `parent_group_id`."""+ await self._lock_names(session)+ for sibling in await self._siblings(session, parent_group_id):+ if sibling.id != moving_group_id and _same_name(sibling.name, name):+ raise RoomGroupNameTaken(+ f"A room group named '{sibling.name}' already exists "+ f"{await self._where(session, parent_group_id)}"+ )++ async def _refuse_promotion_clash(+ self, session: AsyncSession, group: RoomGroup+ ) -> None:+ await self._lock_names(session)+ children = await self._siblings(session, group.id)+ if not children:+ return+ staying = [+ g+ for g in await self._siblings(session, group.parent_group_id)+ if g.id != group.id+ ]+ for child in children:+ for other in staying:+ if _same_name(child.name, other.name):+ where = (+ "to the top level"+ if group.parent_group_id is None+ else await self._where(session, group.parent_group_id)+ )+ raise RoomGroupNameTaken(+ f"Cannot delete room group '{group.name}': its subgroup "+ f"'{child.name}' would move {where}, where a group named "+ f"'{other.name}' already exists. Rename or move one of "+ "them first"+ )+async def _validate_reparent(self, session: AsyncSession, group_id: str, parent_group_id: str | None) -> None:@@ -106,7 +397,9 @@ class RoomGroupStore:returnif parent_group_id == group_id:raise ValueError("A group cannot be its own parent")- parent = await session.get(RoomGroup, parent_group_id)+ # Read fresh, under the lock `update_fields` holds: a move another+ # session committed must count, or two crossing moves make a cycle.+ parent = await session.get(RoomGroup, parent_group_id, populate_existing=True)if parent is None:raise ValueError(f"Parent group not found: {parent_group_id}")# Walk up from the proposed parent; if we reach `group_id`, the new@@ -121,7 +414,7 @@ class RoomGroupStore:if cursor in seen:breakseen.add(cursor)- ancestor = await session.get(RoomGroup, cursor)+ ancestor = await session.get(RoomGroup, cursor, populate_existing=True)cursor = ancestor.parent_group_id if ancestor else Noneasync def get_room_counts(self, session: AsyncSession) -> dict[str, int]:diff --git a/core/switch_core/gateway/room_groups.py b/core/switch_core/gateway/room_groups.pyindex 88b49c0d8..e7cb8d405 100644--- a/core/switch_core/gateway/room_groups.py+++ b/core/switch_core/gateway/room_groups.py@@ -7,7 +7,10 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.authz import Principal, requirefrom switch_core.db.models import RoomGroup, User-from switch_core.db.stores.room_group_store import RoomGroupStore+from switch_core.db.stores.room_group_store import (+ RoomGroupNameTaken,+ RoomGroupStore,+)from switch_core.db.stores.room_store import RoomStorefrom switch_core.gateway.auth import get_current_user, get_tenant_is_adminfrom switch_core.gateway.dependencies import (@@ -67,6 +70,8 @@ async def create_room_group(color=req.color,parent_group_id=req.parent_group_id,)+ except RoomGroupNameTaken as e:+ raise HTTPException(status_code=409, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=400, detail=str(e)) from eawait session.commit()@@ -99,6 +104,8 @@ async def patch_room_group(parent_group_id=req.parent_group_id,reparent=reparent,)+ except RoomGroupNameTaken as e:+ raise HTTPException(status_code=409, detail=str(e)) from eexcept ValueError as e:# "not found" → 404; cycle/validation → 400.if "not found" in str(e).lower():@@ -167,7 +174,10 @@ async def delete_room_group(# what makes that stay true if the order ever changes.age = age_days(group.created_at) if group else UNKNOWN_AGE- removed = await room_group_store.delete(session, group_id)+ try:+ removed = await room_group_store.delete(session, group_id)+ except RoomGroupNameTaken as e:+ raise HTTPException(status_code=409, detail=str(e)) from eif not removed:raise HTTPException(status_code=404, detail="Room group not found")await session.commit()diff --git a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.pyindex 5db2fdef1..116a0aa5b 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py@@ -10,10 +10,12 @@ from switch_core.db.stores.room_store import RoomStoredef _bare_service() -> AgentCore:- # These methods only touch the passed-in session / session_factory, so we- # can exercise them on an un-__init__'d instance (matching the fake-based- # protocol tests).- return object.__new__(AgentCore)+ # These methods only touch the passed-in session / session_factory and the+ # group store, so we can exercise them on an un-__init__'d instance+ # (matching the fake-based protocol tests).+ svc = object.__new__(AgentCore)+ svc.room_group_store = RoomGroupStore() # type: ignore[attr-defined]+ return svcclass TestResolveGroupName:@@ -44,7 +46,7 @@ class TestResolveGroupName:with pytest.raises(ValueError, match="No room group named"):await svc._resolve_group_name(session, "Nope")- async def test_ambiguous_name_raises(+ async def test_ambiguous_name_lists_paths_and_path_resolves(self, session_factory: async_sessionmaker[AsyncSession]) -> None:svc = _bare_service()@@ -54,15 +56,34 @@ class TestResolveGroupName:session, name="Root", description=None, color=None, parent_group_id=None)# Two distinct groups can share a name (one nested under the other).- await store.create(+ top = await store.create(session, name="Dup", description=None, color=None, parent_group_id=None)- await store.create(+ nested = await store.create(session, name="Dup", description=None, color=None, parent_group_id=a.id)await session.commit()- with pytest.raises(ValueError, match="Multiple room groups named"):+ with pytest.raises(ValueError) as e:await svc._resolve_group_name(session, "Dup")+ assert str(e.value) == (+ "Ambiguous room group 'Dup': use 'Root/Dup' or id "+ f"'{top.id}' for the top-level 'Dup'"+ )+ assert await svc._resolve_group_name(session, "Root/Dup") == nested.id+ assert await svc._resolve_group_name(session, top.id) == top.id++ async def test_unknown_path_names_the_missing_segment(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _bare_service()+ store = RoomGroupStore()+ async with session_factory() as session:+ await store.create(+ session, name="Root", description=None, color=None, parent_group_id=None+ )+ await session.commit()+ with pytest.raises(ValueError, match="no group named 'Nope' under 'Root'"):+ await svc._resolve_group_name(session, "Root/Nope")class TestListRoomGroups:diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.pyindex b2b837ec8..f16304919 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py@@ -6,7 +6,10 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.db.models import Room-from switch_core.db.stores.room_group_store import RoomGroupStore+from switch_core.db.stores.room_group_store import (+ RoomGroupNameTaken,+ RoomGroupStore,+)from switch_core.db.stores.room_store import RoomStore@@ -60,6 +63,37 @@ class TestCreateRoomGroup:with pytest.raises(ValueError, match="No room group named"):await svc.create_room_group("agent-x", "C", None, None, "Nope")+ async def test_creates_under_a_parent_given_by_path(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _service(session_factory)+ for top in ("Payments", "Fraud"):+ await svc.create_room_group("agent-x", top, None, None, None)+ await svc.create_room_group("agent-x", "Incidents", None, None, top)+ fraud_incidents = await svc.create_room_group(+ "agent-x", "Triage", None, None, "Fraud/Incidents"+ )+ assert fraud_incidents["path"] == "Fraud / Incidents / Triage"++ with pytest.raises(ValueError) as e:+ await svc.create_room_group("agent-x", "Triage", None, None, "Incidents")+ assert str(e.value) == (+ "Ambiguous room group 'Incidents': use 'Fraud/Incidents' or "+ "'Payments/Incidents'"+ )++ async def test_refuses_a_sibling_with_the_same_name(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _service(session_factory)+ await svc.create_room_group("agent-x", "Fraud", None, None, None)+ await svc.create_room_group("agent-x", "Incidents", None, None, "Fraud")+ with pytest.raises(RoomGroupNameTaken) as e:+ await svc.create_room_group("agent-x", "incidents", None, None, "Fraud")+ assert str(e.value) == (+ "A room group named 'Incidents' already exists under 'Fraud'"+ )+class TestGetRoomGroupDetail:async def test_returns_members_and_children(diff --git a/core/tests/switch_core/db/stores/test_room_group_paths.py b/core/tests/switch_core/db/stores/test_room_group_paths.pynew file mode 100644index 000000000..4ff12587b--- /dev/null+++ b/core/tests/switch_core/db/stores/test_room_group_paths.py@@ -0,0 +1,179 @@+"""How an agent's group reference (a path, a bare name or an id) resolves.++Pure: the resolver works on the tenant's groups as already loaded, so these+need no database. The store tests cover the sibling-name rule that keeps paths+unambiguous going forward.+"""++from __future__ import annotations++from dataclasses import dataclass++import pytest++from switch_core.db.stores.room_group_store import (+ group_path,+ resolve_group_reference,+)+++@dataclass(frozen=True)+class G:+ id: str+ name: str+ parent_group_id: str | None+++# Payments+# ├── Incidents+# └── Releases+# Fraud+# ├── Incidents+# └── Releases+# Eng+TREE = [+ G("pay", "Payments", None),+ G("pay-inc", "Incidents", "pay"),+ G("pay-rel", "Releases", "pay"),+ G("fraud", "Fraud", None),+ G("fraud-inc", "Incidents", "fraud"),+ G("fraud-rel", "Releases", "fraud"),+ G("eng", "Eng", None),+]+++class TestResolveGroupReference:+ def test_unique_bare_name(self) -> None:+ assert resolve_group_reference(TREE, "Eng") == "eng"+ assert resolve_group_reference(TREE, "Fraud") == "fraud"++ def test_path_picks_the_child_under_that_parent(self) -> None:+ assert resolve_group_reference(TREE, "Fraud/Incidents") == "fraud-inc"+ assert resolve_group_reference(TREE, "Payments/Incidents") == "pay-inc"++ def test_displayed_path_with_spaces_works(self) -> None:+ assert resolve_group_reference(TREE, "Fraud / Releases") == "fraud-rel"++ def test_id_works(self) -> None:+ assert resolve_group_reference(TREE, "fraud-inc") == "fraud-inc"++ def test_ambiguous_bare_name_lists_each_path(self) -> None:+ with pytest.raises(ValueError) as e:+ resolve_group_reference(TREE, "Incidents")+ assert str(e.value) == (+ "Ambiguous room group 'Incidents': use 'Fraud/Incidents' or "+ "'Payments/Incidents'"+ )++ def test_unknown_bare_name(self) -> None:+ with pytest.raises(ValueError, match="No room group named 'Nope'"):+ resolve_group_reference(TREE, "Nope")++ def test_unknown_first_segment_is_named(self) -> None:+ with pytest.raises(ValueError) as e:+ resolve_group_reference(TREE, "Billing/Incidents")+ assert str(e.value) == (+ "No room group 'Billing/Incidents': there is no group named "+ "'Billing' at the top level"+ )++ def test_unknown_later_segment_is_named_with_its_parent(self) -> None:+ with pytest.raises(ValueError) as e:+ resolve_group_reference(TREE, "Fraud/Outages")+ assert str(e.value) == (+ "No room group 'Fraud/Outages': there is no group named 'Outages' "+ "under 'Fraud'"+ )++ def test_path_must_start_at_the_top_level(self) -> None:+ with pytest.raises(ValueError, match="no group named 'Incidents' at the top"):+ resolve_group_reference(TREE, "Incidents/Anything")++ def test_names_match_exactly(self) -> None:+ with pytest.raises(ValueError, match="No room group named 'ENG'"):+ resolve_group_reference(TREE, "ENG")++ def test_empty_segment_is_refused(self) -> None:+ with pytest.raises(ValueError, match="empty segment"):+ resolve_group_reference(TREE, "Fraud//Incidents")++ def test_legacy_sibling_duplicates_point_at_ids(self) -> None:+ groups = [+ G("top", "Ops", None),+ G("a", "Dup", "top"),+ G("b", "Dup", "top"),+ ]+ with pytest.raises(ValueError) as e:+ resolve_group_reference(groups, "Dup")+ assert str(e.value) == (+ "Ambiguous room group 'Dup': use 'Ops/Dup' (id 'a') or 'Ops/Dup' (id 'b')"+ )+ with pytest.raises(ValueError, match="pass one of their ids instead"):+ resolve_group_reference(groups, "Ops/Dup")+ assert resolve_group_reference(groups, "b") == "b"++ def test_ambiguous_ancestor_names_the_final_groups_by_id(self) -> None:+ # The ids of the two "Ops" groups would file the room under Ops, not+ # Incidents, so the error offers the Incidents groups instead.+ groups = [+ G("ops-1", "Ops", None),+ G("ops-2", "Ops", None),+ G("inc-1", "Incidents", "ops-1"),+ G("inc-2", "Incidents", "ops-2"),+ ]+ with pytest.raises(ValueError) as e:+ resolve_group_reference(groups, "Ops/Incidents")+ assert str(e.value) == (+ "Ambiguous room group 'Ops/Incidents': 2 groups are named 'Ops' at "+ "the top level, so the path does not single out one group; pass the "+ "id of the one you mean instead: 'Ops/Incidents' (id 'inc-1') or "+ "'Ops/Incidents' (id 'inc-2')"+ )++ def test_ambiguous_ancestor_with_one_final_group_offers_its_id(self) -> None:+ groups = [+ G("ops-1", "Ops", None),+ G("ops-2", "Ops", None),+ G("inc-2", "Incidents", "ops-2"),+ ]+ with pytest.raises(ValueError) as e:+ resolve_group_reference(groups, "Ops/Incidents")+ assert str(e.value).endswith(+ "pass its id instead: 'Ops/Incidents' (id 'inc-2')"+ )++ def test_ambiguous_ancestor_without_the_final_group(self) -> None:+ groups = [G("ops-1", "Ops", None), G("ops-2", "Ops", None)]+ with pytest.raises(ValueError) as e:+ resolve_group_reference(groups, "Ops/Incidents")+ assert str(e.value) == (+ "No room group 'Ops/Incidents': there is no group named 'Incidents' "+ "under any of the 2 groups at 'Ops'"+ )++ def test_a_top_level_match_is_offered_by_id(self) -> None:+ # Its path is the bare name itself, so suggesting the path would only+ # repeat the ambiguous reference.+ groups = [+ G("root", "Root", None),+ G("top", "Dup", None),+ G("nested", "Dup", "root"),+ ]+ with pytest.raises(ValueError) as e:+ resolve_group_reference(groups, "Dup")+ assert str(e.value) == (+ "Ambiguous room group 'Dup': use 'Root/Dup' or id 'top' for the "+ "top-level 'Dup'"+ )++ def test_legacy_name_with_separator_is_reached_by_id(self) -> None:+ groups = [G("x", "A/B", None), G("y", "A", None), G("z", "B", "y")]+ assert resolve_group_reference(groups, "A/B") == "z"+ assert resolve_group_reference(groups, "x") == "x"+++class TestGroupPath:+ def test_root_first(self) -> None:+ by_id = {g.id: g for g in TREE}+ assert group_path(by_id["fraud-inc"], by_id) == "Fraud/Incidents"+ assert group_path(by_id["eng"], by_id) == "Eng"diff --git a/core/tests/switch_core/db/stores/test_room_group_store.py b/core/tests/switch_core/db/stores/test_room_group_store.pyindex 020406ac6..f5eeb31d9 100644--- a/core/tests/switch_core/db/stores/test_room_group_store.py+++ b/core/tests/switch_core/db/stores/test_room_group_store.py@@ -3,8 +3,11 @@ from __future__ import annotationsimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.models import Room-from switch_core.db.stores.room_group_store import RoomGroupStore+from switch_core.db.models import Room, RoomGroup+from switch_core.db.stores.room_group_store import (+ RoomGroupNameTaken,+ RoomGroupStore,+)from switch_core.db.stores.room_store import RoomStoreGroupStore = RoomGroupStore@@ -113,6 +116,32 @@ class TestRoomGroupStore:session, a.id, parent_group_id=c.id, reparent=True)+ async def test_reparent_sees_a_move_another_session_committed(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ a = await store.create(+ session, name="A", description=None, color=None, parent_group_id=None+ )+ b = await store.create(+ session, name="B", description=None, color=None, parent_group_id=None+ )+ await session.commit()+ # This session still holds A at the top level when another one+ # moves A under B; B under A would then close a cycle.+ async with session_factory() as other:+ await store.update_fields(+ other, a.id, parent_group_id=b.id, reparent=True+ )+ await other.commit()+ assert a.parent_group_id is None++ with pytest.raises(ValueError, match="descendants"):+ await store.update_fields(+ session, b.id, parent_group_id=a.id, reparent=True+ )+async def test_reparent_to_top_level(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -207,6 +236,36 @@ class TestRoomGroupStore:b_refreshed = await store.get(session, b.id)assert b_refreshed is not None and b_refreshed.parent_group_id is None+ async def test_delete_promotes_children_to_the_parent_committed_last(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ a = await store.create(+ session, name="A", description=None, color=None, parent_group_id=None+ )+ b = await store.create(+ session, name="B", description=None, color=None, parent_group_id=a.id+ )+ c = await store.create(+ session, name="C", description=None, color=None, parent_group_id=b.id+ )+ await session.commit()+ # This session still holds B under A when another one moves it.+ assert (await store.get(session, b.id)) is not None+ async with session_factory() as other:+ await store.update_fields(+ other, b.id, parent_group_id=None, reparent=True+ )+ await other.commit()++ assert await store.delete(session, b.id) is True+ await session.commit()+ c_refreshed = await store.get(session, c.id)+ assert c_refreshed is not None+ await session.refresh(c_refreshed)+ assert c_refreshed.parent_group_id is None+async def test_delete_missing_returns_false(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -244,3 +303,174 @@ class TestRoomGroupStore:rooms = Rooms()async with session_factory() as session:assert await rooms.set_group_bulk(session, [], None) == 0+++async def _group(+ store: RoomGroupStore, session: AsyncSession, name: str, parent: str | None+) -> str:+ group = await store.create(+ session, name=name, description=None, color=None, parent_group_id=parent+ )+ return group.id+++class TestSiblingNames:+ async def test_same_name_under_different_parents_is_allowed(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ payments = await _group(store, session, "Payments", None)+ fraud = await _group(store, session, "Fraud", None)+ await _group(store, session, "Incidents", payments)+ await _group(store, session, "Incidents", fraud)+ await session.commit()+ assert await store.resolve(session, "Fraud/Incidents") != (+ await store.resolve(session, "Payments/Incidents")+ )++ async def test_top_level_duplicate_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ await _group(store, session, "Fraud", None)+ with pytest.raises(RoomGroupNameTaken) as e:+ await _group(store, session, " fraud ", None)+ assert str(e.value) == (+ "A room group named 'Fraud' already exists at the top level"+ )++ async def test_nested_duplicate_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ fraud = await _group(store, session, "Fraud", None)+ await _group(store, session, "Incidents", fraud)+ with pytest.raises(RoomGroupNameTaken, match="under 'Fraud'"):+ await _group(store, session, "Incidents", fraud)++ async def test_separator_and_empty_names_are_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ with pytest.raises(ValueError, match="cannot contain '/'"):+ await _group(store, session, "Fraud/Incidents", None)+ with pytest.raises(ValueError, match="cannot be empty"):+ await _group(store, session, " ", None)++ async def test_rename_onto_a_sibling_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ await _group(store, session, "Fraud", None)+ other = await _group(store, session, "Payments", None)+ with pytest.raises(RoomGroupNameTaken, match="'Fraud' already exists"):+ await store.update_fields(session, other, name="Fraud")+ with pytest.raises(ValueError, match="cannot contain '/'"):+ await store.update_fields(session, other, name="Pay/ments")+ # Changing only the case of its own name is not a clash with itself.+ renamed = await store.update_fields(session, other, name="PAYMENTS")+ assert renamed.name == "PAYMENTS"++ async def test_reparent_next_to_a_namesake_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ payments = await _group(store, session, "Payments", None)+ fraud = await _group(store, session, "Fraud", None)+ await _group(store, session, "Incidents", payments)+ moving = await _group(store, session, "Incidents", fraud)+ with pytest.raises(RoomGroupNameTaken, match="under 'Payments'"):+ await store.update_fields(+ session, moving, parent_group_id=payments, reparent=True+ )++ async def test_rename_checks_names_under_the_parent_committed_last(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ payments = await _group(store, session, "Payments", None)+ fraud = await _group(store, session, "Fraud", None)+ await _group(store, session, "Releases", payments)+ moving = await _group(store, session, "Incidents", fraud)+ await session.commit()+ # This session still holds Incidents under Fraud when another one+ # moves it under Payments. Kept referenced so the session's+ # identity map keeps the stale copy.+ held = await store.get(session, moving)+ assert held is not None and held.parent_group_id == fraud+ async with session_factory() as other:+ await store.update_fields(+ other, moving, parent_group_id=payments, reparent=True+ )+ await other.commit()++ with pytest.raises(RoomGroupNameTaken, match="under 'Payments'"):+ await store.update_fields(session, moving, name="Releases")++ async def test_rename_checks_sibling_names_committed_last(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ payments = await _group(store, session, "Payments", None)+ releases = await _group(store, session, "Releases", payments)+ incidents = await _group(store, session, "Incidents", payments)+ await session.commit()+ # This session still holds the sibling as Releases when another+ # one renames it to Archive.+ held = await store.get(session, releases)+ assert held is not None+ async with session_factory() as other:+ await store.update_fields(other, releases, name="Archive")+ await other.commit()++ with pytest.raises(RoomGroupNameTaken, match="'Archive'"):+ await store.update_fields(session, incidents, name="Archive")++ async def test_delete_that_would_promote_onto_a_namesake_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = GroupStore()+ async with session_factory() as session:+ payments = await _group(store, session, "Payments", None)+ await _group(store, session, "Incidents", payments)+ archive = await _group(store, session, "Archive", payments)+ await _group(store, session, "Incidents", archive)+ await session.commit()+ with pytest.raises(RoomGroupNameTaken) as e:+ await store.delete(session, archive)+ assert str(e.value) == (+ "Cannot delete room group 'Archive': its subgroup 'Incidents' "+ "would move under 'Payments', where a group named 'Incidents' "+ "already exists. Rename or move one of them first"+ )++ async def test_legacy_top_level_duplicates_offer_the_final_groups_ids(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Two top-level "Ops" groups from before the sibling rule, added past+ # the store because it would refuse the second.+ store = GroupStore()+ async with session_factory() as session:+ ops = [RoomGroup(name="Ops"), RoomGroup(name="Ops")]+ session.add_all(ops)+ await session.flush()+ incidents = [+ await _group(store, session, "Incidents", group.id) for group in ops+ ]+ await session.commit()+ with pytest.raises(ValueError) as e:+ await store.resolve(session, "Ops/Incidents")+ message = str(e.value)+ assert "2 groups are named 'Ops' at the top level" in message+ for group_id in incidents:+ assert f"'Ops/Incidents' (id '{group_id}')" in message+ for group in ops:+ assert group.id not in messagediff --git a/gateway/src/pages/rooms/GroupsPage.tsx b/gateway/src/pages/rooms/GroupsPage.tsxindex 452a6ab89..feeea4fcc 100644--- a/gateway/src/pages/rooms/GroupsPage.tsx+++ b/gateway/src/pages/rooms/GroupsPage.tsx@@ -461,6 +461,7 @@ export default function GroupsPage() {const [formOpen, setFormOpen] = useState(false);const [editGroup, setEditGroup] = useState<RoomGroupDetail | null>(null);const [deleteTarget, setDeleteTarget] = useState<RoomGroupDetail | null>(null);+ const [deleteError, setDeleteError] = useState<string | null>(null);const groupList = useMemo(() => groups ?? [], [groups]);const roomList = useMemo(() => rooms ?? [], [rooms]);@@ -480,12 +481,23 @@ export default function GroupsPage() {const handleDelete = useCallback(async () => {if (!deleteTarget) return;- await deleteRoomGroup(deleteTarget.id);+ setDeleteError(null);+ try {+ await deleteRoomGroup(deleteTarget.id);+ } catch (err) {+ setDeleteError(err instanceof Error ? err.message : "Failed to delete group");+ return;+ }if (selectedId === deleteTarget.id) setSelectedId(null);setDeleteTarget(null);refetchAll();}, [deleteTarget, selectedId, refetchAll]);+ const closeDelete = useCallback(() => {+ setDeleteTarget(null);+ setDeleteError(null);+ }, []);+return (<Box><Stack direction="row" alignItems="center" spacing={1} mb={2}>@@ -552,16 +564,21 @@ export default function GroupsPage() {onSaved={refetchAll}/>- <Dialog open={deleteTarget !== null} onClose={() => setDeleteTarget(null)}>+ <Dialog open={deleteTarget !== null} onClose={closeDelete}><DialogTitle>Delete group?</DialogTitle><DialogContent>+ {deleteError && (+ <Alert severity="error" sx={{ mb: 2 }}>+ {deleteError}+ </Alert>+ )}<Typography variant="body2">Delete <b>{deleteTarget?.name}</b>? Its rooms become standalone and anysubgroups move up to this group's parent. This cannot be undone.</Typography></DialogContent><DialogActions>- <Button onClick={() => setDeleteTarget(null)}>Cancel</Button>+ <Button onClick={closeDelete}>Cancel</Button><Button color="error" variant="contained" onClick={handleDelete}>Delete</Button>