Coverage for app / services / swarms / topologies / units.py: 95%

336 statements  

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

1"""Teams as nested units — what every shape so far is made of. 

2 

3A **unit** is a plan, its pieces, a review and an answer. The lead's plan is 

4the root unit; each of its pieces is either a piece of work, or — in a shape 

5with managers — a **team** of its own: a manager's plan for its part, the 

6pieces it gives its workers (or a team of its own again, one level down), its 

7review of them, and its report up. So a lead and its workers is one level of 

8units, and a lead over managers over workers is two, on the same machinery: 

9 

10* a planner at level ``L`` makes at most ``span(L)`` pieces, assigned to the 

11 members ``assignable`` to it — workers at the last level, managers above 

12 it, and a manager may take a piece itself; 

13* a plan of ``one_agent`` is one piece, done alone, whose result is the 

14 unit's: no review, no report; 

15* a unit's review reads each piece's **result** — a piece of work as last 

16 done, a team's report as last written — and sends any back once: a piece 

17 is done again, a team's report written again with the note; 

18* the unit's answer (the run's answer at the root, a report below it) is 

19 written from the results, and the review above waits for it. 

20 

21The lead's review may also ask for **more work** (``more_work``), up to 

22``MAX_ROUNDS`` more rounds — a task ledger's progress check: what is still 

23open, and whether it is worth another round. Each round's pieces are then 

24reviewed, and the answer waits for every round. 

25 

26Budgets follow the teams. The engine splits what is left for work between 

27the root's pieces by estimate (a team's estimate is its plan, review, report 

28and pieces, in its manager's typical turns); a team's share is its own 

29budget, of which its plan, review and report keep a part each and its pieces 

30split the rest — with what the plan did not spend (``Step.pool``). 

31 

32Money follows the work (:meth:`Units.release`): what a settled task did not 

33spend goes to the work still waiting in its unit, by estimate; once a whole 

34team has settled, what it left goes to the work waiting beside it. A piece 

35done again, or a further round, is shared from what is free — never on top 

36of what open tasks hold. Reviews keep their fixed shares, and the answer its 

37reserve. 

38""" 

39 

40from __future__ import annotations 

41 

42from abc import abstractmethod 

43from dataclasses import replace 

44from decimal import Decimal 

45from typing import Any 

46 

47from pydantic import ValidationError 

48 

49from app.db.postgres.enums import SwarmEnum 

50from app.db.postgres.models import SwarmTask 

51from app.services.swarms import budget, thread 

52from app.services.swarms.roster import Member 

53from app.services.swarms.schemas import ( 

54 Approach, 

55 Next, 

56 ProposedTask, 

57 ReadPlan, 

58 SwarmPlan, 

59 SwarmReview, 

60 SwarmReviewRound, 

61 TaskBrief, 

62 Verdict, 

63) 

64from app.services.swarms.topologies import ( 

65 SETTLED, 

66 NewTask, 

67 PlanSpec, 

68 Release, 

69 RunState, 

70 Step, 

71 TaskKind, 

72 TaskStatus, 

73 Topology, 

74) 

75from app.util import cost_profiles 

76 

77Tier = SwarmEnum.Tier 

78 

79#: A level's model, and its effort, as a shape's settings offer them. 

80TIER_CHOICES = ( 

81 (Tier.as_configured.value, "Each agent's own model"), 

82 (Tier.lighter.value, "A lighter model of the same maker"), 

83) 

84COST_PROFILE_CHOICES = tuple( 

85 (profile.value, cost_profiles.LABELS[profile.value]) 

86 for profile in cost_profiles.CostProfile 

87) 

88 

89LEAD = "lead" 

90MANAGER = "manager" 

91WORKER = "worker" 

92 

93ROOT_PLAN = "P1" 

94ROOT_ANSWER = "S1" 

95 

96#: A piece whose result is its unit's (a plan of one piece). 

97FINAL_KEY = "final" 

98#: A plan's level: 0 for the lead's, one more for each team below it. 

99LEVEL_KEY = "level" 

100#: A team's budget, kept on its plan's brief (``engine._share_out``). 

