Coverage for app / services / swarms / roster.py: 87%

94 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""Who plays which part in a swarm: its roster (``Swarm.roster``). 

2 

3Stored as ``[{role, agent_id, spawn, note}]``: each entry is one of the 

4workspace's agents in one of the shape's roles (``Topology.roles``), with an 

5optional ``note`` — what the person who built the swarm wants of it here (a 

6pipeline stage's job, a council member's angle). A ``spawn`` entry is 

7a template rather than one worker: the lead may brief it as many workers as 

8the plan needs, each with a specialism the lead writes, and every one runs — 

9and is governed — as that agent. The others keep the role they were given: 

10weaker models do better with fixed roles, and a person's own agent is theirs 

11to define. 

12 

13A roster agent must be in the swarm's own workspace (or be CHAINR Bot), the 

14same reach rule a dashboard tile's agent meets 

15(``evaluation.targets._reachable_by``): a run reads each agent from inside a 

16background coordinator, where there is no request to check. 

17 

18Members are named to the lead by handle (``A1``, ``A2``…), never by id: the 

19plan's ``assignee`` is a ``Literal`` of the handles, and the engine maps a 

20handle back to the agent itself, so no id ever comes from a model. 

21""" 

22 

23from __future__ import annotations 

24 

25from dataclasses import dataclass 

26from typing import Any 

27from uuid import UUID 

28 

29from sqlalchemy.orm import Session 

30 

31from app.db.postgres.models import Agent 

32 

33#: Most members a roster holds. 

34MAX_MEMBERS = 16 

35#: Longest note an entry may carry. 

36MAX_NOTE_CHARS = 300 

37 

38 

39class RosterInvalid(ValueError): 

40 """A roster that does not fit its shape or its workspace.""" 

41 

42 def __init__(self, problems: list[str]) -> None: 

43 self.problems = problems 

44 super().__init__("; ".join(problems)) 

45 

46 

47@dataclass(frozen=True) 

48class Member: 

49 """One agent in one role.""" 

50 

51 handle: str 

52 role: str 

53 agent_id: str 

54 agent_name: str 

55 #: What the agent says it is for — what the lead assigns by. 

56 description: str = "" 

57 #: A template the lead may brief as many workers. 

58 spawn: bool = False 

59 #: What the swarm's builder wants of it here. 

60 note: str = "" 

61 

62 def stored(self) -> dict[str, Any]: 

63 """As a run's config keeps it: everything a coordinator needs 

64 without reading the agent again.""" 

65 return { 

66 "handle": self.handle, 

67 "role": self.role, 

68 "agent_id": self.agent_id, 

69 "agent_name": self.agent_name, 

70 "description": self.description, 

71 "spawn": self.spawn, 

72 "note": self.note, 

73 } 

74 

75 

76@dataclass(frozen=True) 

77class Roster: 

78 members: tuple[Member, ...] 

79 

80 @classmethod 

81 def from_stored(cls, rows: Any) -> Roster: 

82 """A run's roster, as :meth:`Member.stored` wrote it.""" 

83 return cls( 

84 tuple( 

85 Member( 

86 handle=str(row["handle"]), 

87 role=str(row["role"]), 

88 agent_id=str(row["agent_id"]), 

89 agent_name=str(row.get("agent_name") or ""), 

90 description=str(row.get("description") or ""), 

91 spawn=bool(row.get("spawn")), 

92 note=str(row.get("note") or ""), 

93 ) 

94 for row in rows or [] 

95 if isinstance(row, dict) and row.get("handle") and row.get("agent_id") 

96 ) 

97 ) 

98 

99 def stored(self) -> list[dict[str, Any]]: 

100 return [member.stored() for member in self.members] 

101 

102 def of_role(self, role: str) -> list[Member]: 

103 return [member for member in self.members if member.role == role] 

104 

105 def first(self, role: str) -> Member | None: 

106 found = self.of_role(role) 

