Coverage for app / services / swarms / prompts.py: 98%

224 statements  

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

1"""What each agent in a swarm is told — the task text of every kind of step. 

2 

3The agent's own instructions are never replaced: a swarm task runs the agent 

4as it is, and everything about the swarm reaches it in the task, as a 

5dashboard tile's instructions do. Every task opens with a 

6``<swarm_context>`` — the team's task, the plan and its progress, and the 

7run's ledger — so each agent works from what the team knows, not from its 

8subtask alone. 

9 

10The team's work reaches the lead as attached documents (:func:`work_documents`), 

11one per piece, which svc-ai lets it read whole or search and read on, and 

12cite by id: passed by reference, never pasted into the prompt. 

13""" 

14 

15from __future__ import annotations 

16 

17from collections.abc import Sequence 

18 

19from app.db.postgres.enums import SwarmEnum 

20from app.db.postgres.models import SwarmRun, SwarmTask 

21from app.services.attachments import TurnDocument 

22from app.services.swarms import ledger as ledger_service 

23from app.services.swarms import thread 

24from app.services.swarms.roster import Member, Roster 

25from app.services.swarms.schemas import TaskBrief 

26from app.services.swarms.topologies import PlanSpec 

27from app.util.attachment_wire import carried_sources 

28 

29TaskStatus = SwarmEnum.TaskStatus 

30WrapUpReason = SwarmEnum.WrapUpReason 

31 

32#: How each status reads in the plan an agent is shown. 

33STATUS_WORDS = { 

34 TaskStatus.queued: "to do", 

35 TaskStatus.running: "in progress", 

36 TaskStatus.awaiting_input: "waiting for an answer", 

37 TaskStatus.done: "done", 

38 TaskStatus.failed: "failed", 

39 TaskStatus.blocked: "refused by a rule", 

40 TaskStatus.skipped: "not done", 

41 TaskStatus.cancelled: "dropped", 

42 TaskStatus.interrupted: "to do again", 

43} 

44 

45#: Why a run stopped starting work, as the lead is told it. 

46WRAP_UP_WORDS = { 

47 WrapUpReason.budget: "the run's budget ran low", 

48 WrapUpReason.time: "the run's time ran low", 

49 WrapUpReason.stopped: "the person who started it asked it to stop", 

50} 

51 

52#: Ledger kinds, as headings. 

53LEDGER_HEADINGS = { 

54 "facts": "Established", 

55 "assumptions": "Assumed", 

56 "gaps": "Still open", 

57} 

58 

59 

60def _minutes(seconds: int) -> str: 

61 minutes = max(1, round(seconds / 60)) 

62 return f"{minutes} minute{'s' if minutes != 1 else ''}" 

63 

64 

65#: Lines of the plan an agent is shown; a deep plan is cut there. 

66MAX_PLAN_LINES = 40 

67 

68 

69def _plan_lines(run: SwarmRun, roster: Roster, mine: SwarmTask | None) -> list[str]: 

70 """The plan as it stands: each piece, and each team's part above its 

71 pieces, indented by how deep it sits.""" 

72 lines = [] 

73 for task in run.tasks or []: 

74 part = task.kind == SwarmEnum.TaskKind.plan and (task.depth or 0) > 0 

75 if task.kind != SwarmEnum.TaskKind.work and not part: 

76 continue 

77 status = STATUS_WORDS.get(TaskStatus(task.status), task.status) 

78 who = "you" if mine is not None and task.id == mine.id else task.agent_name 

79 indent = " " * max((task.depth or 1) - 1, 0) 

80 label = "part" if part else "piece" 

81 lines.append( 

82 f"{indent}- {task.handle} {task.title} — {label}, {who} ({status})" 

83 ) 

84 if len(lines) > MAX_PLAN_LINES: 

85 lines = [*lines[:MAX_PLAN_LINES], f"- … and {len(lines) - MAX_PLAN_LINES} more"] 

86 return lines 

87 

88 

89def swarm_context(run: SwarmRun, roster: Roster, mine: SwarmTask | None) -> str: 