101TEAM_BUDGET_KEY = budget.TEAM_BUDGET_KEY 

102#: Which of the lead's rounds of work a piece or a review belongs to. 

103ROUND_KEY = "round" 

104#: The review that asked for a piece: a further round's, or one done again. 

105ASKED_BY_KEY = "asked_by" 

106#: What a piece copied from the one it redoes must not carry on. 

107_NOT_CARRIED = (ASKED_BY_KEY, budget.TOPPED_UP_KEY, budget.PASSED_ON_KEY) 

108 

109#: More rounds of work the lead may ask for after its first review. 

110MAX_ROUNDS = 2 

111#: A team's budget: what its plan, review and report each keep, of the whole. 

112TEAM_PLAN_SHARE = Decimal("0.15") 

113TEAM_REVIEW_SHARE = Decimal("0.10") 

114TEAM_ANSWER_SHARE = Decimal("0.10") 

115#: A piece of work, in typical turns, for a team's estimate (medium effort). 

116PIECE_TURNS = 2 

117 

118_CENT = Decimal("0.000001") 

119 

120 

121def level_of(task: SwarmTask) -> int: 

122 """A plan's level (0 for the lead's).""" 

123 value = TaskBrief.from_stored(task.brief).extra.get(LEVEL_KEY, 0) 

124 try: 

125 return int(value) 

126 except (TypeError, ValueError): 

127 return 0 

128 

129 

130def round_of(task: SwarmTask) -> int: 

131 value = TaskBrief.from_stored(task.brief).extra.get(ROUND_KEY, 1) 

132 try: 

133 return int(value) 

134 except (TypeError, ValueError): 

135 return 1 

136 

137 

138def team_budget(task: SwarmTask) -> Decimal | None: 

139 """A team plan's budget for the whole team, or None (the root's).""" 

140 return budget.brief_usd(task, TEAM_BUDGET_KEY) 

141 

142 

143def _with_extra(brief: TaskBrief, **extra: Any) -> TaskBrief: 

144 return replace(brief, extra={**brief.extra, **extra}) 

145 

146 

147def _closed(team: SwarmTask) -> bool: 

148 """Whether what ``team`` left has been passed on (``Units._close``).""" 

149 return budget.brief_usd(team, budget.PASSED_ON_KEY) is not None 

150 

151 

152class Units(Topology): 

153 """A shape of nested teams; subclasses say how deep and how wide.""" 

154 

155 @abstractmethod 

156 def levels(self, params: dict[str, Any]) -> int: 

157 """Levels of work below the lead: 1 for a lead and its workers.""" 

158 

159 @abstractmethod 

160 def span(self, params: dict[str, Any], level: int) -> int: 

161 """The most pieces a planner at ``level`` makes.""" 

162 

163 def child_role(self, params: dict[str, Any], level: int) -> str: 

164 """The role that does a planner's pieces at ``level``.""" 

165 return WORKER if level + 1 >= self.levels(params) else MANAGER 

166 

167 def level_settings(self, params: dict[str, Any], role: str) -> dict[str, Any]: 

168 """The model tier and cost profile a role's pieces run under.""" 

169 return {} 

170 

171 def assignable(self, state: RunState, plan: SwarmTask) -> list[Member]: 

172 """Whom ``plan`` may give pieces to: the role below it, and — for a 

173 manager — itself.""" 

174 level = level_of(plan) 

175 members = list(state.roster.of_role(self.child_role(state.params, level))) 

176 planner = self._member(state, plan) 

177 if level > 0 and planner is not None and planner not in members: 

178 members.append(planner) 

179 if not members and planner is not None: 

180 members = [planner] 

181 return members 

182 

183 # ── Reading the tree ───────────────────────────────────────────────────── 

184 

185 def _member(self, state: RunState, task: SwarmTask) -> Member | None: 

186 for member in state.roster.members: 

187 if member.agent_id == str(task.agent_id) and member.role == task.role: 

188 return member 

189 return state.roster.first(LEAD) 

190 

191 def _parent(self, state: RunState, task: SwarmTask) -> SwarmTask | None: 

192 return next((t for t in state.tasks if t.id == task.parent_id), None) 

193 

