Coverage for app / services / decisions / sections.py: 97%

353 statements  

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

1"""The sections of a decision record — one class each, in reading order. 

2 

3Adding a section is one class here and one model in ``schema.py``. Each says 

4which kinds of turn it applies to and builds its part from the 

5``DecisionContext``; whatever a section cannot find it reports through its 

6``status`` and ``note`` rather than as an empty list, so a gap in the record 

7reads as a gap. A section that fails is ``unavailable`` on its own; the rest 

8of the record still renders. 

9""" 

10 

11from __future__ import annotations 

12 

13import logging 

14import re 

15from abc import ABC, abstractmethod 

16from decimal import Decimal 

17from typing import Any, ClassVar 

18 

19from app.db.postgres.crud_schemas import Schema 

20from app.db.postgres.enums import DecisionEnum, GovernanceEnum, MessageEnum 

21from app.db.postgres.models import Agent, TestCase, TestSuite, User 

22from app.services import attachments, web_search_summary 

23from app.services.swarms import thread as swarm_thread 

24from app.util import web_search_report 

25from app.services.decisions.context import DecisionContext 

26from app.services.decisions.schema import ( 

27 AnswerSection, 

28 CaseRef, 

29 Citation, 

30 ConfigurationSection, 

31 CostSection, 

32 HumanInputSection, 

33 LedgerEntry, 

34 ModelCall, 

35 ModelCallsSection, 

36 OutcomeRead, 

37 OutcomeSection, 

38 QualityCheckSection, 

39 ReadsSection, 

40 RecordRead, 

41 RequestSection, 

42 ReviewsSection, 

43 RulesSection, 

44 LaneStep, 

45 Step, 

46 StepsSection, 

47 ToolCall, 

48 ToolCallsSection, 

49 WebSearchRecord, 

50 WebSourcesSection, 

51 _Section, 

52) 

53 

54logger = logging.getLogger(__name__) 

55 

56Kind = DecisionEnum.Kind 

57Status = DecisionEnum.SectionStatus 

58 

59#: When every row a turn writes started carrying its id (migration 91). A 

60#: turn from before it has its rules and messages, and none of the rest. 

61THREADED_SINCE = "12 October 2026" 

62_BEFORE_THREADING = ( 

63 f"Not recorded by turn: the turn is from before {THREADED_SINCE}, when " 

64 "this started being filed under its id." 

65) 

66_UNREACHABLE = "svc-ai, which keeps this, could not be reached. Try again." 

67#: How much of a step's output the record carries. 

68STEP_PREVIEW_CHARS = 500 

69 

70 

71class SectionBuilder(ABC): 

72 key: ClassVar[str] 

73 title: ClassVar[str] 

74 #: The section's model in ``schema.py``; its ``key`` is this one's. 

75 model: ClassVar[type[_Section]] 

76 kinds: ClassVar[frozenset[Kind]] = frozenset(Kind) 

77 

78 @abstractmethod 

79 def build(self, ctx: DecisionContext) -> _Section: ... 

80 

81 

82_SECTIONS: list[SectionBuilder] = [] 

83 

84 

85def register(cls: type[SectionBuilder]) -> type[SectionBuilder]: 

86 _SECTIONS.append(cls()) 

87 return cls 

88 

89 

90def builders() -> tuple[SectionBuilder, ...]: 

91 return tuple(_SECTIONS) 

92 

93 

94def build_all(ctx: DecisionContext) -> list[_Section]: 

95 """Every section that applies to the turn, in reading order.""" 

96 built: list[_Section] = [] 

97 for builder in _SECTIONS: 

98 if ctx.kind not in builder.kinds: 

99 continue 

100 try: 

101 built.append(builder.build(ctx)) 

102 except Exception: 

103 logger.exception( 

104 "Decision %s: section %s could not be built", 

105 ctx.invocation_id, 

106 builder.key, 

107 ) 

108 built.append(_unavailable(builder)) 

109 return built 

110 

111 

112def _unavailable(builder: SectionBuilder) -> _Section: 

113 return builder.model( 

114 title=builder.title, 

115 status=Status.unavailable, 

116 note="This part of the record could not be read.", 

117 ) 