90 """The team's task — after the thread's earlier requests, for a 

91 follow-up — the plan as it stands and what the team knows.""" 

92 parts = [f"The team's task:\n{run.task.strip()}"] 

93 earlier = thread.block(run) 

94 if earlier: 

95 parts.insert(0, earlier) 

96 plan = _plan_lines(run, roster, mine) 

97 if plan: 

98 parts.append("The plan:\n" + "\n".join(plan)) 

99 ledger = run.ledger if isinstance(run.ledger, dict) else {} 

100 for kind in ledger_service.KINDS: 

101 entries = ledger.get(kind) or [] 

102 if entries: 

103 parts.append( 

104 f"{LEDGER_HEADINGS[kind]}:\n" + "\n".join(f"- {e}" for e in entries) 

105 ) 

106 return "<swarm_context>\n" + "\n\n".join(parts) + "\n</swarm_context>" 

107 

108 

109def _member_line(member: Member, lead: Member | None) -> str: 

110 you = " (you)" if lead is not None and member.handle == lead.handle else "" 

111 template = ( 

112 " — can be briefed as several workers, each with its own specialism" 

113 if member.spawn 

114 else "" 

115 ) 

116 about = f": {member.description}" if member.description else "" 

117 here = f" In this swarm: {member.note}" if member.note else "" 

118 return f"- {member.handle} {member.agent_name}{you}{template}{about}{here}" 

119 

120 

121def plan(run: SwarmRun, spec: PlanSpec) -> str: 

122 """What a planner is asked: the lead, for the whole task; a manager, for 

123 the part of it the lead gave its team.""" 

124 team = "\n".join(_member_line(m, spec.planner) for m in spec.members) 

125 documents = ( 

126 "\nThe person attached documents; every member receives them.\n" 

127 if run.file_ids 

128 else "" 

129 ) 

130 earlier = thread.block(run) 

131 earlier = f"{earlier}\n\n" if earlier else "" 

132 if spec.part is None: 

133 opening = ( 

134 "You are leading a team of agents on one task, under a budget of " 

135 f"${float(run.budget_usd):.2f} and {_minutes(run.time_cap_s)}.\n\n" 

136 f"<team>\n{team}\n</team>\n\n" 

137 f"{earlier}<task>\n{run.task.strip()}\n</task>\n{documents}" 

138 f"{thread.pieces_listing(run)}\n" 

139 "Plan how the team will do the task.\n" 

140 ) 

141 doing = ( 

142 "- Assign each piece to the member best suited to it. You review " 

143 "the work and write the answer yourself, so take on a piece only " 

144 "when no one else suits it.\n" 

145 ) 

146 else: 

147 part = "\n".join(_brief_lines(spec.part)) 

148 opening = ( 

149 "You manage one part of a larger task: your team does your part, " 

150 "you check its work, and you report to the lead.\n\n" 

151 f"<your_part>\n{part}\n</your_part>\n\n" 

152 f"{earlier}<whole_task>\n{run.task.strip()}\n</whole_task>\n{documents}\n" 

153 f"<team>\n{team}\n</team>\n\n" 

154 "Plan how your team will do your part, and only your part.\n" 

155 ) 

156 doing = ( 

157 "- Assign each piece to the member best suited to it, yourself " 

158 "included when no one else suits it: you also check the pieces " 

159 "and write your part's report.\n" 

160 ) 

161 follow_up = ( 

162 "- This request follows up earlier ones: plan only what it asks for " 

163 "beyond what the earlier work did. A small change to an earlier " 

164 "answer is one piece.\n" 

165 if earlier 

166 else "" 

167 ) 

168 return ( 

169 opening + "- Split the work only where its pieces can be done apart. When " 

170 "each step needs the last one's result, or the work is small, one " 

171 "member does it all as one piece.\n" 

172 + follow_up 

173 + "- Use as many pieces as the work needs and no more — " 

174 f"{spec.span} at most.\n" 

175 "- Brief each piece in full: what it must find out or produce, what " 

176 "to hand back, where to look, what is not its business so pieces do " 

177 "not overlap, and how its review will know it is done.\n" 

178 + doing 

179 + "- Say what the request already establishes, and what you assume " 

180 "where it is silent." 

181 ) 