194 def _children(self, state: RunState, plan: SwarmTask) -> list[SwarmTask]: 

195 """A unit's pieces — work, or teams — each once (not their redos).""" 

196 return [ 

197 t 

198 for t in state.tasks 

199 if t.parent_id == plan.id 

200 and t.kind in (TaskKind.work, TaskKind.plan) 

201 and not TaskBrief.from_stored(t.brief).redoes 

202 and t.status != TaskStatus.cancelled 

203 ] 

204 

205 def _redo_of(self, state: RunState, task: SwarmTask) -> SwarmTask | None: 

206 return next( 

207 ( 

208 t 

209 for t in state.tasks 

210 if TaskBrief.from_stored(t.brief).redoes == str(task.id) 

211 and t.status != TaskStatus.cancelled 

212 ), 

213 None, 

214 ) 

215 

216 def result_of(self, state: RunState, piece: SwarmTask) -> SwarmTask: 

217 """What a piece came to: a piece of work as last done; a team's 

218 report as last written, or its one piece, or — when it never got that 

219 far — its plan, which reads as missing.""" 

220 if piece.kind == TaskKind.work: 

221 return self._redo_of(state, piece) or piece 

222 answer = state.by_handle(self._answer_handle(piece)) 

223 if answer is not None: 

224 return self._redo_of(state, answer) or answer 

225 final = next( 

226 ( 

227 t 

228 for t in self._children(state, piece) 

229 if TaskBrief.from_stored(t.brief).extra.get(FINAL_KEY) 

230 ), 

231 None, 

232 ) 

233 return self.result_of(state, final) if final is not None else piece 

234 

235 # ── Handles ────────────────────────────────────────────────────────────── 

236 

237 def _child_handle(self, plan: SwarmTask, k: int) -> str: 

238 return f"T{k}" if level_of(plan) == 0 else f"{plan.handle}.{k}" 

239 

240 def _review_handle(self, plan: SwarmTask, round_no: int = 1) -> str: 

241 return f"R{round_no}" if level_of(plan) == 0 else f"{plan.handle}r" 

242 

243 def _answer_handle(self, plan: SwarmTask) -> str: 

244 return ROOT_ANSWER if level_of(plan) == 0 else f"{plan.handle}s" 

245 

246 # ── What the engine asks ───────────────────────────────────────────────── 

247 

248 def seed(self, state: RunState) -> list[NewTask]: 

249 lead = state.roster.first(LEAD) 

250 assert lead is not None # the roster was checked at dispatch 

251 return [ 

252 NewTask( 

253 kind=TaskKind.plan, 

254 handle=ROOT_PLAN, 

255 title="Plan the work", 

256 role=LEAD, 

257 member=lead.handle, 

258 brief=TaskBrief(objective=state.run.task, extra={LEVEL_KEY: 0}), 

259 ) 

260 ] 

261 

262 def plan_spec(self, state: RunState, task: SwarmTask) -> PlanSpec: 

263 level = level_of(task) 

264 planner = self._member(state, task) 

265 return PlanSpec( 

266 planner=planner, 

267 members=tuple(self.assignable(state, task)), 

268 span=max(1, int(self.span(state.params, level))), 

269 part=None if level == 0 else TaskBrief.from_stored(task.brief), 

270 ) 

271 

272 def inputs(self, state: RunState, task: SwarmTask) -> list[SwarmTask]: 

273 unit = self._parent(state, task) 

274 if unit is None: 

275 return state.current_work() 

276 children = self._children(state, unit) 

277 if task.kind == TaskKind.review and level_of(unit) == 0: 

278 # Each of the lead's reviews reads its own round's pieces. 

279 children = [c for c in children if round_of(c) == round_of(task)] 

280 return [self.result_of(state, child) for child in children] 

281 

282 def part_of(self, state: RunState, task: SwarmTask) -> TaskBrief | None: 

283 unit = self._parent(state, task) 

284 if unit is None or level_of(unit) == 0: 

285 return None 

286 return TaskBrief.from_stored(unit.brief) 

287 

288 def more_work(self, state: RunState, task: SwarmTask) -> PlanSpec | None: 