107 return found[0] if found else None 

108 

109 def by_handle(self, handle: str) -> Member | None: 

110 return next((m for m in self.members if m.handle == handle), None) 

111 

112 def handles(self, *roles: str) -> tuple[str, ...]: 

113 return tuple(m.handle for m in self.members if not roles or m.role in roles) 

114 

115 

116def entries(raw: Any) -> tuple[list[dict[str, Any]], list[str]]: 

117 """``raw`` as stored roster entries, and what is wrong with it.""" 

118 problems: list[str] = [] 

119 if not isinstance(raw, list): 

120 return [], ["The roster must be a list of agents."] 

121 if len(raw) > MAX_MEMBERS: 

122 problems.append(f"A swarm holds {MAX_MEMBERS} agents at most.") 

123 out: list[dict[str, Any]] = [] 

124 # One agent may play a role twice with different notes: two stages of a 

125 # pipeline, say. The same agent, role and note twice is a repeat. 

126 seen: set[tuple[str, str, str]] = set() 

127 for index, row in enumerate(raw[:MAX_MEMBERS], start=1): 

128 if not isinstance(row, dict): 

129 problems.append(f"Entry {index} is not an object.") 

130 continue 

131 role = str(row.get("role") or "").strip() 

132 try: 

133 agent_id = str(UUID(str(row.get("agent_id")))) 

134 except (TypeError, ValueError): 

135 problems.append(f"Entry {index} names no agent.") 

136 continue 

137 if not role: 

138 problems.append(f"Entry {index} has no role.") 

139 continue 

140 note = " ".join(str(row.get("note") or "").split()) 

141 if len(note) > MAX_NOTE_CHARS: 

142 problems.append( 

143 f"Entry {index}'s note is longer than {MAX_NOTE_CHARS} characters." 

144 ) 

145 continue 

146 if (role, agent_id, note) in seen: 

147 problems.append(f"Entry {index} repeats an agent in the same role.") 

148 continue 

149 seen.add((role, agent_id, note)) 

150 entry: dict[str, Any] = { 

151 "role": role, 

152 "agent_id": agent_id, 

153 "spawn": bool(row.get("spawn")), 

154 } 

155 if note: 

156 entry["note"] = note 

157 out.append(entry) 

158 return out, problems 

159 

160 

161def _reachable(agent: Agent, owner: dict[str, Any]) -> bool: 

162 """Whether ``agent`` sits in the owner scope ``owner`` names (its three 

163 owner columns), or is a built-in every workspace may use.""" 

164 if getattr(agent, "is_system", False) is True: 

165 return True 

166 for column in ("owner_user_id", "owner_organisation_id", "owner_project_id"): 

167 value = owner.get(column) 

168 if value is not None: 

169 return str(getattr(agent, column, None)) == str(value) 

170 return False 

171 

172 

173def resolve(db: Session, raw: Any, owner: dict[str, Any]) -> Roster: 

174 """The roster ``raw`` describes, each agent read and checked against the 

175 swarm's owner. Raises :class:`RosterInvalid` naming every problem — 

176 another workspace's agent reads as not found, never as forbidden.""" 

177 rows, problems = entries(raw) 

178 members: list[Member] = [] 

179 for index, row in enumerate(rows, start=1): 

180 agent = db.get(Agent, UUID(row["agent_id"])) 

181 if agent is None or not _reachable(agent, owner): 

182 problems.append(f"Agent {row['agent_id']} was not found in this workspace.") 

183 continue 

184 members.append( 

185 Member( 

186 handle=f"A{index}", 

187 role=row["role"], 

188 agent_id=row["agent_id"], 

189 agent_name=str(agent.name), 

190 description=str(getattr(agent, "description", None) or "")[:300], 

191 spawn=row["spawn"], 

192 note=row.get("note", ""), 

193 ) 

194 ) 

195 if problems: 

196 raise RosterInvalid(problems) 

197 return Roster(tuple(members))