118 

119 

120def _value(enum_or_text: Any) -> str | None: 

121 if enum_or_text is None: 

122 return None 

123 return str(getattr(enum_or_text, "value", enum_or_text)) 

124 

125 

126def _is_model_chat(ctx: DecisionContext) -> bool: 

127 return ctx.conversation is not None and ctx.conversation.agent_id is None 

128 

129 

130# ── Sections ────────────────────────────────────────────────────────────────── 

131 

132 

133@register 

134class Request(SectionBuilder): 

135 key = "request" 

136 title = "Request" 

137 model = RequestSection 

138 

139 def build(self, ctx: DecisionContext) -> RequestSection: 

140 if ctx.kind == Kind.swarm_task: 

141 task = ctx.task 

142 brief = task.brief if isinstance(task.brief, dict) else {} 

143 note = ( 

144 "A task of a swarm run: the brief its lead wrote. The agent " 

145 "was also shown the team's task, the plan and what the team " 

146 "had established." 

147 ) 

148 given: list[dict[str, Any]] = [] 

149 run = ctx.swarm_run 

150 if run is not None and swarm_thread.view(run) is not None: 

151 # What it was given from the thread, derived again from the 

152 # earlier runs' rows, which do not change. 

153 documents = swarm_thread.documents_for(ctx.db, run, task) 

154 given = [ 

155 {"id": d.id, "name": d.name, "mime_type": d.mime_type} 

156 for d in ( 

157 *documents.previous, 

158 *documents.builds_on, 

159 *documents.older, 

160 ) 

161 ] 

162 note += ( 

163 f" It was request {run.thread_seq} of a thread: it was shown " 

164 "the earlier requests and how each went, and given the " 

165 "documents listed here from them." 

166 ) 

167 return RequestSection( 

168 title=self.title, 

169 prompt=brief.get("objective") or task.title, 

170 inputs=brief or None, 

171 attachments=given or None, 

172 note=note, 

173 ) 

174 if ctx.kind == Kind.skill_run: 

175 run = ctx.run 

176 return RequestSection( 

177 title=self.title, 

178 prompt=run.prompt, 

179 task=run.task, 

180 inputs=run.inputs or None, 

181 ) 

182 question = ctx.question 

183 if question is None: 

184 return RequestSection( 

185 title=self.title, 

186 status=Status.not_recorded, 

187 note="The question was not stored with this answer.", 

188 ) 

189 meta = question.meta if isinstance(question.meta, dict) else {} 

190 return RequestSection( 

191 title=self.title, 

192 prompt=question.content, 

193 # Under ``command``; a chat stored it as the whole meta until 

194 # 24 October 2026. 

195 command=attachments.command_of(meta), 

196 attachments=attachments.stored_refs(meta) or None, 

197 note=( 

198 "Stored after the policy rules ran: what they redacted is " 

199 "redacted here." 

200 ), 

201 ) 

202 

203 

204@register 

205class Answer(SectionBuilder): 

206 key = "answer" 

207 title = "Answer" 

208 model = AnswerSection 

209 

210 def build(self, ctx: DecisionContext) -> AnswerSection: 

211 if ctx.kind == Kind.swarm_task: 

212 task = ctx.task 

213 return AnswerSection( 

214 title=self.title, 

215 outcome=task.status, 

216 content=task.output, 

217 outputs=task.result if isinstance(task.result, dict) else None, 

218 error=task.error, 

219 ) 

220 if ctx.kind == Kind.skill_run: 

221 run = ctx.run 

222 return AnswerSection( 

223 title=self.title, 

224 outcome=run.status, 

225 content=run.output, 

226 outputs=run.outputs, 

227 error=run.error, 

228 ) 

229 answer = ctx.answer 

230 if answer is None: 

231 return AnswerSection( 

232 title=self.title, 

233 status=Status.not_recorded, 

234 note="The answer was not stored under this turn's id.", 

235 ) 

236 meta = ctx.answer_meta 

237 outcome = _value(answer.status) or MessageEnum.Status.COMPLETED.value 

238 withheld = ( 

239 meta.get("withheld") if isinstance(meta.get("withheld"), dict) else None 

240 ) 