289 unit = self._parent(state, task) 

290 if unit is None or level_of(unit) != 0: 

291 return None 

292 used = round_of(task) - 1 

293 if used >= MAX_ROUNDS: 

294 return None 

295 spec = self.plan_spec(state, unit) 

296 return replace( 

297 spec, 

298 rounds_left=MAX_ROUNDS - used, 

299 # What a new round could be given if this review asked for one: 

300 # its own share is not counted as held, being what it spends now. 

301 pool=self._pool(state, unit, review=True, but=task), 

302 # A piece of a further round is a whole team in a shape of teams. 

303 piece_turns=None 

304 if self.levels(state.params) <= 1 

305 else self._team_turns(state.params, 1), 

306 ) 

307 

308 def advance(self, state: RunState, finished: SwarmTask) -> Step: 

309 if finished.kind == TaskKind.plan: 

310 return self._after_plan(state, finished) 

311 if finished.kind == TaskKind.review: 

312 return self._after_review(state, finished) 

313 if finished.status != TaskStatus.done: 

314 return Step() 

315 unit = self._parent(state, finished) 

316 at_root = unit is not None and level_of(unit) == 0 

317 if finished.kind == TaskKind.synthesise: 

318 return Step(final=finished) if at_root else Step() 

319 if TaskBrief.from_stored(finished.brief).extra.get(FINAL_KEY) and at_root: 

320 return Step(final=finished) 

321 return Step() 

322 

323 # ── Money follows the work ─────────────────────────────────────────────── 

324 

325 def release(self, state: RunState, settled: SwarmTask) -> list[Release]: 

326 """Where what ``settled`` did not spend goes: to the work waiting in 

327 its unit, by estimate; and once its whole team has settled, what the 

328 team left to the work waiting beside it. Nothing moves while the run 

329 wraps up, and the plans and the run's answer give nothing: a plan's 

330 leftovers reach its pieces through their pool, and the answer's 

331 reserve is its own.""" 

332 if state.run.status == SwarmEnum.RunStatus.wrapping_up: 

333 return [] 

334 if settled.kind == TaskKind.plan: 

335 if level_of(settled) > 0 and ( 

336 settled.status != TaskStatus.done or not settled.result 

337 ): 

338 # A team that never planned: all of its budget moves on. 

339 return [self._close(state, settled)] 

340 return [] 

341 if settled.kind == TaskKind.route: 

342 return [] 

343 unit = self._parent(state, settled) 

344 if unit is None: 

345 return [] 

346 if settled.kind == TaskKind.synthesise and level_of(unit) == 0: 

347 return [] 

348 releases: list[Release] = [] 

349 left = budget.share_left(settled) 

350 waiting = self._waiting(state, unit, but=settled) 

351 if left >= budget.MIN_TASK_USD and waiting: 

352 releases.append(Release(settled, self._handout(waiting, left))) 

353 # A team all of whose work has now settled closes, and so may the 

354 # team above it, when this was the last of its work too. 

355 team: SwarmTask | None = unit 

356 while ( 

357 team is not None 

358 and level_of(team) > 0 

359 and not _closed(team) 

360 and self._team_done(state, team, settled) 

361 ): 

362 releases.append(self._close(state, team)) 

363 team = self._parent(state, team) 

364 return releases 

365 

366 def _waiting( 

367 self, state: RunState, unit: SwarmTask, *, but: SwarmTask | None = None 

368 ) -> list[SwarmTask]: 

369 """A unit's work that has not started: pieces, pieces done again and 

370 teams not yet planned — what unspent money goes to.""" 

371 return [ 

372 t 

373 for t in state.tasks 

374 if t.parent_id == unit.id 

375 and t is not but 

376 and t.status == TaskStatus.queued 

377 and ( 

378 t.kind == TaskKind.work 

379 or (t.kind == TaskKind.plan and team_budget(t) is not None) 

380 ) 

381 ] 

382 

383 @staticmethod 

384 def _handout( 

385 waiting: list[SwarmTask], usd: Decimal 

386 ) -> list[tuple[SwarmTask, Decimal]]: 

387 """``usd`` split between ``waiting`` by estimate.""" 

