Coverage for app / services / swarms / thread.py: 92%
226 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"""Follow-ups: a thread of requests to one swarm, each building on the last.
3A person reads a run's answer and sends a follow-up (``engine.follow_up``):
4another run of the same swarm, as it is now, that follows up the thread's
5latest run (``SwarmRun.parent_run_id``; ``thread_id`` the first run's id,
6``thread_seq`` its place). A thread is a line, never a tree: only its
7latest run may be followed up, and its place is unique.
9What a follow-up's agents receive from the earlier runs is the work itself,
10never a summary a model wrote of it:
12- **The requests** (:func:`block`): every earlier request in order, as the
13 person wrote it, with how each went — in every step's prompt, so no agent
14 works from the newest request alone.
15- **The previous answer**, attached to every step; **older answers** (up to
16 :data:`MAX_OLDER_ANSWERS`) to the steps that plan and that write the
17 answer; and **the earlier pieces** a new piece builds on — the lead's plan
18 names them (``builds_on``, from :func:`earlier_refs`) and only they go to
19 its worker. svc-ai shows a short document whole and lets an agent read a
20 long one on, so fidelity costs no extra model call (:func:`documents_for`).
21- **What the team established**: the parent's ledger seeds the follow-up's.
23What the follow-up was sent with is snapshotted on its run when it is sent
24(``config["thread"]``, :func:`snapshot`): the earlier requests and outcomes
25and the pieces it may build on. Earlier runs are finished and never change,
26so what each step was given can be derived again from the rows — which the
27decision record does.
29Every step's documents are held to svc-ai's limit together (:func:`fit`):
30its own inputs first, then the previous answer, the person's documents,
31the pieces it builds on and older answers; what does not fit is named in
32its prompt.
33"""
35from __future__ import annotations
37from collections.abc import Iterable, Sequence
38from dataclasses import dataclass, field, replace
39from typing import Any
40from uuid import UUID
42from sqlalchemy import func
43from sqlalchemy.orm import Session
45from app.db.postgres.enums import SwarmEnum
46from app.db.postgres.models import SwarmRun, SwarmTask
47from app.services.attachments import TurnDocument
48from app.util.attachment_wire import (
49 MAX_ATTACHMENT_CHARS,
50 MAX_ATTACHMENTS,
51 AttachedIn,
52 carried_sources,
53)
55RunStatus = SwarmEnum.RunStatus
56TaskKind = SwarmEnum.TaskKind
57TaskStatus = SwarmEnum.TaskStatus
58WrapUpReason = SwarmEnum.WrapUpReason
60#: Where a follow-up's snapshot of its thread is kept on its run's config.
61THREAD_KEY = "thread"
62#: The most requests one thread holds.
63MAX_THREAD_RUNS = 20
64#: How much of an older request the steps are shown (the previous one is
65#: shown whole).
66MAX_EARLIER_TASK_CHARS = 2_000
67#: Older answers attached beside the previous one, newest first.
68MAX_OLDER_ANSWERS = 4
69#: Earlier pieces one new piece may build on.
70MAX_BUILDS_ON = 4
71#: Earlier pieces the lead is offered to build on.
72MAX_EARLIER_PIECES = 24
73#: A run that may be followed up: it has finished, however it went.
74FINISHED = frozenset(
75 {
76 RunStatus.completed,
77 RunStatus.partial,
78 RunStatus.failed,
79 RunStatus.cancelled,
80 RunStatus.blocked,
81 }
82)
83#: Steps that read older answers too: the ones that plan the work and the
84#: one that writes the answer.
85TAKES_OLDER = frozenset({TaskKind.plan, TaskKind.route, TaskKind.synthesise})
86#: Where a piece's brief keeps the earlier pieces it builds on.
87BUILDS_ON_KEY = "builds_on"
89#: How a run's end reads to the agents of a later one.
90_WRAP_UP = {
91 WrapUpReason.budget: "its budget ran low",
92 WrapUpReason.time: "its time ran low",
93 WrapUpReason.stopped: "it was stopped",
94 WrapUpReason.unanswered: "nobody answered its question",
95}
98# ── The thread's rows ────────────────────────────────────────────────────────
101def chain(db: Session, run: SwarmRun) -> list[SwarmRun]:
102 """Every run of ``run``'s thread, its owner's, first to latest."""
103 return (
104 db.query(SwarmRun)
105 .filter(
106 SwarmRun.thread_id == run.thread_id,
107 SwarmRun.user_id == run.user_id,
108 )
109 .order_by(SwarmRun.thread_seq.asc())
110 .all()
111 )
114def threads(db: Session, *where: Any, limit: int = 20) -> list[list[SwarmRun]]:
115 """The ``limit`` threads with the newest activity among the runs
116 ``where`` selects, each its runs first to latest — what a list of a
117 person's runs shows, one row a thread."""
118 latest = func.max(SwarmRun.created_at)
119 ids = [
120 row[0]
121 for row in db.query(SwarmRun.thread_id, latest)
122 .filter(*where)
123 .group_by(SwarmRun.thread_id)
124 .order_by(latest.desc())
125 .limit(limit)
126 .all()
127 ]
128 if not ids:
129 return []
130 runs = (
131 db.query(SwarmRun)
132 .filter(SwarmRun.thread_id.in_(ids), *where)
133 .order_by(SwarmRun.thread_seq.asc())
134 .all()
135 )
136 return group(runs, order=ids)
139def group(
140 runs: Iterable[SwarmRun], *, order: Sequence[Any] = ()
141) -> list[list[SwarmRun]]:
142 """``runs`` by thread, each first to latest; threads in ``order`` (by
143 id), else the one with the newest run first."""
144 by_thread: dict[Any, list[SwarmRun]] = {}
145 for run in runs:
146 by_thread.setdefault(run.thread_id, []).append(run)
147 for members in by_thread.values():
148 members.sort(key=lambda r: int(r.thread_seq or 1))
149 if order:
150 return [by_thread[t] for t in order if t in by_thread]
151 return sorted(
152 by_thread.values(),
153 key=lambda members: max(r.created_at for r in members),
154 reverse=True,
155 )
158def outcome(run: SwarmRun) -> str:
159 """How a run went, in a few words: what a later run's agents are told."""
160 status = run.status
161 if status == RunStatus.completed:
162 return "answered"
163 if status == RunStatus.partial:
164 missing = sum(
165 1
166 for t in run.tasks or []
167 if t.status in (TaskStatus.failed, TaskStatus.blocked, TaskStatus.skipped)
168 )
169 why = []
170 if run.wrap_up_reason:
171 why.append(
172 _WRAP_UP.get(WrapUpReason(run.wrap_up_reason), "it stopped early")
173 )
174 if missing:
175 why.append(f"{missing} piece{'s' if missing != 1 else ''} not done")
176 return "answered in part" + (f" ({'; '.join(why)})" if why else "")
177 if status == RunStatus.failed:
178 error = (run.error or "").strip()
179 return "failed" + (f": {error[:300]}" if error else "")
180 if status == RunStatus.blocked:
181 return "refused by a rule"
182 if status == RunStatus.cancelled:
183 return "stopped before it answered"
184 return str(status)
187# ── The snapshot a follow-up is sent with ────────────────────────────────────
190def earlier_pieces(run: SwarmRun) -> list[dict[str, Any]]:
191 """``run``'s finished pieces of work, as a follow-up's lead is offered
192 them to build on — each by a ref naming the request and the piece."""
193 pieces = []
194 for task in run.tasks or []:
195 if task.kind != TaskKind.work or task.status != TaskStatus.done:
196 continue
197 if not (task.output or "").strip():
198 continue
199 brief = task.brief if isinstance(task.brief, dict) else {}
200 pieces.append(
201 {
202 "ref": f"{run.thread_seq}.{task.handle}",
203 "task_id": str(task.id),
204 "title": task.title,
205 "agent": task.agent_name,
206 "objective": str(brief.get("objective") or "")[:300],
207 }
208 )
209 return pieces[:MAX_EARLIER_PIECES]
212def snapshot(runs: Sequence[SwarmRun], parent: SwarmRun) -> dict[str, Any]:
213 """What a follow-up of ``parent`` is sent with: the earlier requests in
214 order (``runs``, the thread up to ``parent``) and how each went, and the
215 pieces of ``parent`` its lead may build on."""
216 earlier = []
217 for run in runs:
218 text = (run.task or "").strip()
219 if run.id != parent.id and len(text) > MAX_EARLIER_TASK_CHARS:
220 text = text[:MAX_EARLIER_TASK_CHARS].rstrip() + " …"
221 earlier.append(
222 {
223 "run_id": str(run.id),
224 "seq": int(run.thread_seq or 1),
225 "task": text,
226 "outcome": outcome(run),
227 "answered": bool((run.output or "").strip()),
228 }
229 )
230 return {
231 "position": int(parent.thread_seq or 1) + 1,
232 "earlier": earlier,
233 "pieces": earlier_pieces(parent),
234 "carried_files": [],
235 }
238@dataclass(frozen=True)
239class View:
240 """A follow-up's snapshot of its thread, read back."""
242 position: int
243 earlier: tuple[dict[str, Any], ...]
244 pieces: tuple[dict[str, Any], ...]
245 carried_files: tuple[str, ...]
247 @property
248 def previous(self) -> dict[str, Any] | None:
249 return self.earlier[-1] if self.earlier else None
252def view(run: SwarmRun) -> View | None:
253 """``run``'s thread as it was sent, or None for a first request."""
254 raw = (run.config or {}).get(THREAD_KEY)
255 if not isinstance(raw, dict):
256 return None
257 earlier = tuple(e for e in raw.get("earlier") or [] if isinstance(e, dict))
258 if not earlier:
259 return None
260 return View(
261 position=int(raw.get("position") or len(earlier) + 1),
262 earlier=earlier,
263 pieces=tuple(p for p in raw.get("pieces") or [] if isinstance(p, dict)),
264 carried_files=tuple(str(f) for f in raw.get("carried_files") or []),
265 )
268def earlier_refs(run: SwarmRun) -> tuple[str, ...]:
269 """The refs of the earlier pieces a follow-up's pieces may build on."""
270 thread = view(run)
271 return tuple(str(p["ref"]) for p in thread.pieces) if thread else ()
274def carried_files(run: SwarmRun) -> tuple[str, ...]:
275 """The person's documents a follow-up carried from earlier requests."""
276 thread = view(run)
277 return thread.carried_files if thread else ()
280# ── What every step is told ──────────────────────────────────────────────────
283def block(run: SwarmRun) -> str:
284 """The earlier requests of ``run``'s thread and how each went, with how
285 to build on them; empty for a first request."""
286 thread = view(run)
287 if thread is None:
288 return ""
289 lines = [
290 (
291 f"This is request {thread.position} of a thread: the person sent "
292 "the requests below to this swarm first, in this order, and read "
293 "each answer before sending the next."
294 )
295 ]
296 for entry in thread.earlier:
297 lines.append(
298 f"\nRequest {entry.get('seq')} ({entry.get('outcome')}):\n"
299 f"{str(entry.get('task') or '').strip()}"
300 )
301 lines.append(
302 "\nBuild on that work: keep what it established and do not do it "
303 "again unless this request asks you to. When this request asks to "
304 "change an earlier answer, give the changed result in full, not only "
305 "the changes. What an earlier answer cites is that answer's claim: "
306 "to rely on a source of it directly, read the source yourself."
307 )
308 return "<earlier_requests>\n" + "\n".join(lines) + "\n</earlier_requests>"
311def pieces_listing(run: SwarmRun) -> str:
312 """The earlier pieces a follow-up's lead may have its pieces build on,
313 for its plan; empty when there are none."""
314 thread = view(run)
315 if thread is None or not thread.pieces:
316 return ""
317 previous = thread.previous or {}
318 lines = [
319 f"- {p['ref']} {p['title']} ({p['agent']})"
320 + (f" — for: {p['objective']}" if p.get("objective") else "")
321 for p in thread.pieces
322 ]
323 return (
324 f"\nThe pieces request {previous.get('seq')} finished, which a new "
325 "piece may build on:\n"
326 + "\n".join(lines)
327 + "\nWhere a new piece carries one of them further, say it builds on "
328 f"it ({MAX_BUILDS_ON} at most): that piece is given to its worker in "
329 "full. The previous answer goes to every member.\n"
330 )
333# ── What every step is given ─────────────────────────────────────────────────
336@dataclass
337class Documents:
338 """The documents from earlier requests one step is given, by priority."""
340 previous: list[TurnDocument] = field(default_factory=list)
341 builds_on: list[TurnDocument] = field(default_factory=list)
342 older: list[TurnDocument] = field(default_factory=list)
345def answer_document(
346 db: Session, entry: dict[str, Any], *, previous: bool
347) -> TurnDocument | None:
348 """An earlier request's answer as a document — or, for one that did not
349 answer, the pieces it finished; None when it left nothing to read."""
350 run = db.get(SwarmRun, _uuid(entry.get("run_id")))
351 if run is None:
352 return None
353 seq = entry.get("seq")
354 name = f"Answer to request {seq}" + (" (previous)" if previous else "")
355 text = (run.output or "").strip()
356 if not text:
357 done = [
358 t
359 for t in run.tasks or []
360 if t.kind == TaskKind.work
361 and t.status == TaskStatus.done
362 and (t.output or "").strip()
363 ]
364 if not done:
365 return None
366 name = f"Unfinished work of request {seq}" + (" (previous)" if previous else "")
367 text = f"Request {seq} {outcome(run)}. These are the pieces it finished.\n\n"
368 text += "\n\n".join(
369 f"## {t.handle} {t.title}\n\n{(t.output or '').strip()}" for t in done
370 )
371 return TurnDocument(
372 id=f"swarm-answer-{run.id}",
373 name=name[:200],
374 mime_type="text/markdown",
375 text=text,
376 attached_in=AttachedIn.earlier,
377 # An answer's sources travel with it; pieces put together keep
378 # theirs in their text, numbered each its own.
379 sources=tuple(carried_sources(getattr(run, "citations", None)))
380 if (run.output or "").strip()
381 else (),
382 )
385def piece_document(db: Session, piece: dict[str, Any], seq: Any) -> TurnDocument | None:
386 """An earlier piece, in full, for a worker that builds on it."""
387 task = db.get(SwarmTask, _uuid(piece.get("task_id")))
388 if task is None or not (task.output or "").strip():
389 return None
390 return TurnDocument(
391 id=f"swarm-piece-{task.id}",
392 name=f"Earlier work: request {seq} · {task.handle} {task.title}"[:200],
393 mime_type="text/markdown",
394 text=task.output or "",
395 attached_in=AttachedIn.earlier,
396 sources=tuple(carried_sources(getattr(task, "citations", None))),
397 )
400def builds_on(task: SwarmTask) -> tuple[str, ...]:
401 """The refs of the earlier pieces ``task`` builds on, as its brief keeps
402 them."""
403 brief = task.brief if isinstance(task.brief, dict) else {}
404 refs = brief.get(BUILDS_ON_KEY) or []
405 return tuple(str(r) for r in refs if isinstance(r, str))[:MAX_BUILDS_ON]
408def takes_older(task: SwarmTask) -> bool:
409 """Whether ``task`` reads the older answers too: it plans the work or
410 writes the answer."""
411 return task.kind in TAKES_OLDER and (task.depth or 0) == 0
414def documents_for(db: Session, run: SwarmRun, task: SwarmTask) -> Documents:
415 """The documents from earlier requests ``task`` is given."""
416 thread = view(run)
417 documents = Documents()
418 if thread is None:
419 return documents
420 previous = thread.previous
421 if previous is not None:
422 document = answer_document(db, previous, previous=True)
423 if document is not None:
424 documents.previous.append(document)
425 wanted = set(builds_on(task))
426 for piece in thread.pieces:
427 if str(piece.get("ref")) in wanted:
428 document = piece_document(db, piece, (previous or {}).get("seq"))
429 if document is not None:
430 documents.builds_on.append(document)
431 if takes_older(task):
432 for entry in reversed(thread.earlier[:-1][-MAX_OLDER_ANSWERS:]):
433 document = answer_document(db, entry, previous=False)
434 if document is not None:
435 documents.older.append(document)
436 return documents
439# ── Held to svc-ai's limit ───────────────────────────────────────────────────
442@dataclass(frozen=True)
443class Fitted:
444 """One step's documents within the limit, and what was left out."""
446 documents: tuple[TurnDocument, ...]
447 file_ids: tuple[str, ...]
448 #: The thread's documents it was given, by name, for its prompt.
449 given: tuple[str, ...]
450 left_out: tuple[str, ...]
453def fit(
454 inputs: Sequence[TurnDocument],
455 thread: Documents,
456 file_ids: Sequence[str],
457 *,
458 limit: int = MAX_ATTACHMENTS,
459 files_as_one: bool = False,
460) -> Fitted:
461 """``inputs`` (the step's own), the thread's documents and the person's
462 (``file_ids``, new before carried) within ``limit`` documents, in that
463 order of need: inputs, the previous answer, the person's documents, the
464 pieces it builds on, older answers. ``files_as_one``: the person's
465 documents reach the step as one part (a chain of agents' reader)."""
466 room = limit
467 kept_inputs = [within(d) for d in inputs[:room]]
468 left_out = [d.name for d in inputs[room:]]
469 room -= len(kept_inputs)
471 def take(documents: Iterable[TurnDocument]) -> list[TurnDocument]:
472 nonlocal room
473 kept = []
474 for document in documents:
475 if room > 0:
476 kept.append(within(document))
477 room -= 1
478 else:
479 left_out.append(document.name)
480 return kept
482 previous = take(thread.previous)
483 files = tuple(file_ids)
484 if files_as_one:
485 if files and room > 0:
486 room -= 1
487 elif files:
488 left_out.append("the person's documents")
489 files = ()
490 else:
491 kept_files = files[: max(room, 0)]
492 gone = len(files) - len(kept_files)
493 if gone:
494 left_out.append(
495 f"{gone} of the person's documents"
496 if gone > 1
497 else "one of the person's documents"
498 )
499 files = kept_files
500 room -= len(files)
501 building = take(thread.builds_on)
502 older = take(thread.older)
503 given = [*previous, *building, *older]
504 return Fitted(
505 documents=(*kept_inputs, *given),
506 file_ids=files,
507 given=tuple(d.name for d in given),
508 left_out=tuple(left_out),
509 )
512def note(fitted: Fitted) -> str:
513 """What a step's prompt says of the documents from earlier requests it
514 was given, and of any left out for space; empty when neither."""
515 lines = []
516 if fitted.given:
517 lines.append(
518 "Attached from earlier requests: "
519 + "; ".join(f"“{name}”" for name in fitted.given)
520 + "."
521 )
522 if fitted.left_out:
523 lines.append(
524 "Left out for space (only so many documents can go with one "
525 "step): " + "; ".join(fitted.left_out) + "."
526 )
527 return ("\n\n" + "\n".join(lines)) if lines else ""
530def within(document: TurnDocument) -> TurnDocument:
531 """``document`` cut to what svc-ai takes of one document, marked when
532 cut: svc-ai refuses a request with a longer one."""
533 if len(document.text) <= MAX_ATTACHMENT_CHARS:
534 return document
535 return replace(document, text=document.text[:MAX_ATTACHMENT_CHARS], truncated=True)
538def _uuid(value: Any) -> UUID | None:
539 try:
540 return UUID(str(value))
541 except (TypeError, ValueError):
542 return None