182 

183 

184def _brief_lines(brief: TaskBrief) -> list[str]: 

185 lines = [f"What it is for: {brief.objective}"] 

186 if brief.specialism: 

187 lines.insert(0, f"You are: {brief.specialism}") 

188 if brief.output_format: 

189 lines.append(f"Hand back: {brief.output_format}") 

190 if brief.sources: 

191 lines.append(f"Where to look: {brief.sources}") 

192 if brief.boundaries: 

193 lines.append(f"Not your business: {brief.boundaries}") 

194 if brief.done_when: 

195 lines.append(f"Done when: {brief.done_when}") 

196 return lines 

197 

198 

199def work( 

200 run: SwarmRun, 

201 roster: Roster, 

202 task: SwarmTask, 

203 *, 

204 answers: str = "", 

205 has_inputs: bool = False, 

206) -> str: 

207 """What a member is asked when it does a piece of work.""" 

208 brief = TaskBrief.from_stored(task.brief) 

209 lines = [f"Your piece: {task.handle} {task.title}", *_brief_lines(brief)] 

210 if brief.review_note: 

211 lines.append( 

212 "The review sent this piece back: " 

213 f"{brief.review_note}\nDo it again with that put right." 

214 ) 

215 if has_inputs: 

216 lines.append("The pieces this one needs are attached, one document each.") 

217 if answers: 

218 lines.append( 

219 f"You asked the person who started the task; they said:\n{answers}" 

220 ) 

221 return ( 

222 f"{swarm_context(run, roster, task)}\n\n" 

223 "You are one member of a team of agents working on the task above. " 

224 "Others are doing the other pieces; do only yours.\n\n" 

225 "<your_piece>\n" + "\n".join(lines) + "\n</your_piece>\n\n" 

226 "Do your piece now and hand back what it asks for, citing your " 

227 "sources as you would in any answer." 

228 ) 

229 

230 

231#: How much of why a piece did not finish a reviewer reads. 

232_WHY_CHARS = 300 

233 

234 

235def _piece_lines(pieces: Sequence[SwarmTask]) -> list[str]: 

236 lines = [] 

237 for piece in pieces: 

238 brief = TaskBrief.from_stored(piece.brief) 

239 status = STATUS_WORDS.get(TaskStatus(piece.status), piece.status) 

240 line = f"- {piece.handle} {piece.title} ({piece.agent_name}, {status})" 

241 if brief.objective: 

242 line += f"\n For: {brief.objective}" 

243 if brief.done_when: 

244 line += f"\n Done when: {brief.done_when}" 

245 if piece.status != TaskStatus.done and piece.error: 

246 # Why it did not finish — its money, its time, a refusal — so the 

247 # reviewer does not ask for the same again the same way. 

248 why = " ".join(str(piece.error).split())[:_WHY_CHARS] 

249 line += f"\n Not finished: {why}" 

250 lines.append(line) 

251 return lines 

252 

253 

254def review( 

255 run: SwarmRun, 

256 roster: Roster, 

257 pieces: Sequence[SwarmTask], 

258 *, 

259 part: TaskBrief | None = None, 

260 more: PlanSpec | None = None, 

261 time_left_s: int | None = None, 

262) -> str: 

263 """What a reviewer is asked: the lead, of the team's work; a manager, of 

264 its team's work on its part. ``more`` lets the lead ask for another 

265 round of work, told what new work could be given (the answer's reserve 

266 kept apart) and offered only the members that money covers.""" 

267 whose = ( 

268 "Your team has worked on the task." 

269 if part is None 

270 else f"Your team has worked on your part: {part.objective}" 

271 ) 

272 ask = "" 

273 if more is not None: 

274 team = "\n".join(_member_line(m, more.planner) for m in more.members) 