388 estimates = [budget.usd(t.estimate_usd) for t in waiting] 

389 return [ 

390 (task, share) 

391 for task, share in zip(waiting, budget.shares(estimates, usd)) 

392 if share > 0 

393 ] 

394 

395 def _subtree(self, state: RunState, plan: SwarmTask) -> list[SwarmTask]: 

396 """Every task under ``plan``, at any depth.""" 

397 found: list[SwarmTask] = [] 

398 frontier = [plan.id] 

399 while frontier: 

400 below = [t for t in state.tasks if t.parent_id in frontier] 

401 found += below 

402 frontier = [t.id for t in below] 

403 return found 

404 

405 def _team_done(self, state: RunState, team: SwarmTask, settled: SwarmTask) -> bool: 

406 """Whether ``team``'s plan and everything under it have settled — 

407 ``settled`` included, which is settling now.""" 

408 rows = [team, *self._subtree(state, team)] 

409 return all(t is settled or t.status in SETTLED for t in rows) 

410 

411 def _close(self, state: RunState, team: SwarmTask) -> Release: 

412 """What a settled team left of its budget, to the work waiting beside 

413 it — recorded even when nothing waits, so it is passed on once.""" 

414 whole = team_budget(team) or Decimal(0) 

415 spent = budget.usd(team.spent_usd) + sum( 

416 (budget.usd(t.spent_usd) for t in self._subtree(state, team)), 

417 Decimal(0), 

418 ) 

419 left = max(whole - spent, Decimal(0)) 

420 parent = self._parent(state, team) 

421 waiting = self._waiting(state, parent, but=team) if parent else [] 

422 to = ( 

423 self._handout(waiting, left) 

424 if waiting and left >= budget.MIN_TASK_USD 

425 else [] 

426 ) 

427 return Release(team, to) 

428 

429 def _pool( 

430 self, 

431 state: RunState, 

432 unit: SwarmTask, 

433 *, 

434 review: bool, 

435 fixed: Decimal = Decimal(0), 

436 but: SwarmTask | None = None, 

437 ) -> Decimal: 

438 """What a unit's new pieces may be given now: at the root, what the 

439 run has for work less what open tasks hold (and a further round's 

440 review share, with ``review``); in a team, its budget less what the 

441 team has spent and holds. ``fixed`` is held by the new tasks that 

442 bring their own share; ``but`` is a task not to count as holding.""" 

443 if level_of(unit) == 0: 

444 held = budget.held(t for t in state.tasks if t is not but) 

445 return budget.work_pool(state.run, held + fixed, review=review) 

446 rows = self._subtree(state, unit) 

447 spent = budget.usd(unit.spent_usd) + sum( 

448 (budget.usd(t.spent_usd) for t in rows), Decimal(0) 

449 ) 

450 held = budget.held(t for t in rows if t is not but) 

451 whole = team_budget(unit) or Decimal(0) 

452 return max(whole - spent - held - fixed, Decimal(0)) 

453 

454 # ── After a plan ───────────────────────────────────────────────────────── 

455 

456 def _after_plan(self, state: RunState, plan: SwarmTask) -> Step: 

457 if plan.status != TaskStatus.done or not plan.result: 

458 # A team that never planned: the review above reads it as missing. 

459 return Step() 

460 level = level_of(plan) 

461 spec = self.plan_spec(state, plan) 

462 allowed = {m.handle for m in spec.members} 

463 try: 

464 # As stored, whichever schema it was asked in: a follow-up's 

465 # lead may have said what each piece builds on. 

466 parsed = ReadPlan.model_validate(plan.result) 

467 except ValidationError: 

468 return Step(warnings=[f"The plan for “{plan.title}” could not be read."]) 

469 proposals = [p for p in parsed.tasks if p.assignee in allowed][: spec.span] 

470 ledger = {"facts": list(parsed.facts), "assumptions": list(parsed.assumptions)} 

471 if not proposals: 

472 who = ( 

473 "The lead's plan" 

474 if level == 0 

475 else f"{plan.agent_name}'s plan for “{plan.title}”" 

476 ) 

477 return Step(ledger=ledger, warnings=[f"{who} held no work."]) 