241 return AnswerSection( 

242 title=self.title, 

243 outcome=outcome, 

244 content=answer.content, 

245 stopped=bool(meta.get("stopped")), 

246 blocked_by=meta.get("rule") 

247 if outcome == MessageEnum.Status.BLOCKED.value 

248 else None, 

249 withheld_by=withheld.get("rule") if withheld else None, 

250 # The answer the rule withheld is not here: its review item, for 

251 # those who may review it, is the one place it is kept. 

252 note=( 

253 "An Output rule withheld this answer: this is its message. " 

254 + ( 

255 "The answer went to review." 

256 if withheld.get("review") 

257 else "The answer was not kept." 

258 ) 

259 if withheld 

260 else None 

261 ), 

262 ) 

263 

264 

265@register 

266class Configuration(SectionBuilder): 

267 key = "configuration" 

268 title = "Configuration" 

269 model = ConfigurationSection 

270 

271 def build(self, ctx: DecisionContext) -> ConfigurationSection: 

272 if ctx.kind == Kind.swarm_task: 

273 task, run = ctx.task, ctx.swarm_run 

274 provider, model_name = traced_model(ctx) 

275 swarm = getattr(run, "swarm_name", None) or "a swarm" 

276 lighter = " on a lighter model" if task.tier == "lighter" else "" 

277 return ConfigurationSection( 

278 title=self.title, 

279 agent_id=task.agent_id, 

280 agent_name=task.agent_name, 

281 provider=provider, 

282 model_name=model_name, 

283 cost_profile=task.cost_profile, 

284 note=f"Its {task.role} in “{swarm}”{lighter}.", 

285 ) 

286 if ctx.kind == Kind.skill_run: 

287 run = ctx.run 

288 return ConfigurationSection( 

289 title=self.title, 

290 skill_id=run.skill_id, 

291 skill_name=run.skill_name, 

292 skill_version=run.skill_version, 

293 note=None 

294 if run.skill_version is not None 

295 else "The skill's revision was not recorded on this run.", 

296 ) 

297 meta = ctx.answer_meta 

298 conversation = ctx.conversation 

299 agent_id = getattr(conversation, "agent_id", None) 

300 agent = ctx.db.get(Agent, agent_id) if agent_id else None 

301 provider, model_name = meta.get("provider"), meta.get("model_name") 

302 if model_name is None and _is_model_chat(ctx): 

303 provider, model_name = traced_model(ctx) 

304 note = None 

305 if agent_id and meta.get("agent_version") is None: 

306 note = "The agent's revision was not recorded on this answer." 

307 lighter = meta.get("lighter_model") 

308 return ConfigurationSection( 

309 title=self.title, 

310 agent_id=agent_id, 

311 agent_name=getattr(agent, "name", None), 

312 agent_version=meta.get("agent_version"), 

313 ai_model_id=getattr(conversation, "ai_model_id", None), 

314 provider=provider, 

315 model_name=model_name, 

316 # Stored only when it was not the default (``_persist_conversation``). 

317 cost_profile=(meta.get("cost_profile") or "thorough") if agent_id else None, 

318 lighter_model=lighter if isinstance(lighter, dict) else None, 

319 note=note, 

320 ) 

321 

322 

323def traced_model(ctx: DecisionContext) -> tuple[str | None, str | None]: 

324 """The model svc-ai's first traced invocation names, for a direct prompt 

325 (its messages name none).""" 

326 for invocation in (ctx.trace or {}).get("invocations") or []: 

327 name = invocation.get("model_display_name") or invocation.get("model_name") 

328 if name: 

329 return invocation.get("provider"), name 

330 return None, None 

331 

332 

333@register 

334class Rules(SectionBuilder): 

335 key = "rules" 

336 title = "Rules" 

337 model = RulesSection 

338 

339 def build(self, ctx: DecisionContext) -> RulesSection: 

340 events = [ 

341 Schema.GovernanceActivity.Read.model_validate(event) for event in ctx.events 

342 ] 

343 outcomes = {outcome.value: 0 for outcome in GovernanceEnum.Outcome} 

344 for event in events: 