275 left = [] 

276 if more.pool is not None: 

277 left.append( 

278 f"${float(more.pool):.2f} for new work — the answer's share " 

279 "is kept apart —" 

280 ) 

281 if time_left_s is not None: 

282 left.append(_minutes(time_left_s)) 

283 unfinished = any(p.status != TaskStatus.done for p in pieces) 

284 ask = ( 

285 "\nThen decide what comes next. When a gap matters enough to " 

286 "fill before the answer, and what is left allows it" 

287 + (f" ({' and '.join(left)} left)" if left else "") 

288 + f", ask for more work: at most {more.span} new pieces, briefed " 

289 f"in full, for:\n{team}\n" 

290 + ( 

291 "A piece that is not finished cannot be sent back; if what it " 

292 "was for still matters, ask for it as new work — smaller, if " 

293 "money stopped it.\n" 

294 if unfinished 

295 else "" 

296 ) 

297 + f"You may ask for {more.rounds_left} more round" 

298 f"{'s' if more.rounds_left != 1 else ''} at most. Otherwise the " 

299 "answer is written from the work as it stands." 

300 ) 

301 return ( 

302 f"{swarm_context(run, roster, None)}\n\n" 

303 f"{whose} Each finished piece is attached as a document named by its " 

304 "handle and title. The pieces and their briefs:\n" 

305 + "\n".join(_piece_lines(pieces)) 

306 + "\n\n" 

307 "Check each finished piece against its brief. Accept it if it does " 

308 "what its brief asked and what it states is supported by the sources " 

309 "it cites; send it back, once, with an instruction, if it misses its " 

310 "brief or states what its sources do not support. Judge the substance, " 

311 "not the style. A piece that is not finished gets no verdict.\n" 

312 "Then say what facts the work established and what it leaves " 

313 "unanswered." + ask 

314 ) 

315 

316 

317def synthesis( 

318 run: SwarmRun, 

319 roster: Roster, 

320 pieces: Sequence[SwarmTask], 

321 missing: Sequence[SwarmTask], 

322 *, 

323 part: TaskBrief | None = None, 

324 review_note: str = "", 

325) -> str: 

326 """What the lead is asked when it writes the answer — or a manager, its 

327 part's report for the lead.""" 

328 stopped = "" 

329 if run.wrap_up_reason: 

330 reason = WRAP_UP_WORDS.get(WrapUpReason(run.wrap_up_reason), "it was stopped") 

331 stopped = f"\nThe run stopped starting work early, because {reason}. " 

332 if missing: 

333 stopped += ( 

334 "These pieces were not finished: " 

335 + "; ".join(f"{t.handle} {t.title}" for t in missing) 

336 + ". Say plainly what " 

337 + ("the answer" if part is None else "your report") 

338 + " cannot cover because of it.\n" 

339 ) 

340 if review_note: 

341 stopped += ( 

342 f"\nThe lead sent your report back: {review_note}\n" 

343 "Write it again with that put right.\n" 

344 ) 

345 if part is None: 

346 ask = ( 

347 "Write the answer to the task, for the person who asked it, from " 

348 "the team's work: use what it found, keep its citations to its " 

349 "sources, and say plainly what it could not establish. Mention " 

350 "the team, the pieces or the review only where the person needs " 

351 "to know." 

352 ) 

353 whose = "Your team's finished work is attached, one document per piece." 

354 else: 

355 ask = ( 

356 f"Write your part's report for the lead — {part.objective}" 

357 + (f" — handing back {part.output_format}" if part.output_format else "") 

358 + ": what your team found, keeping its citations to its sources, " 

359 "and plainly what it could not establish." 

360 ) 

361 whose = ( 

362 "Your team's finished work on your part is attached, one document " 

363 "per piece." 

364 ) 

365 return f"{swarm_context(run, roster, None)}\n\n{whose}\n{stopped}\n{ask}" 

366 

367 

368def work_documents(pieces: Sequence[SwarmTask]) -> list[TurnDocument]: 