478 one = parsed.approach == Approach.one_agent or len(proposals) == 1 

479 pieces = self._pieces( 

480 state, plan, proposals[:1] if one else proposals, one=one, first=1 

481 ) 

482 step = Step(add=list(pieces), ledger=ledger) 

483 if level == 0: 

484 step.approve = True 

485 step.plan = _shown(parsed, pieces) 

486 result = pieces[0].handle 

487 if not one: 

488 review, answer = self._closing(state, plan, [p.handle for p in pieces]) 

489 step.add += [review, answer] 

490 result = answer.handle 

491 if level > 0: 

492 # The review above waits for what this team comes to. 

493 step.wait_also = { 

494 t.handle: [result] 

495 for t in state.tasks 

496 if t.kind == TaskKind.review and str(plan.id) in (t.depends_on or []) 

497 } 

498 whole = team_budget(plan) 

499 if whole is not None: 

500 # A piece done alone has no review or report to share with; 

501 # what the plan did not spend of its part goes to the pieces. 

502 kept = Decimal(0) if one else TEAM_REVIEW_SHARE + TEAM_ANSWER_SHARE 

503 step.pool = max( 

504 whole * (1 - kept) - budget.usd(plan.spent_usd), Decimal(0) 

505 ).quantize(_CENT) 

506 return step 

507 

508 def _pieces( 

509 self, 

510 state: RunState, 

511 plan: SwarmTask, 

512 proposals: list[ProposedTask], 

513 *, 

514 one: bool, 

515 first: int, 

516 round_no: int = 1, 

517 direct_after: bool = False, 

518 asked_by: str | None = None, 

519 ) -> list[NewTask]: 

520 """The pieces a plan (or a round of more work) asks for: work at the 

521 last level or for a plan of one piece, else teams of their own. 

522 ``first`` is the number the first takes; ``after`` names pieces of 

523 the same plan by place (``T1``…), or — for a round of more work — 

524 existing pieces by handle (``direct_after``).""" 

525 level = level_of(plan) 

526 params = state.params 

527 leaf = one or level + 1 >= self.levels(params) 

528 # Only the lead's plan may build on the previous request's pieces, 

529 # and only on the ones it was offered. 

530 earlier = set(thread.earlier_refs(state.run)) if level == 0 else set() 

531 handles = [self._child_handle(plan, first + i) for i in range(len(proposals))] 

532 by_place = {f"T{i + 1}": h for i, h in enumerate(handles)} 

533 made: list[NewTask] = [] 

534 for index, (handle, proposal) in enumerate(zip(handles, proposals)): 

535 member = state.roster.by_handle(proposal.assignee) 

536 brief = TaskBrief.from_proposal(proposal) 

537 if not member.spawn: 

538 # A fixed member keeps the role it was given. 

539 brief = replace(brief, specialism="") 

540 extra: dict[str, Any] = {} 

541 if round_no > 1: 

542 extra[ROUND_KEY] = round_no 

543 if asked_by: 

544 extra[ASKED_BY_KEY] = asked_by 

545 building = [ 

546 ref for ref in getattr(proposal, "builds_on", []) if ref in earlier 

547 ] 

548 if building: 

549 extra[thread.BUILDS_ON_KEY] = list(dict.fromkeys(building))[ 

550 : thread.MAX_BUILDS_ON 

551 ] 

552 if direct_after: 

553 after = tuple(proposal.after) 

554 else: 

555 # Only pieces earlier in the plan: a later one cannot be 

556 # needed first, and naming one would make a cycle. 

557 after = tuple( 

558 by_place[h] 

559 for h in proposal.after 

560 if h in by_place and handles.index(by_place[h]) < index 

561 ) 

562 common = { 

563 "handle": handle, 

564 "title": proposal.title.strip()[:255] or handle, 

565 "role": member.role, 

566 "member": member.handle, 

567 "parent": plan.handle, 

568 "depth": level + 1, 

569 **self.level_settings(params, member.role), 

570 } 

571 if leaf: 

572 if one: 

573 extra[FINAL_KEY] = True 