345 outcomes[_value(event.outcome)] += 1 

346 return RulesSection( 

347 title=self.title, 

348 events=events, 

349 outcomes=outcomes, 

350 status=Status.recorded if events else Status.empty, 

351 note=None if events else "No rule applied to this turn.", 

352 ) 

353 

354 

355@register 

356class WebSources(SectionBuilder): 

357 key = "web_sources" 

358 title = "Web sources" 

359 model = WebSourcesSection 

360 

361 def build(self, ctx: DecisionContext) -> WebSourcesSection: 

362 trace = ctx.trace 

363 if trace is None: 

364 return WebSourcesSection( 

365 title=self.title, status=Status.unavailable, note=_UNREACHABLE 

366 ) 

367 searches = [ 

368 WebSearchRecord( 

369 created_at=call.get("created_at"), 

370 query=_query_of(call.get("input_args")), 

371 report=call.get("report") 

372 if isinstance(call.get("report"), dict) 

373 else None, 

374 ) 

375 for call in trace.get("tool_calls") or [] 

376 if call.get("tool_name") == "web_search" 

377 ] 

378 if not searches: 

379 if not ctx.threaded: 

380 return WebSourcesSection( 

381 title=self.title, 

382 status=Status.not_recorded, 

383 note=_BEFORE_THREADING, 

384 ) 

385 return WebSourcesSection( 

386 title=self.title, 

387 status=Status.empty, 

388 note="The agent did not search the web.", 

389 ) 

390 reports = web_search_report.reports([s.report for s in searches]) 

391 if not reports: 

392 return WebSourcesSection( 

393 title=self.title, 

394 searches=searches, 

395 note=( 

396 "These searches were recorded before each kept its report " 

397 f"({REPORTS_SINCE}): what each found is under Tool calls." 

398 ), 

399 ) 

400 return WebSourcesSection( 

401 title=self.title, 

402 searches=searches, 

403 summary=web_search_summary.summarise(reports, _tools_rows(ctx)), 

404 ) 

405 

406 

407#: When a web search started keeping its report (svc-ai migration 32). 

408REPORTS_SINCE = "25 October 2026" 

409 

410 

411def _query_of(args: Any) -> str | None: 

412 query = args.get("query") if isinstance(args, dict) else None 

413 return str(query) if query else None 

414 

415 

416def _tools_rows(ctx: DecisionContext) -> list[dict[str, Any]]: 

417 """The turn's Tools rows, as the summary reads an evaluation.""" 

418 return [ 

419 { 

420 "rule_id": event.rule_id, 

421 "rule": event.rule_name, 

422 "layer": event.layer, 

423 "outcome": event.outcome, 

424 "detail": event.detail or {}, 

425 } 

426 for event in ctx.events 

427 if _value(event.phase) == GovernanceEnum.Phase.input.value 

428 ] 

429 

430 

431@register 

432class QualityCheck(SectionBuilder): 

433 key = "quality_check" 

434 title = "Quality check" 

435 model = QualityCheckSection 

436 kinds = frozenset({Kind.answer}) 

437 

438 def build(self, ctx: DecisionContext) -> QualityCheckSection: 

439 if _is_model_chat(ctx): 

440 return QualityCheckSection( 

441 title=self.title, 

442 status=Status.empty, 

443 note="A direct model prompt has no quality check.", 

444 ) 

445 meta = ctx.answer_meta 

446 if not meta.get("eval_outcome"): 

447 blocked = _value(getattr(ctx.answer, "status", None)) == ( 

448 MessageEnum.Status.BLOCKED.value 

449 ) 

450 return QualityCheckSection( 

451 title=self.title, 

452 status=Status.empty if blocked else Status.not_recorded, 

453 note="Blocked before the model answered." 

454 if blocked 

455 else ( 

456 "No quality check was stored with this answer. A turn that " 

457 "failed ends before it, and the HTTP prompt endpoint does " 

458 "not store one yet." 

459 ), 

460 ) 

461 score = meta.get("eval_score") 

462 skipped = meta.get("eval_outcome") == "skipped" 