369 """The finished pieces as documents the lead reads, each named by its 

370 handle and title, carrying the sources it cites — so the lead cites the 

371 pages a piece read, not the piece.""" 

372 return [ 

373 TurnDocument( 

374 id=str(piece.id), 

375 name=f"{piece.handle} {piece.title}"[:200], 

376 mime_type="text/markdown", 

377 text=piece.output or "", 

378 sources=tuple(carried_sources(getattr(piece, "citations", None))), 

379 ) 

380 for piece in pieces 

381 if piece.status == TaskStatus.done and (piece.output or "").strip() 

382 ] 

383 

384 

385def _task_block(run: SwarmRun) -> str: 

386 documents = ( 

387 "\nThe person attached documents to the task.\n" if run.file_ids else "\n" 

388 ) 

389 earlier = thread.block(run) 

390 earlier = f"{earlier}\n\n" if earlier else "" 

391 return f"{earlier}<task>\n{run.task.strip()}\n</task>\n{documents}" 

392 

393 

394def _stopped(run: SwarmRun) -> str: 

395 if not run.wrap_up_reason: 

396 return "" 

397 reason = WRAP_UP_WORDS.get(WrapUpReason(run.wrap_up_reason), "it was stopped") 

398 return f"The run stopped starting work early, because {reason}.\n" 

399 

400 

401# ── A mixture of experts ───────────────────────────────────────────────────── 

402 

403 

404def route( 

405 run: SwarmRun, 

406 router: Member, 

407 experts: Sequence[Member], 

408 *, 

409 questions: int, 

410 top_k: int, 

411 samples: int, 

412 layers: int, 

413) -> str: 

414 """What the router is asked: which experts answer which part of the 

415 task.""" 

416 panel = "\n".join(_member_line(m, router) for m in experts) 

417 each = f", each {samples} times on its own" if samples > 1 else "" 

418 again = ( 

419 " after each expert has read the others' answers to its question and " 

420 "answered again" 

421 if layers > 1 

422 else "" 

423 ) 

424 templates = ( 

425 "- For an expert that can be briefed as several specialists, say which " 

426 "specialist it is for the question.\n" 

427 if any(m.spawn for m in experts) 

428 else "" 

429 ) 

430 return ( 

431 "You route one task to a panel of experts, under a budget of " 

432 f"${float(run.budget_usd):.2f} and {_minutes(run.time_cap_s)}.\n\n" 

433 f"<experts>\n{panel}\n</experts>\n\n" 

434 f"{_task_block(run)}\n" 

435 "Decide which experts answer what.\n" 

436 "- Split the task into questions only where its parts call for " 

437 "different expertise or can be answered apart; otherwise keep it one " 

438 f"question. {questions} at most.\n" 

439 "- For each question, list the experts best suited to answer it, most " 

440 "suited first, judging by what each says it is for. The first " 

441 f"{top_k} answer it{each}; the rest are not asked.\n" 

442 "- Brief each question in full: what its answer must find out or " 

443 "produce, what to hand back, where to look, what is not its business, " 

444 "and how you will know it is answered.\n" 

445 f"{templates}" 

446 "- Say what the request already establishes, and what you assume where " 

447 "it is silent.\n" 

448 f"You write the answer from the experts' answers yourself{again}." 

449 ) 

450 

451 

452def expert( 

453 run: SwarmRun, roster: Roster, task: SwarmTask, *, others: int, answers: str = "" 

454) -> str: 

455 """What an expert is asked first: the question the router sent it, which 

456 others may answer too, each on its own.""" 

457 brief = TaskBrief.from_stored(task.brief) 

458 lines = [f"The question: {task.handle} {task.title}", *_brief_lines(brief)] 

459 if answers: 

460 lines.append( 

461 f"You asked the person who started the task; they said:\n{answers}" 

462 ) 

463 alone = ( 

464 f" {others} other answer{'s are' if others != 1 else ' is'} being " 

465 "written to it apart from yours; write your own, as if no one else " 

466 "would." 

467 if others 

468 else "" 

469 ) 