574 made.append( 

575 NewTask( 

576 kind=TaskKind.work, 

577 brief=_with_extra(brief, **extra) if extra else brief, 

578 after=() if one else after, 

579 **common, 

580 ) 

581 ) 

582 else: 

583 extra[LEVEL_KEY] = level + 1 

584 made.append( 

585 NewTask( 

586 kind=TaskKind.plan, 

587 brief=_with_extra(brief, **extra), 

588 team=True, 

589 turns=self._team_turns(params, level + 1), 

590 **common, 

591 ) 

592 ) 

593 return made 

594 

595 def _closing( 

596 self, state: RunState, plan: SwarmTask, after: list[str], round_no: int = 1 

597 ) -> tuple[NewTask, NewTask]: 

598 """A unit's review of its pieces, and its answer (or report) after it.""" 

599 level = level_of(plan) 

600 planner = self._member(state, plan) 

601 whole = team_budget(plan) if level > 0 else None 

602 part = TaskBrief.from_stored(plan.brief) 

603 name = plan.title if level > 0 else "" 

604 review = NewTask( 

605 kind=TaskKind.review, 

606 handle=self._review_handle(plan, round_no), 

607 title=f"Review “{name}”" if name else "Review the work", 

608 role=plan.role, 

609 member=planner.handle, 

610 brief=TaskBrief( 

611 objective=state.run.task if level == 0 else part.objective, 

612 extra={ROUND_KEY: round_no} if round_no > 1 else {}, 

613 ), 

614 after=tuple(after), 

615 parent=plan.handle, 

616 depth=level, 

617 budget_usd=(whole * TEAM_REVIEW_SHARE).quantize(_CENT) if whole else None, 

618 tier=plan.tier, 

619 cost_profile=plan.cost_profile, 

620 ) 

621 answer = NewTask( 

622 kind=TaskKind.synthesise, 

623 handle=self._answer_handle(plan), 

624 title=f"Report on “{name}”" if name else "Write the answer", 

625 role=plan.role, 

626 member=planner.handle, 

627 # A team's report is judged above against the part it was given. 

628 brief=replace(part, extra={}) 

629 if level > 0 

630 else TaskBrief(objective=state.run.task), 

631 after=(review.handle,), 

632 parent=plan.handle, 

633 depth=level, 

634 budget_usd=(whole * TEAM_ANSWER_SHARE).quantize(_CENT) if whole else None, 

635 tier=plan.tier, 

636 cost_profile=plan.cost_profile, 

637 ) 

638 return review, answer 

639 

640 def _team_turns(self, params: dict[str, Any], level: int) -> float: 

641 """A team at ``level``, in its manager's typical turns: its plan, 

642 review and report, and its pieces — work, or teams again.""" 

643 below = ( 

644 self._team_turns(params, level + 1) 

645 if level + 1 < self.levels(params) 

646 else PIECE_TURNS 

647 ) 

648 return 3 + int(self.span(params, level)) * below 

649 

650 # ── After a review ─────────────────────────────────────────────────────── 

651 

652 def _after_review(self, state: RunState, review_task: SwarmTask) -> Step: 

653 if review_task.status != TaskStatus.done or not review_task.result: 

654 return Step() 

655 unit = self._parent(state, review_task) 

656 if unit is None: 

657 return Step() 

658 result = review_task.result 

659 try: 

660 review = ( 

661 SwarmReviewRound.model_validate(result) 

662 if "next" in result 

663 else SwarmReview.model_validate(result) 

664 ) 

665 except ValidationError: 

666 # Nothing is sent back: the answer is written from what is done. 

667 return Step( 

668 warnings=[f"The review “{review_task.title}” could not be read."] 

669 ) 

670 ledger = {"facts": list(review.facts), "gaps": list(review.gaps)} 

671 answer_handle = self._answer_handle(unit) 

672 asked_by = str(review_task.id) 

673 added: list[NewTask] = [] 

674 for item in review.verdicts: 

675 if item.verdict != Verdict.redo: 

676 continue 

677 redo = self._redo(state, item.task, item.issue.strip(), asked_by) 

678 if redo is not None: 

679 added.append(redo) 

680 wait = [t.handle for t in added] 

