Coverage for app / services / swarms / topologies / __init__.py: 94%
223 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Shapes a swarm can take — one registered class each.
3A shape says who leads, who works, and how work moves between them: which
4tasks a run starts with (:meth:`Topology.seed`), what follows a finished one
5(:meth:`Topology.advance`), and what is written when the run wraps up early
6(:meth:`Topology.wrap_up`). The engine (``swarms.engine``) does everything
7else the same way for every shape — dispatching ready tasks, the budget and
8the clock, approval, questions, finishing — so adding a shape is one class
9here, as widget types, rule actions and scorers are.
11The engine asks a shape what each step reads rather than assuming one flat
12team (:meth:`Topology.plan_spec`, :meth:`Topology.inputs`,
13:meth:`Topology.part_of`, :meth:`Topology.more_work`), so a shape of nested
14teams — a lead over managers over workers — runs on the same engine as a
15lead and its workers. A shape whose steps are not a plan, its pieces, a
16review and an answer — a router's, a council's vote, a pipeline's stage —
17writes what each of its steps is asked itself (:meth:`Topology.ask`).
19The registry is served as a catalogue (``GET /app/swarms/topologies``): each
20shape's roles, its settings with their bounds and choices, and its presets,
21so fe-core draws the form from the backend's own vocabulary.
22"""
24from __future__ import annotations
26from abc import ABC, abstractmethod
27from dataclasses import dataclass, field
28from datetime import datetime
29from decimal import Decimal
30from typing import TYPE_CHECKING, Any, ClassVar
32from app.db.postgres.enums import SwarmEnum
33from app.db.postgres.models import SwarmRun, SwarmTask
34from app.services.swarms import budget
35from app.services.swarms.roster import Member, Roster
36from app.services.swarms.schemas import TaskBrief
38if TYPE_CHECKING:
39 from app.services.attachments import TurnDocument
41TaskKind = SwarmEnum.TaskKind
42TaskStatus = SwarmEnum.TaskStatus
44#: A task that will not run again: what waits on it may go ahead.
45SETTLED = frozenset(
46 {
47 TaskStatus.done,
48 TaskStatus.failed,
49 TaskStatus.blocked,
50 TaskStatus.skipped,
51 TaskStatus.cancelled,
52 }
53)
56# ── What a shape declares ────────────────────────────────────────────────────
59@dataclass(frozen=True)
60class RoleSlot:
61 """A part agents play in the shape."""
63 key: str
64 label: str
65 description: str
66 min_members: int = 0
67 max_members: int = 1
68 #: Whether an entry may be a template the lead briefs as many workers.
69 spawn_allowed: bool = False
70 #: Whether its members' order matters (a pipeline's stages): the roster
71 #: keeps them in the order given, and each entry may carry a note.
72 ordered: bool = False
74 def catalogue(self) -> dict[str, Any]:
75 return {
76 "key": self.key,
77 "label": self.label,
78 "description": self.description,
79 "min_members": self.min_members,
80 "max_members": self.max_members,
81 "spawn_allowed": self.spawn_allowed,
82 "ordered": self.ordered,
83 }
86@dataclass(frozen=True)
87class Param:
88 """One setting of a shape."""
90 key: str
91 label: str
92 description: str
93 #: ``int`` or ``choice``.
94 kind: str
95 default: Any
96 minimum: int | None = None
97 maximum: int | None = None
98 #: For a choice: ``(value, label)`` pairs, from the enum that defines it.
99 choices: tuple[tuple[str, str], ...] = ()
100 #: Shown (and used) only when another setting holds one of some values:
101 #: ``(key, values)``.
102 shown_when: tuple[str, tuple[Any, ...]] | None = None
104 def read(self, raw: Any) -> tuple[Any, str | None]:
105 """``raw`` as this setting's value, or the default and a problem."""
106 if raw is None:
107 return self.default, None
108 if self.kind == "int":
109 try:
110 value = int(raw)
111 except (TypeError, ValueError):
112 return self.default, f"{self.label} must be a whole number."
113 if self.minimum is not None and value < self.minimum:
114 return self.default, f"{self.label} is at least {self.minimum}."
115 if self.maximum is not None and value > self.maximum:
116 return self.default, f"{self.label} is at most {self.maximum}."
117 return value, None
118 allowed = {value for value, _ in self.choices}
119 if raw in allowed:
120 return raw, None
121 if raw in ("", None) and self.default is None:
122 return None, None
123 return self.default, f"{self.label} is not one of its choices."
125 def catalogue(self) -> dict[str, Any]:
126 return {
127 "key": self.key,
128 "label": self.label,
129 "description": self.description,
130 "kind": self.kind,
131 "default": self.default,
132 "minimum": self.minimum,
133 "maximum": self.maximum,
134 "choices": [{"value": v, "label": label} for v, label in self.choices],
135 "shown_when": (
136 {"param": self.shown_when[0], "values": list(self.shown_when[1])}
137 if self.shown_when
138 else None
139 ),
140 }
143@dataclass(frozen=True)
144class Preset:
145 """Settings with a name — the organisational shapes people ask for."""
147 key: str
148 label: str
149 description: str
150 params: dict[str, Any]
152 def catalogue(self) -> dict[str, Any]:
153 return {
154 "key": self.key,
155 "label": self.label,
156 "description": self.description,
157 "params": dict(self.params),
158 }
161# ── What a shape does ────────────────────────────────────────────────────────
164@dataclass
165class NewTask:
166 """A task a shape asks for, before the engine has made it a row."""
168 kind: str
169 handle: str
170 title: str
171 role: str
172 #: The roster member that does it.
173 member: str
174 brief: TaskBrief
175 #: Handles of the tasks it waits for — this run's, new or existing.
176 after: tuple[str, ...] = ()
177 #: The handle of the task whose work this one belongs under.
178 parent: str | None = None
179 depth: int = 0
180 #: Its share of the budget, when the shape decides one.
181 budget_usd: Any = None
182 estimate_usd: Any = None
183 tier: str = SwarmEnum.Tier.as_configured.value
184 cost_profile: str | None = None
185 #: A team of its own (a manager's part): its share of the budget is the
186 #: whole team's, of which its plan keeps a part (``engine._share_out``).
187 team: bool = False
188 #: What it is expected to cost, in its agent's typical turns, when not
189 #: one piece of ``brief.effort`` — a team's plan, review, answer and work.
190 turns: float | None = None
193@dataclass(frozen=True)
194class PlanSpec:
195 """What a plan decides over: who plans, whom it may assign, how many
196 pieces at most, and the part of the task it plans (None for the whole
197 task)."""
199 planner: Member
200 members: tuple[Member, ...]
201 span: int
202 part: TaskBrief | None = None
203 #: For a review that may ask for more work: how many rounds are left.
204 rounds_left: int = 0
205 #: For a review that may ask for more work: what new work could be given
206 #: now — the answer's reserve and what open tasks hold kept apart.
207 pool: Decimal | None = None
208 #: What one new piece costs, in its agent's typical turns, when not one
209 #: small piece — a whole team, in a shape of teams.
210 piece_turns: float | None = None
213@dataclass
214class Step:
215 """What follows a finished task."""
217 add: list[NewTask] = field(default_factory=list)
218 #: Tasks that now also wait for others: ``{handle: [handles]}``.
219 wait_also: dict[str, list[str]] = field(default_factory=dict)
220 #: The task whose output is the run's answer, once it is done.
221 final: SwarmTask | None = None
222 #: The work just added waits for a person to approve the plan.
223 approve: bool = False
224 #: What the step established, for the run's ledger.
225 ledger: dict[str, list[str]] = field(default_factory=dict)
226 #: The proposal to show at approval (``SwarmRun.plan``).
227 plan: dict[str, Any] | None = None
228 #: Things the reader should know that are not failures.
229 warnings: list[str] = field(default_factory=list)
230 #: What the step's new shares are split from — a team's own budget for
231 #: its pieces. None: what the run has left for work (``budget.work_pool``).
232 pool: Any = None
235@dataclass
236class Release:
237 """What a settled task — or a team, once all of it has settled — did not
238 spend, and the waiting work it goes to: ``to`` holds each task and what
239 it is given (empty: it stays free for its unit's later work)."""
241 donor: SwarmTask
242 to: list[tuple[SwarmTask, Decimal]] = field(default_factory=list)
245@dataclass(frozen=True)
246class AskContext:
247 """What the engine knows when a task starts, for a shape writing what it
248 is asked."""
250 now: datetime
251 #: Whether this task may ask the person a question (the swarm allows it,
252 #: the run is not wrapping up, and it has not asked before).
253 may_ask: bool
254 #: What the person answered its last questions, as its agent reads it.
255 answers: str = ""
256 time_left_s: int | None = None
259@dataclass
260class Ask:
261 """What one task is asked: its prompt, the schema a structured step
262 fills, the documents it reads — or why it has nothing to do."""
264 prompt: str = ""
265 #: The ``ModelOutput`` a structured step fills; None for prose.
266 schema: type | None = None
267 documents: list[TurnDocument] = field(default_factory=list)
268 may_ask: bool = False
269 #: Whether the person's attached documents go with it.
270 library: bool = True
271 #: For a step that reads the person's documents a part at a time (a
272 #: chain of agents): which part, from 1. Its worker reports how many
273 #: there are (``tasks.TaskOutcome.value``).
274 part: int | None = None
275 #: Whether the documents of the thread's earlier requests go with it
276 #: (``swarms.thread``): the previous answer, the pieces it builds on and,
277 #: for a step that plans or answers, the older answers.
278 thread: bool = True
279 #: Why it has nothing to do: it is skipped, never run.
280 skip: str | None = None
283@dataclass
284class RunState:
285 """A run as a shape reads it."""
287 run: SwarmRun
288 roster: Roster
289 params: dict[str, Any]
291 @property
292 def tasks(self) -> list[SwarmTask]:
293 return list(self.run.tasks or [])
295 def by_handle(self, handle: str) -> SwarmTask | None:
296 return next((t for t in self.tasks if t.handle == handle), None)
298 def of_kind(self, kind: str) -> list[SwarmTask]:
299 return [t for t in self.tasks if t.kind == kind]
301 def done(self, kind: str) -> list[SwarmTask]:
302 return [t for t in self.of_kind(kind) if t.status == TaskStatus.done]
304 def current_work(self) -> list[SwarmTask]:
305 """The run's work tasks, each piece once: a redone piece's latest
306 attempt in place of the one it redoes."""
307 redone = {
308 TaskBrief.from_stored(t.brief).redoes
309 for t in self.of_kind(TaskKind.work)
310 if TaskBrief.from_stored(t.brief).redoes
311 }
312 return [
313 t
314 for t in self.of_kind(TaskKind.work)
315 if str(t.id) not in redone and t.status != TaskStatus.cancelled
316 ]
319class Topology(ABC):
320 """One shape a swarm can take."""
322 key: ClassVar[str]
323 label: ClassVar[str]
324 description: ClassVar[str]
325 roles: ClassVar[tuple[RoleSlot, ...]]
326 params: ClassVar[tuple[Param, ...]] = ()
327 presets: ClassVar[tuple[Preset, ...]] = ()
328 #: Whether a run's first step is a plan a person may approve.
329 plans: ClassVar[bool] = True
331 def read_params(self, raw: Any) -> tuple[dict[str, Any], list[str]]:
332 """``raw`` as this shape's settings, defaults filled, and what is
333 wrong with it. Keys it does not know are dropped."""
334 given = raw if isinstance(raw, dict) else {}
335 out: dict[str, Any] = {}
336 problems: list[str] = []
337 for param in self.params:
338 value, problem = param.read(given.get(param.key))
339 out[param.key] = value
340 if problem:
341 problems.append(problem)
342 if not problems:
343 problems = self.params_problems(out)
344 return out, problems
346 def params_problems(self, params: dict[str, Any]) -> list[str]:
347 """What is wrong with settings each in bounds but not together."""
348 return []
350 def warnings(self, params: dict[str, Any]) -> list[str]:
351 """What a run of these settings should know that is not wrong — a
352 shape the literature says coordinates worse."""
353 return []
355 def check(self, params: dict[str, Any], roster: Roster) -> list[str]:
356 """What is wrong with settings and roster each fine alone but not
357 together — a council of one answer, say."""
358 return []
360 def dispatch_problems(
361 self, params: dict[str, Any], file_ids: list[str]
362 ) -> list[str]:
363 """What is wrong with sending a run of these settings as asked — a
364 chain of agents with no documents to read, say."""
365 return []
367 def check_roster(self, roster: Roster) -> list[str]:
368 """What is wrong with ``roster`` for this shape: a role it does not
369 have, too few or too many in one, a template where none may be."""
370 problems: list[str] = []
371 known = {slot.key: slot for slot in self.roles}
372 for member in roster.members:
373 slot = known.get(member.role)
374 if slot is None:
375 problems.append(f"{self.label} has no role '{member.role}'.")
376 elif member.spawn and not slot.spawn_allowed:
377 problems.append(f"A {slot.label.lower()} cannot be a template.")
378 for slot in self.roles:
379 count = len(roster.of_role(slot.key))
380 if count < slot.min_members:
381 problems.append(
382 f"{slot.label}: {self.label} needs at least {slot.min_members}."
383 )
384 if count > slot.max_members:
385 problems.append(
386 f"{slot.label}: {self.label} takes at most {slot.max_members}."
387 )
388 return problems
390 @abstractmethod
391 def seed(self, state: RunState) -> list[NewTask]:
392 """The tasks a run starts with."""
394 def seed_pool(self, state: RunState) -> Decimal | None:
395 """What the first tasks' shares are split from; None for what the
396 run has for its work (``budget.work_pool``)."""
397 return None
399 def work_pool(self, state: RunState) -> Decimal:
400 """What a plan's pieces share, as it is approved. Nothing else is open
401 then but the rows being shared out again, so nothing held is left
402 out."""
403 return budget.work_pool(state.run)
405 def release(self, state: RunState, settled: SwarmTask) -> list[Release]:
406 """Where what ``settled`` did not spend goes, now it has settled. None
407 by default: a shape whose shares are fixed up front keeps them."""
408 return []
410 def ask(self, state: RunState, task: SwarmTask, ctx: AskContext) -> Ask | None:
411 """What ``task`` is asked, for a step of this shape's own; None for
412 the engine's own plan, piece, review and answer
413 (``engine._standard_ask``)."""
414 return None
416 @abstractmethod
417 def advance(self, state: RunState, finished: SwarmTask) -> Step:
418 """What follows ``finished``, which has settled."""
420 def wrap_up(self, state: RunState) -> list[NewTask]:
421 """Tasks to add when the run stops starting work early, so it still
422 writes an answer from what is done. None by default: a shape whose
423 answer task already exists needs none."""
424 return []
426 @abstractmethod
427 def plan_spec(self, state: RunState, task: SwarmTask) -> PlanSpec:
428 """What the plan ``task`` decides over."""
430 def inputs(self, state: RunState, task: SwarmTask) -> list[SwarmTask]:
431 """The pieces a review or an answer reads: by default every piece
432 of work, each once."""
433 return state.current_work()
435 def part_of(self, state: RunState, task: SwarmTask) -> TaskBrief | None:
436 """The part of the task a review or an answer covers; None for the
437 whole of it."""
438 return None
440 def more_work(self, state: RunState, task: SwarmTask) -> PlanSpec | None:
441 """Whether the review ``task`` may ask for more work, and from whom;
442 None when it may not."""
443 return None
445 def catalogue(self) -> dict[str, Any]:
446 return {
447 "key": self.key,
448 "label": self.label,
449 "description": self.description,
450 "roles": [slot.catalogue() for slot in self.roles],
451 "params": [param.catalogue() for param in self.params],
452 "presets": [preset.catalogue() for preset in self.presets],
453 "plans": self.plans,
454 }
457_REGISTRY: dict[str, Topology] = {}
460def register_topology(cls: type[Topology]) -> type[Topology]:
461 if cls.key in _REGISTRY:
462 raise RuntimeError(f"Swarm shape '{cls.key}' is already registered.")
463 _REGISTRY[cls.key] = cls()
464 return cls
467def get(key: str) -> Topology | None:
468 return _REGISTRY.get(key)
471def keys() -> tuple[str, ...]:
472 return tuple(_REGISTRY)
475def catalogue() -> list[dict[str, Any]]:
476 return [topology.catalogue() for topology in _REGISTRY.values()]
479# Registered on import, in catalogue order (so not sorted).
480# isort: off
481from app.services.swarms.topologies import supervisor # noqa: F401, E402
482from app.services.swarms.topologies import hierarchy # noqa: F401, E402
483from app.services.swarms.topologies import experts # noqa: F401, E402
484from app.services.swarms.topologies import council # noqa: F401, E402
485from app.services.swarms.topologies import pipeline # noqa: F401, E402
486# isort: on