470 return ( 

471 f"{swarm_context(run, roster, task)}\n\n" 

472 "The router sent you one question of the task above, as the expert " 

473 f"best suited to it.{alone}\n\n" 

474 "<your_question>\n" + "\n".join(lines) + "\n</your_question>\n\n" 

475 "Answer it now: a complete answer to the question, citing your sources " 

476 "as you would in any answer." 

477 ) 

478 

479 

480def refine(run: SwarmRun, roster: Roster, task: SwarmTask) -> str: 

481 """What an expert is asked in a second layer: its question again, with 

482 every expert's first answer to it in hand.""" 

483 brief = TaskBrief.from_stored(task.brief) 

484 lines = [f"The question: {task.handle} {task.title}", *_brief_lines(brief)] 

485 return ( 

486 f"{swarm_context(run, roster, task)}\n\n" 

487 "You are one of several experts asked the same question. Each " 

488 "expert's first answer to it, yours among them, is attached, named by " 

489 "its handle.\n\n" 

490 "<your_question>\n" + "\n".join(lines) + "\n</your_question>\n\n" 

491 "Answer the question again, better: keep what holds up, take in what " 

492 "the others found that yours missed, and correct what they show was " 

493 "wrong. Judge each claim by its sources, not by how many experts make " 

494 "it. Hand back a complete answer, citing your sources." 

495 ) 

496 

497 

498def aggregate( 

499 run: SwarmRun, 

500 roster: Roster, 

501 groups: Sequence[tuple[SwarmTask, Sequence[SwarmTask]]], 

502 missing: Sequence[SwarmTask], 

503) -> str: 

504 """What the router is asked last: the answer, from the experts' 

505 answers, question by question.""" 

506 lines = [] 

507 for question, answers in groups: 

508 named = ", ".join(f"{a.handle} ({a.agent_name})" for a in answers) 

509 lines.append(f"- {question.title}: {named}") 

510 gaps = ( 

511 "These answers were not finished: " 

512 + "; ".join(f"{t.handle} {t.title}" for t in missing) 

513 + ". Say plainly what the answer cannot cover because of it.\n" 

514 if missing 

515 else "" 

516 ) 

517 return ( 

518 f"{swarm_context(run, roster, None)}\n\n" 

519 "Your experts have answered the task's questions. Each finished " 

520 "answer is attached, named by its handle:\n" 

521 + "\n".join(lines) 

522 + f"\n\n{_stopped(run)}{gaps}" 

523 "Write the answer to the task, for the person who asked it, from the " 

524 "experts' answers: where they agree, rely on it; where they differ, " 

525 "weigh them by their sources and say which you follow; keep their " 

526 "citations; and say plainly what none of them could establish. " 

527 "Mention the experts only where the person needs to know." 

528 ) 

529 

530 

531# ── A council ──────────────────────────────────────────────────────────────── 

532 

533 

534def _council_line(seats: int, votes: bool, rounds: int) -> str: 

535 then = ( 

536 "the council votes for the answer that serves best" 

537 if votes 

538 else "the chair writes the answer from all of them" 

539 ) 

540 debate = ( 

541 f", after {rounds} round{'s' if rounds != 1 else ''} in which each " 

542 "member reads the others' answers and may write its own again" 

543 if rounds 

544 else "" 

545 ) 

546 return ( 

547 f"You sit on a council giving {seats} answers to one task. Each is " 

548 f"written on its own, without seeing the others; then {then}{debate}." 

549 ) 

550 

551 

552def propose( 

553 run: SwarmRun, 

554 member: Member, 

555 *, 

556 seats: int, 

557 votes: bool, 

558 rounds: int, 

559 answers: str = "", 

560) -> str: 

561 """What a council member is asked first: its own answer, alone.""" 

562 angle = f"\nYour angle on it: {member.note}\n" if member.note else "" 

563 asked = ( 

564 f"\nYou asked the person who started the task; they said:\n{answers}\n" 

565 if answers 

566 else "" 

567 ) 