681 rounds = False 

682 if isinstance(review, SwarmReviewRound) and review.next == Next.more_work: 

683 more = self._more_round(state, unit, review_task, review.more_work) 

684 added += more 

685 wait += [t.handle for t in more if t.kind == TaskKind.review] 

686 rounds = any(t.kind == TaskKind.review for t in more) 

687 # Pieces done again and a further round share what is free, never on 

688 # top of it; a report written again keeps the share it had. 

689 fixed = sum( 

690 (budget.usd(t.budget_usd) for t in added if t.budget_usd is not None), 

691 Decimal(0), 

692 ) 

693 return Step( 

694 add=added, 

695 wait_also={answer_handle: wait} if wait else {}, 

696 ledger=ledger, 

697 pool=self._pool(state, unit, review=rounds, fixed=fixed) if added else None, 

698 ) 

699 

700 def _redo( 

701 self, state: RunState, handle: str, note: str, asked_by: str = "" 

702 ) -> NewTask | None: 

703 """A piece sent back: a piece of work done again — with a share of 

704 what is free, as a new piece — or a team's report written again, 

705 within the share it had the first time. Once each.""" 

706 original = state.by_handle(handle) 

707 if original is None or original.status != TaskStatus.done: 

708 return None 

709 brief = TaskBrief.from_stored(original.brief) 

710 if brief.redoes: 

711 return None # sent back once already 

712 redo_handle = f"{original.handle}b" 

713 if state.by_handle(redo_handle) is not None: 

714 return None 

715 if original.kind not in (TaskKind.work, TaskKind.synthesise): 

716 return None 

717 member = self._member(state, original) 

718 extra = {k: v for k, v in brief.extra.items() if k not in _NOT_CARRIED} 

719 if asked_by: 

720 extra[ASKED_BY_KEY] = asked_by 

721 report = original.kind == TaskKind.synthesise 

722 return NewTask( 

723 kind=original.kind, 

724 handle=redo_handle, 

725 title=f"{original.title} (again)"[:255], 

726 role=original.role, 

727 member=member.handle if member else "", 

728 brief=replace( 

729 brief, review_note=note, redoes=str(original.id), extra=extra 

730 ), 

731 parent=self._parent(state, original).handle 

732 if self._parent(state, original) 

733 else None, 

734 depth=original.depth, 

735 budget_usd=original.budget_usd if report else None, 

736 estimate_usd=original.estimate_usd if report else None, 

737 tier=original.tier, 

738 cost_profile=original.cost_profile, 

739 ) 

740 

741 def _more_round( 

742 self, 

743 state: RunState, 

744 unit: SwarmTask, 

745 review_task: SwarmTask, 

746 proposals: list[ProposedTask], 

747 ) -> list[NewTask]: 

748 """Another round of work the lead asked for, and its review.""" 

749 spec = self.more_work(state, review_task) 

750 if spec is None or state.run.status == SwarmEnum.RunStatus.wrapping_up: 

751 return [] 

752 allowed = {m.handle for m in spec.members} 

753 chosen = [p for p in proposals if p.assignee in allowed][: spec.span] 

754 if not chosen: 

755 return [] 

756 round_no = round_of(review_task) + 1 

757 first = len(self._children(state, unit)) + 1 

758 pieces = self._pieces( 

759 state, 

760 unit, 

761 chosen, 

762 one=False, 

763 first=first, 

764 round_no=round_no, 

765 direct_after=True, 

766 asked_by=str(review_task.id), 

767 ) 

768 review, _ = self._closing(state, unit, [p.handle for p in pieces], round_no) 

769 return [*pieces, review] 

770 

771 

772def _shown(plan: SwarmPlan, pieces: list[NewTask]) -> dict: 

773 """The plan as a person approves it: the approach and each piece.""" 

774 return { 

775 "approach": plan.approach.value, 

776 "assumptions": list(plan.assumptions), 

777 "tasks": [ 

778 { 

779 "handle": task.handle, 

780 "title": task.title, 

781 "member": task.member, 

782 "after": list(task.after), 

783 **task.brief.stored(), 

784 } 

785 for task in pieces 

786 ], 

787 }