463 return QualityCheckSection( 

464 title=self.title, 

465 outcome=meta.get("eval_outcome"), 

466 score=float(score) if score is not None else None, 

467 critique=meta.get("eval_critique"), 

468 gaps=[str(g) for g in meta.get("eval_gaps") or []], 

469 note=( 

470 "Not checked: the agent's cost profile answers a request " 

471 "triage calls simple without a quality check." 

472 if skipped 

473 else "The score is uncalibrated: a reading, not a confidence." 

474 ), 

475 ) 

476 

477 

478@register 

479class HumanInput(SectionBuilder): 

480 key = "human_input" 

481 title = "Human input" 

482 model = HumanInputSection 

483 

484 def build(self, ctx: DecisionContext) -> HumanInputSection: 

485 if ctx.kind == Kind.skill_run: 

486 run = ctx.run 

487 exchanges = [r for r in run.responses or [] if isinstance(r, dict)] 

488 pending = run.interrupt if run.status == "awaiting_input" else None 

489 elif ctx.kind == Kind.swarm_task: 

490 task = ctx.task 

491 exchanges = [r for r in task.responses or [] if isinstance(r, dict)] 

492 pending = task.questions if task.status == "awaiting_input" else None 

493 else: 

494 exchanges = [ 

495 r for r in ctx.answer_meta.get("hitl") or [] if isinstance(r, dict) 

496 ] 

497 pending = None 

498 found = bool(exchanges or pending) 

499 return HumanInputSection( 

500 title=self.title, 

501 exchanges=exchanges, 

502 pending=pending if isinstance(pending, dict) else None, 

503 status=Status.recorded if found else Status.empty, 

504 note=None if found else "The turn did not stop for a person.", 

505 ) 

506 

507 

508@register 

509class Reviews(SectionBuilder): 

510 key = "reviews" 

511 title = "Reviews" 

512 model = ReviewsSection 

513 

514 def build(self, ctx: DecisionContext) -> ReviewsSection: 

515 flags = [Schema.Review.Read.model_validate(flag) for flag in ctx.flags] 

516 if flags: 

517 return ReviewsSection(title=self.title, flags=flags) 

518 if not ctx.threaded: 

519 return ReviewsSection( 

520 title=self.title, status=Status.not_recorded, note=_BEFORE_THREADING 

521 ) 

522 return ReviewsSection( 

523 title=self.title, 

524 status=Status.empty, 

525 note="Nothing was flagged for review.", 

526 ) 

527 

528 

529@register 

530class Outcome(SectionBuilder): 

531 key = "outcome" 

532 title = "Verdict" 

533 model = OutcomeSection 

534 

535 def build(self, ctx: DecisionContext) -> OutcomeSection: 

536 from app.services.decisions import outcomes 

537 

538 rows = outcomes.history(ctx.db, ctx.invocation_id) 

539 cases = ( 

540 ctx.db.query(TestCase.id, TestCase.test_suite_id, TestCase.created_at) 

541 .filter(TestCase.source_invocation_id == ctx.invocation_id) 

542 .order_by(TestCase.created_at.asc()) 

543 .all() 

544 ) 

545 if not rows and not cases: 

546 return OutcomeSection( 

547 title=self.title, 

548 status=Status.empty, 

549 note="Nobody has given a verdict on this yet.", 

550 ) 

551 names = _user_names(ctx, {row.actor_user_id for row in rows}) 

552 suites = _suite_names(ctx, {suite_id for _, suite_id, _ in cases}) 

553 given = [ 

554 OutcomeRead.model_validate(row).model_copy( 

555 update={"actor_name": names.get(row.actor_user_id)} 

556 ) 

557 for row in rows 

558 ] 

559 return OutcomeSection( 

560 title=self.title, 

561 current=given[-1] if given else None, 

562 history=given, 

563 cases=[ 

564 CaseRef( 

565 case_id=case_id, 

566 test_suite_id=suite_id, 

567 test_suite_name=suites.get(suite_id), 

568 created_at=created_at, 

569 ) 

570 for case_id, suite_id, created_at in cases 

571 ], 

572 ) 

573 

574 

575def _user_names(ctx: DecisionContext, ids: set) -> dict: 

576 if not ids: 

577 return {} 