568 return ( 

569 f"{_council_line(seats, votes, rounds)}\n\n" 

570 f"{_task_block(run)}{angle}{asked}\n" 

571 "Write your complete answer to the task, citing your sources. Give " 

572 "your own judgement; do not hedge to suit the others." 

573 ) 

574 

575 

576def revise( 

577 run: SwarmRun, 

578 member: Member, 

579 *, 

580 seats: int, 

581 votes: bool, 

582 rounds: int, 

583 round_no: int, 

584) -> str: 

585 """What a council member is asked in a later round: its answer again, 

586 every answer of the round before in hand.""" 

587 angle = f"\nYour angle on it: {member.note}\n" if member.note else "" 

588 return ( 

589 f"{_council_line(seats, votes, rounds)}\n\n" 

590 f"{_task_block(run)}{angle}\n" 

591 f"This is round {round_no} of {rounds + 1}. Every answer of the round " 

592 "before is attached, numbered; yours say so.\n\n" 

593 "Write your answer again: keep what holds up, take in what another " 

594 "answer shows better, and correct what it shows was wrong — and keep " 

595 "a view the others do not share when your sources support it. " 

596 "Agreeing is not the aim; the best answer is. Cite your sources." 

597 ) 

598 

599 

600def ballot(run: SwarmRun, *, own_left_out: bool) -> str: 

601 """What a council member is asked when it votes.""" 

602 yours = ", yours left out" if own_left_out else "" 

603 return ( 

604 "You sit on a council that answered one task, each answer written on " 

605 f"its own. They are attached, numbered{yours}.\n\n" 

606 f"{_task_block(run)}\n" 

607 "Choose the answer that serves the person best: correct and supported " 

608 "by its sources first, then complete, then clear. Judge the substance, " 

609 "not how it is phrased. Say what makes it best, and what even it " 

610 "leaves unanswered or gets wrong." 

611 ) 

612 

613 

614def merge(run: SwarmRun, *, fallback: bool, missing: Sequence[SwarmTask]) -> str: 

615 """What the chair is asked when it writes the answer from the council's 

616 answers.""" 

617 why = ( 

618 "No vote could be counted, so you write the answer from the council's " 

619 "answers.\n" 

620 if fallback 

621 else "" 

622 ) 

623 gaps = ( 

624 "These answers were not finished: " 

625 + "; ".join(f"{t.handle} {t.title}" for t in missing) 

626 + ".\n" 

627 if missing 

628 else "" 

629 ) 

630 return ( 

631 "You chair a council that answered one task, each answer written on " 

632 "its own. The finished answers are attached, numbered.\n\n" 

633 f"{_task_block(run)}\n{_stopped(run)}{why}{gaps}" 

634 "Write the answer to the task, for the person who asked it, from them: " 

635 "where they agree, rely on it; where they differ, decide on the " 

636 "evidence each cites and say which you follow; keep their citations; " 

637 "and say plainly what none could establish. Mention the council only " 

638 "where the person needs to know." 

639 ) 

640 

641 

642# ── A pipeline ─────────────────────────────────────────────────────────────── 

643 

644 

645def _stage_lines(stages: Sequence[SwarmTask], mine: SwarmTask) -> list[str]: 

646 lines = [] 

647 for index, stage in enumerate(stages, start=1): 

648 brief = TaskBrief.from_stored(stage.brief) 

649 status = STATUS_WORDS.get(TaskStatus(stage.status), stage.status) 

650 who = "you" if stage.id == mine.id else f"{stage.agent_name}, {status}" 

651 lines.append(f"{index}. {brief.objective} ({who})") 

652 return lines 

653 

654 

655def stage( 

656 run: SwarmRun, 

657 stages: Sequence[SwarmTask], 

658 task: SwarmTask, 

659 previous: SwarmTask | None, 

660 *, 

661 answers: str = "", 

662) -> str: 

663 """What a pipeline's stage is asked: its job, on the work handed to it.""" 