578 users = ctx.db.query(User).filter(User.id.in_(ids)).all() 

579 return {u.id: u.name or u.email for u in users} 

580 

581 

582def _suite_names(ctx: DecisionContext, ids: set) -> dict: 

583 if not ids: 

584 return {} 

585 rows = ( 

586 ctx.db.query(TestSuite.id, TestSuite.name).filter(TestSuite.id.in_(ids)).all() 

587 ) 

588 return dict(rows) 

589 

590 

591@register 

592class Steps(SectionBuilder): 

593 key = "steps" 

594 title = "Steps" 

595 model = StepsSection 

596 

597 def build(self, ctx: DecisionContext) -> StepsSection: 

598 if ctx.kind == Kind.swarm_task: 

599 return StepsSection( 

600 title=self.title, 

601 status=Status.not_recorded, 

602 note="A swarm task keeps no record of its graph's steps: its " 

603 "model and tool calls are below, and its place in the team on " 

604 "the run's page.", 

605 ) 

606 if ctx.kind == Kind.skill_run: 

607 steps = [_run_step(s) for s in ctx.run.steps or [] if isinstance(s, dict)] 

608 return StepsSection( 

609 title=self.title, 

610 steps=steps, 

611 status=Status.recorded if steps else Status.empty, 

612 note=None if steps else "The run stopped before any node ran.", 

613 ) 

614 if _is_model_chat(ctx): 

615 return StepsSection( 

616 title=self.title, 

617 status=Status.empty, 

618 note="A direct model prompt runs no graph: its call is under " 

619 "Model calls.", 

620 ) 

621 steps = _trace_steps(getattr(ctx.answer, "trace", None)) 

622 if steps: 

623 return StepsSection(title=self.title, steps=steps) 

624 return StepsSection( 

625 title=self.title, 

626 status=Status.not_recorded, 

627 note="This answer's steps were not stored. The HTTP prompt " 

628 "endpoint stores only the rules a turn ran.", 

629 ) 

630 

631 

632def _run_step(step: dict[str, Any]) -> Step: 

633 output = step.get("output") 

634 return Step( 

635 node_id=str(step.get("node_id") or ""), 

636 kind="system" if step.get("kind") == "system" else "node", 

637 input_tokens=step.get("input_tokens"), 

638 output_tokens=step.get("output_tokens"), 

639 error=bool(step.get("error")), 

640 output_preview=str(output)[:STEP_PREVIEW_CHARS] if output else None, 

641 tools=[ 

642 str(call.get("name")) 

643 for call in step.get("tool_calls") or [] 

644 if isinstance(call, dict) and call.get("name") 

645 ], 

646 ) 

647 

648 

649#: A knowledge lane's node (svc-ai ``graph.LANE_NODE_IDS``: 

650#: ``__<kind>_retrieval__``), and the join that packs the lanes. 

651_LANE_NODE = re.compile(r"^__([a-z]+)_retrieval__$") 

652_RETRIEVAL_JOIN = "__retrieval_join__" 

653#: Not lanes, though named like them: the web, the tools, and the one 

654#: internal node before the lanes. 

655_NOT_LANES = frozenset({"external", "tool", "internal"}) 

656 

657 

658def _count(value: Any) -> int: 

659 return value if isinstance(value, int) and value > 0 else 0 

660 

661 

662def _lane_step(result: Any) -> LaneStep | None: 

663 """A lane's frame (``system_node_result``) as its step reads it.""" 

664 if not isinstance(result, dict) or not isinstance(result.get("category"), str): 

665 return None 

666 queries = result.get("queries") 

667 kbs = result.get("kb_ids") 

668 return LaneStep( 

669 category=result["category"], 

670 role=str(result.get("role") or ""), 

671 knowledge_bases=len(kbs) if isinstance(kbs, list) else 0, 

672 queries=len(queries) if isinstance(queries, list) else 0, 

673 found=_count(result.get("found")), 

674 judged=_count(result.get("judged")), 

675 ruled_out=_count(result.get("ruled_out")), 

676 out_of_window=_count(result.get("out_of_window")), 

677 handed_on=_count(result.get("handed_on")), 

678 judge_failure=str(result.get("judge_failure") or "") or None, 

679 failure=str(result.get("error") or "") or None, 

680 ) 

681 

682 

683def _trace_steps(trace: Any) -> list[Step]: 

684 """One step per ``node_end`` frame of a stored chat trace, with the tools 

685 its node called before it ended. A knowledge lane's step carries what it 

686 did (its frame) and what the join packed of it (the join's frame).""" 

687 steps: list[Step] = [] 

688 tools: dict[str, list[str]] = {} 

689 lanes: dict[str, LaneStep] = {} 

690 unpacked: list[LaneStep] = [] 

691 for event in trace if isinstance(trace, list) else []: 

692 if not isinstance(event, dict): 

693 continue 

694 node_id = str(event.get("node_id") or "") 

695 lane_kind = _LANE_NODE.match(node_id) 

696 if event.get("type") == "tool_call" and event.get("tool"): 

697 tools.setdefault(node_id, []).append(str(event["tool"])) 

698 elif event.get("type") == "system_node_result": 

699 if lane_kind and lane_kind.group(1) not in _NOT_LANES: 

700 lane = _lane_step(event.get("result")) 

701 if lane is not None: 

702 lanes[node_id] = lane 

703 elif node_id == _RETRIEVAL_JOIN: 

704 result = event.get("result") 

705 packing = result.get("lanes") if isinstance(result, dict) else None 

706 for lane in unpacked: 

707 entry = (packing or {}).get(lane.category) 

708 if isinstance(entry, dict): 

709 lane.packed = _count(entry.get("packed")) 

710 unpacked = [] 

711 elif event.get("type") == "node_end": 

712 tokens = ( 

713 event.get("tokens") if isinstance(event.get("tokens"), dict) else {} 

714 ) 

715 preview = event.get("output_preview") 

716 steps.append( 

717 Step( 

718 node_id=node_id, 

719 kind="system" if event.get("is_system_node") else "node", 

720 model_name=event.get("model_name"), 

721 provider=event.get("provider"), 

722 input_tokens=tokens.get("input"), 

723 output_tokens=tokens.get("output"), 

724 duration_ms=event.get("duration_ms"), 

725 error=event.get("status") == "error", 

726 output_preview=str(preview)[:STEP_PREVIEW_CHARS] 

727 if preview 

728 else None, 

729 tools=tools.pop(node_id, []), 

730 history_turns_omitted=event.get("history_turns_omitted") 

731 if isinstance(event.get("history_turns_omitted"), int) 

732 else None, 

733 lane=lanes.pop(node_id, None), 

734 ) 

735 ) 

736 if steps[-1].lane is not None: 

737 unpacked.append(steps[-1].lane) 

738 return steps 

739 

740 

741@register 

742class ModelCalls(SectionBuilder): 

743 key = "model_calls" 

744 title = "Model calls" 

745 model = ModelCallsSection 

746 

747 def build(self, ctx: DecisionContext) -> ModelCallsSection: 

748 trace = ctx.trace 

749 if trace is None: 

750 return ModelCallsSection( 

751 title=self.title, status=Status.unavailable, note=_UNREACHABLE 

752 ) 

753 calls = [ 

754 ModelCall( 

755 purpose=invocation.get("purpose"), 

756 **{ 

757 field: call.get(field) 

758 for field in ModelCall.model_fields 

759 if field != "purpose" and call.get(field) is not None 

760 }, 

761 ) 

762 for invocation in trace.get("invocations") or [] 

763 for call in invocation.get("calls") or [] 

764 ] 

765 if calls: 

766 return ModelCallsSection(title=self.title, calls=calls) 

767 if not ctx.threaded: 

768 return ModelCallsSection( 

769 title=self.title, status=Status.not_recorded, note=_BEFORE_THREADING 

770 ) 

771 return ModelCallsSection( 

772 title=self.title, status=Status.empty, note="No model was called." 

773 ) 

774 

775 

776@register 

777class ToolCalls(SectionBuilder): 

778 key = "tool_calls" 

779 title = "Tool calls" 

780 model = ToolCallsSection 

781 

782 def build(self, ctx: DecisionContext) -> ToolCallsSection: 