664 index = next(i for i, t in enumerate(stages, start=1) if t.id == task.id) 

665 last = index == len(stages) 

666 brief = TaskBrief.from_stored(task.brief) 

667 if previous is None: 

668 start = "You are first: start from the task." 

669 else: 

670 at = next(i for i, t in enumerate(stages, start=1) if t.id == previous.id) 

671 start = f"The work of stage {at} ({previous.agent_name}) is attached: start from it." 

672 if at < index - 1: 

673 start += " The stages between did not finish." 

674 hand = ( 

675 "Your work is the answer the person receives: write it for them, " 

676 "complete, citing your sources." 

677 if last 

678 else "Hand on your complete work for the next stage — the work itself, " 

679 "not notes about it — keeping its citations." 

680 ) 

681 asked = ( 

682 f"\nYou asked the person who started the task; they said:\n{answers}\n" 

683 if answers 

684 else "" 

685 ) 

686 return ( 

687 f"You are stage {index} of {len(stages)} in a pipeline of agents working " 

688 "on one task, each stage handing its work to the next.\n\n" 

689 "<pipeline>\n" + "\n".join(_stage_lines(stages, task)) + "\n</pipeline>\n\n" 

690 f"{_task_block(run)}\n" 

691 f"<your_stage>\n{brief.objective}\n</your_stage>\n{asked}\n" 

692 f"{start}\n{hand}" 

693 ) 

694 

695 

696def finish(run: SwarmRun, latest: SwarmTask, stages: Sequence[SwarmTask]) -> str: 

697 """What the last stage is asked when the pipeline stopped before it.""" 

698 at = next((i for i, t in enumerate(stages, start=1) if t.id == latest.id), 0) 

699 return ( 

700 f"A pipeline of {len(stages)} agents was working on the task below and " 

701 f"stopped after stage {at}. {_stopped(run)}" 

702 f"The latest work (stage {at}, {latest.agent_name}) is attached.\n\n" 

703 f"{_task_block(run)}\n" 

704 "Write the answer to the task from it, for the person who asked it: " 

705 "complete what you can, keep its citations, and say plainly what the " 

706 "remaining stages would have done that is not done." 

707 ) 

708 

709 

710def read_part(run: SwarmRun, member: Member, part: int, has_notes: bool) -> str: 

711 """What a reader in a chain of agents is asked: notes on its part.""" 

712 notes = ( 

713 " The notes the reader before you wrote are attached too." if has_notes else "" 

714 ) 

715 angle = f"\nYour angle on it: {member.note}\n" if member.note else "" 

716 return ( 

717 "You are one of a chain of agents reading the documents the person " 

718 f"attached, a part at a time, for the task below. You read part {part}, " 

719 f"attached and named with its number and how many there are.{notes}\n\n" 

720 f"{_task_block(run)}{angle}\n" 

721 "Write notes for the next reader: everything in your part that bears " 

722 "on the task, each point with where it came from (the document, and " 

723 "its section or page where that shows), and everything in the earlier " 

724 "notes that still stands, revised where your part changes it. Do not " 

725 "answer the task yet: the last agent writes the answer from the notes." 

726 ) 

727 

728 

729def write_from_notes(run: SwarmRun, notes: SwarmTask | None, parts: int | None) -> str: 

730 """What the last agent in a chain is asked: the answer, from the notes.""" 

731 if notes is None: 

732 given = "No notes could be made, so the documents themselves are attached." 

733 else: 

734 read = TaskBrief.from_stored(notes.brief).extra.get("part") 

735 given = "The last notes are attached." 

736 if parts and read and int(read) < int(parts): 

737 given += f" The readers got through {read} of the {parts} parts." 

738 return ( 

739 "Agents read the documents the person attached a part at a time, each " 

740 f"passing notes to the next. {given}\n\n" 

741 f"{_task_block(run)}\n{_stopped(run)}" 

742 "Write the answer to the task, for the person who asked it, from the " 

743 "notes: say where each point came from, as the notes do, and say " 

744 "plainly what the notes do not cover." 

745 )