783 trace = ctx.trace 

784 if trace is None: 

785 return ToolCallsSection( 

786 title=self.title, status=Status.unavailable, note=_UNREACHABLE 

787 ) 

788 calls = [ 

789 ToolCall( 

790 tool_name=call.get("tool_name") or "", 

791 created_at=call.get("created_at"), 

792 input_args=call.get("input_args"), 

793 output=call.get("output"), 

794 truncated=bool(call.get("truncated")), 

795 latency_ms=call.get("latency_ms"), 

796 status=call.get("status") or "", 

797 error_detail=call.get("error_detail"), 

798 citations=[ 

799 Citation.model_validate(c) for c in call.get("citations") or [] 

800 ], 

801 report=call.get("report") 

802 if isinstance(call.get("report"), dict) 

803 else None, 

804 ) 

805 for call in trace.get("tool_calls") or [] 

806 ] 

807 if calls: 

808 return ToolCallsSection(title=self.title, calls=calls) 

809 if not ctx.threaded: 

810 return ToolCallsSection( 

811 title=self.title, status=Status.not_recorded, note=_BEFORE_THREADING 

812 ) 

813 return ToolCallsSection( 

814 title=self.title, status=Status.empty, note="No tool was called." 

815 ) 

816 

817 

818@register 

819class Cost(SectionBuilder): 

820 key = "cost" 

821 title = "Cost" 

822 model = CostSection 

823 

824 def build(self, ctx: DecisionContext) -> CostSection: 

825 rows = ctx.ledger 

826 if not rows: 

827 if not ctx.threaded: 

828 return CostSection( 

829 title=self.title, status=Status.not_recorded, note=_BEFORE_THREADING 

830 ) 

831 return CostSection( 

832 title=self.title, 

833 status=Status.empty, 

834 note="Nothing reached a model, so nothing was spent.", 

835 ) 

836 entries = [ 

837 LedgerEntry( 

838 occurred_at=row.occurred_at, 

839 execution_type=row.execution_type, 

840 outcome=_value(row.outcome) or "", 

841 input_tokens=row.input_tokens or 0, 

842 output_tokens=row.output_tokens or 0, 

843 estimated_cost_usd=float(row.estimated_cost_usd) 

844 if row.estimated_cost_usd is not None 

845 else None, 

846 llm_calls=row.llm_calls or 0, 

847 unpriced_calls=row.unpriced_calls or 0, 

848 latency_ms=row.latency_ms, 

849 ) 

850 for row in rows 

851 ] 

852 priced = [ 

853 Decimal(str(row.estimated_cost_usd)) 

854 for row in rows 

855 if row.estimated_cost_usd is not None 

856 ] 

857 complete = all( 

858 row.estimated_cost_usd is not None and not row.unpriced_calls 

859 for row in rows 

860 ) 

861 return CostSection( 

862 title=self.title, 

863 entries=entries, 

864 cost_usd=float(sum(priced)) if priced else None, 

865 complete=complete, 

866 input_tokens=sum(e.input_tokens for e in entries), 

867 output_tokens=sum(e.output_tokens for e in entries), 

868 note=None 

869 if complete 

870 else "Some calls could not be priced: the cost is a lower bound.", 

871 ) 

872 

873 

874@register 

875class Reads(SectionBuilder): 

876 key = "reads" 

877 title = "Reviewer reads" 

878 model = ReadsSection 

879 

880 def build(self, ctx: DecisionContext) -> ReadsSection: 

881 logged = ctx.reads 

882 if not logged: 

883 return ReadsSection( 

884 title=self.title, 

885 status=Status.empty, 

886 note="Nobody other than its owner has opened this record.", 

887 ) 

888 names = _user_names(ctx, {row.reader_user_id for row in logged}) 

889 return ReadsSection( 

890 title=self.title, 

891 reads=[ 

892 RecordRead( 

893 reader_user_id=row.reader_user_id, 

894 reader_name=names.get(row.reader_user_id), 

895 access=row.access, 

896 flag_id=row.flag_id, 

897 read_at=row.read_at, 

898 ) 

899 for row in logged 

900 ], 

901 )