Coverage for app / services / scenarios / export.py: 85%
259 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"""A scenario run's export: everything each turn did, in one JSON document
2(schema ``EXPORT_SCHEMA``; docs/guides/scenario-runs.md#the-export).
4Each turn is read from what it sent (``driver.TurnRun``: the trace frames,
5svc-ai's terminal frame) and from what it stored — its answer and meta, its
6retrieval record, its citations, its decision record — so a reader sees
7triage's choice, each lane's funnel, what was retrieved and what was cited
8side by side, without a database. What the answer delivered is read too:
9each chart, diagram, map or document fence checked (``artifacts.py``), each
10document rendered to PDF as its download is, the pauses it asked through,
11and the chat command it ran. Strings are capped, never dropped, and tokens
12are counted, not kept.
14Only the run's owner's own turns go in: the decision record is assembled
15for them as its owner, as ``GET /app/decisions/{id}`` would.
16"""
18from __future__ import annotations
20import dataclasses
21import logging
22from datetime import datetime
23from enum import Enum
24from typing import Any
25from uuid import UUID
27from pydantic import BaseModel
28from sqlalchemy.orm import Session
30from app.db.postgres.enums import MessageEnum
31from app.db.postgres.models import (
32 ChatMessage,
33 KnowledgeCitation,
34 KnowledgeRetrieval,
35 KnowledgeTurn,
36 User,
37)
38from app.services.scenarios import artifacts
39from app.services.scenarios.checks import check_agent, check_swarm_run, check_turn
40from app.services.scenarios.driver import TurnRun
41from app.util.time import utc_isoformat
43logger = logging.getLogger(__name__)
45EXPORT_SCHEMA = 1
46#: The longest a string in the trace is kept.
47TRACE_STRING_CHARS = 2000
48#: The longest a retrieved passage's text is kept.
49SNIPPET_CHARS = 300
50#: The longest a tool call's arguments and output are kept.
51TOOL_CHARS = 1000
53GATE_NODE = "__gate__"
54JOIN_NODE = "__retrieval_join__"
55PLAN_NODE = "__knowledge_plan__"
56#: svc-ai's lane nodes, ``__<kind>_retrieval__``; the web, tool and older
57#: internal nodes are named alike and are no lanes.
58_NOT_LANES = frozenset({"external", "tool", "internal"})
61def jsonable(value: Any) -> Any:
62 """``value`` as JSON: dataclasses and models as objects, enums as their
63 values, ids as strings, times with their offset."""
64 if isinstance(value, BaseModel):
65 return value.model_dump(mode="json")
66 if dataclasses.is_dataclass(value) and not isinstance(value, type):
67 return {
68 f.name: jsonable(getattr(value, f.name)) for f in dataclasses.fields(value)
69 }
70 if isinstance(value, Enum):
71 return value.value
72 if isinstance(value, UUID):
73 return str(value)
74 if isinstance(value, datetime):
75 return utc_isoformat(value)
76 if isinstance(value, dict):
77 return {str(jsonable(k)): jsonable(v) for k, v in value.items()}
78 if isinstance(value, (list, tuple, set, frozenset)):
79 return [jsonable(v) for v in value]
80 return value
83def capped(value: Any, limit: int) -> Any:
84 """``value`` with every string longer than ``limit`` cut, saying how much
85 was left out."""
86 if isinstance(value, str):
87 if len(value) <= limit:
88 return value
89 return f"{value[:limit]}… [{len(value) - limit} more characters]"
90 if isinstance(value, dict):
91 return {k: capped(v, limit) for k, v in value.items()}
92 if isinstance(value, list):
93 return [capped(v, limit) for v in value]
94 return value
97def _result(frames: list[dict], node_id: str) -> dict | None:
98 """The last ``system_node_result`` a node sent, as its ``result``."""
99 for frame in reversed(frames):
100 if (
101 frame.get("type") == "system_node_result"
102 and frame.get("node_id") == node_id
103 ):
104 result = frame.get("result")
105 return result if isinstance(result, dict) else None
106 return None
109def _lane_kind(node_id: str) -> str | None:
110 if node_id.startswith("__") and node_id.endswith("_retrieval__"):
111 kind = node_id[2 : -len("_retrieval__")]
112 return None if kind in _NOT_LANES else kind
113 return None
116def lanes(frames: list[dict]) -> list[dict]:
117 """Each lane that ran (its ``system_node_result``), in order, with its
118 node and pass."""
119 out = []
120 for frame in frames:
121 node_id = str(frame.get("node_id") or "")
122 if frame.get("type") != "system_node_result" or not _lane_kind(node_id):
123 continue
124 result = frame.get("result")
125 if isinstance(result, dict):
126 out.append({"node_id": node_id, "pass": frame.get("pass"), **result})
127 return out
130def _answer(db: Session, run: TurnRun) -> ChatMessage | None:
131 """The answer the turn stored: the one its ``response`` frame names, else
132 (a blocked or failed turn) its conversation's newest."""
133 response = run.last("response")
134 if response and response.get("message_id"):
135 try:
136 message = db.get(ChatMessage, UUID(str(response["message_id"])))
137 except ValueError:
138 message = None
139 if message is not None:
140 return message
141 conversation_id = run.conversation_id
142 if conversation_id is None:
143 return None
144 return (
145 db.query(ChatMessage)
146 .filter(
147 ChatMessage.conversation_id == conversation_id,
148 ChatMessage.role == MessageEnum.Role.ASSISTANT,
149 )
150 .order_by(ChatMessage.sent_at.desc())
151 .first()
152 )
155def _status(run: TurnRun, answer: ChatMessage | None) -> str:
156 meta = (answer.meta or {}) if answer is not None else {}
157 if run.crashed:
158 return "crashed"
159 if meta.get("stopped") or run.timed_out:
160 return "stopped"
161 if answer is not None:
162 return str(getattr(answer.status, "value", answer.status) or "completed")
163 return "error" if run.last("error") else "unknown"
166def _retrieval_record(db: Session, message_id: UUID) -> dict | None:
167 turn = (
168 db.query(KnowledgeTurn).filter(KnowledgeTurn.message_id == message_id).first()
169 )
170 if turn is None:
171 return None
172 retrievals = (
173 db.query(KnowledgeRetrieval).filter(KnowledgeRetrieval.turn_id == turn.id).all()
174 )
175 keep = (
176 "query",
177 "live",
178 "complexity",
179 "profile",
180 "searched",
181 "nothing_relevant",
182 "came_up_short",
183 "gaps",
184 "unresolved",
185 "web_hosts",
186 "scoped_out",
187 )
188 return {
189 **{field: jsonable(getattr(turn, field)) for field in keep},
190 "retrievals": [
191 {
192 "knowledge_id": str(r.knowledge_id),
193 "repository": _built_in_name(r.knowledge_id),
194 **{
195 field: jsonable(getattr(r, field))
196 for field in (
197 "category",
198 "role",
199 "found",
200 "kept",
201 "ruled_out",
202 "out_of_window",
203 "tool_searches",
204 )
205 },
206 }
207 for r in retrievals
208 ],
209 }
212def _built_in_name(knowledge_id: UUID | None) -> str | None:
213 from app.services.system_resources import knowledge as built_in
215 entry = built_in.of_source(knowledge_id)
216 return entry.name if entry is not None else None
219def _cited(db: Session, message_id: UUID) -> tuple[list[dict], list[str]]:
220 """The answer's citations record, and the built-in repositories it
221 cited by name."""
222 rows = (
223 db.query(KnowledgeCitation)
224 .filter(KnowledgeCitation.message_id == message_id)
225 .all()
226 )
227 cited = [
228 {
229 "knowledge_id": str(r.knowledge_id),
230 "document_id": str(r.document_id) if r.document_id else None,
231 "repository": _built_in_name(r.knowledge_id),
232 "tool": r.tool,
233 }
234 for r in rows
235 ]
236 names = sorted({c["repository"] for c in cited if c["repository"]})
237 return cited, names
240def _decision(db: Session, invocation_id: UUID | None, user: User) -> Any:
241 """The turn's decision record, read as its owner; None when it is not
242 theirs or cannot be read."""
243 if invocation_id is None:
244 return None
245 from app.services import decisions
247 try:
248 ctx = decisions.locate(db, invocation_id)
249 if ctx is None or ctx.owner_user_id != user.id:
250 return None
251 return decisions.assemble(ctx).model_dump(mode="json")
252 except Exception: # noqa: BLE001 — the rest of the turn still exports
253 logger.warning("Decision record %s could not be assembled", invocation_id)
254 return {"unavailable": True}
257def _request(db: Session, answer: ChatMessage | None) -> ChatMessage | None:
258 """The person's message the answer replies to: the one its turn wrote."""
259 if answer is None:
260 return None
261 query = db.query(ChatMessage).filter(
262 ChatMessage.conversation_id == answer.conversation_id,
263 ChatMessage.role == MessageEnum.Role.USER,
264 )
265 if answer.invocation_id is not None:
266 mine = query.filter(ChatMessage.invocation_id == answer.invocation_id).first()
267 if mine is not None:
268 return mine
269 return (
270 query.filter(ChatMessage.sent_at <= answer.sent_at)
271 .order_by(ChatMessage.sent_at.desc())
272 .first()
273 )
276def _pdf(
277 document: dict[str, Any], answer: ChatMessage
278) -> tuple[dict[str, Any], list[dict[str, Any]] | None]:
279 """``document`` rendered as the conversation's PDF route renders it:
280 its size, its pages, or why it did not render — and what it drew, None
281 when it did not render."""
282 from app.services import ai_client
283 from app.services import documents as documents_service
285 try:
286 rendered = ai_client.render_document(
287 document,
288 footer=documents_service.message_footer(answer.conversation, answer),
289 generated_at=documents_service.generated_at(answer.sent_at),
290 )
291 except ai_client.DocumentRejected as exc:
292 failed = {"bytes": None, "pages": None, "error": f"rejected: {exc}"[:500]}
293 return failed, None
294 except ai_client.AIServiceError:
295 return {
296 "bytes": None,
297 "pages": None,
298 "error": "svc-ai could not render it",
299 }, None
300 pages = artifacts.pdf_pages(rendered.pdf)
301 return {
302 "bytes": len(rendered.pdf),
303 "pages": pages,
304 "error": None if pages else "not a PDF this can read",
305 }, rendered.visuals
308def documents(answer: ChatMessage | None) -> list[dict[str, Any]]:
309 """Each ```document in the answer: its title, the images its text links
310 against those it embedded, its visuals by kind against those its PDF
311 drew, and its PDF."""
312 if answer is None:
313 return []
314 from app.services import documents as documents_service
316 out = []
317 for document in documents_service.document_fences(answer.content):
318 pdf, drawn = _pdf(document, answer)
319 out.append(
320 {
321 "title": document.get("title"),
322 "images": artifacts.images_of(document),
323 "visuals": artifacts.visuals_of(document, drawn),
324 "pdf": pdf,
325 }
326 )
327 return out
330def hitl(meta: dict[str, Any]) -> list[dict[str, Any]]:
331 """Each pause the turn asked through, as its answer recorded it."""
332 return [
333 {
334 "kind": record.get("kind"),
335 "source": record.get("source"),
336 "outcome": record.get("outcome"),
337 "questions": len(record.get("questions") or []),
338 "waited_ms": record.get("waited_ms"),
339 }
340 for record in meta.get("hitl") or []
341 if isinstance(record, dict)
342 ]
345def command(request: ChatMessage | None) -> dict[str, Any] | None:
346 """The chat command the person's message ran, with its target's slug."""
347 from app.services.attachments import command_of
349 record = command_of(request.meta) if request is not None else None
350 if not record:
351 return None
352 words = str(record.get("line") or "").split()
353 return {
354 **{
355 k: record.get(k)
356 for k in ("line", "action", "kind", "target_name", "inputs", "request")
357 },
358 "slug": words[2] if len(words) > 2 else None,
359 }
362def turn_export(
363 db: Session,
364 run: TurnRun,
365 *,
366 user: User,
367 conversation: str,
368 index: int,
369 prompt: str,
370 expect: Any,
371) -> dict[str, Any]:
372 """One turn, as the export holds it."""
373 answer = _answer(db, run)
374 meta = (answer.meta or {}) if answer is not None else {}
375 response = run.last("response") or {}
376 error = run.last("error")
377 gate = _result(run.frames, GATE_NODE) or {}
378 mix = (
379 gate.get("knowledge_mix") if isinstance(gate.get("knowledge_mix"), dict) else {}
380 )
381 ran = lanes(run.frames)
382 cited, cited_repositories = _cited(db, answer.id) if answer else ([], [])
383 invocation_id = answer.invocation_id if answer is not None else None
384 terminal = [
385 capped(
386 {k: v for k, v in f.items() if k not in ("output", "citations")},
387 TRACE_STRING_CHARS,
388 )
389 for f in run.terminal
390 ]
391 retrieved = [
392 capped(c, SNIPPET_CHARS)
393 for f in run.terminal
394 for c in (f.get("citations") or [])
395 if isinstance(c, dict)
396 ]
397 tools = [capped(f, TOOL_CHARS) for f in run.frames if f.get("type") == "tool_call"]
398 turn = {
399 "conversation": conversation,
400 "index": index,
401 "prompt": prompt,
402 "status": _status(run, answer),
403 "error": (error or {}).get("message") or run.crashed,
404 "error_code": (error or {}).get("code"),
405 "started_at": run.started_at,
406 "duration_ms": run.duration_ms,
407 "tokens_streamed": run.tokens,
408 "pauses": run.pauses,
409 "conversation_id": str(run.conversation_id) if run.conversation_id else None,
410 "message_id": str(answer.id) if answer is not None else None,
411 "invocation_id": str(invocation_id) if invocation_id else None,
412 "answer": answer.content if answer is not None else response.get("response"),
413 "model": {
414 "name": meta.get("model_name") or response.get("model_name"),
415 "provider": meta.get("provider") or response.get("provider"),
416 "lighter_model": meta.get("lighter_model"),
417 },
418 "quality": {
419 "outcome": meta.get("eval_outcome"),
420 "score": meta.get("eval_score"),
421 "critique": meta.get("eval_critique"),
422 "gaps": meta.get("eval_gaps"),
423 "set_aside": meta.get("eval_set_aside"),
424 },
425 "cost": {
426 "usd": response.get("cost_usd"),
427 "unpriced_calls": response.get("unpriced_calls"),
428 },
429 "triage": capped(gate, TRACE_STRING_CHARS),
430 "profile": mix.get("profile"),
431 "knowledge_plan": capped(_result(run.frames, PLAN_NODE), TRACE_STRING_CHARS),
432 "lanes": capped(ran, TRACE_STRING_CHARS),
433 "searched": sorted({lane["category"] for lane in ran if lane.get("category")}),
434 "join": capped(_result(run.frames, JOIN_NODE), TRACE_STRING_CHARS),
435 "cited_sources": capped(meta.get("cited_sources") or [], TRACE_STRING_CHARS),
436 "citations": cited,
437 "cited_repositories": cited_repositories,
438 "retrieved": retrieved,
439 "web_search": meta.get("web_search"),
440 "tools": tools,
441 "artifacts": artifacts.inventory(
442 answer.content if answer is not None else None, tools
443 ),
444 "documents": documents(answer),
445 "hitl": hitl(meta),
446 "command": command(_request(db, answer)),
447 "terminal": terminal,
448 "knowledge_record": _retrieval_record(db, answer.id) if answer else None,
449 "decision": _decision(db, invocation_id, user),
450 "trace": capped(run.frames, TRACE_STRING_CHARS),
451 }
452 if not turn["cost"]["usd"] and invocation_id:
453 from app.services import usage as usage_service
455 figures = usage_service.turn_cost_fields(db, invocation_id)
456 turn["cost"] = {
457 "usd": figures.get("cost_usd"),
458 "unpriced_calls": figures.get("unpriced_calls"),
459 }
460 turn["checks"] = check_turn(expect, turn)
461 return turn
464def agent_context(db: Session, agent: Any, ws: Any, viewer: User) -> list[dict] | None:
465 """What the agent's context panel shows (``agent_context``): each kind,
466 its state and its suggestions. None when it cannot be read."""
467 from app.services import agent_context as context_service
469 try:
470 inputs = context_service.AgentContextInputs(
471 db=db, agent=agent, ws=ws, viewer=viewer
472 )
473 return jsonable(context_service.read_all(inputs))
474 except Exception: # noqa: BLE001 — a snapshot never fails the run
475 logger.warning(
476 "Agent context for %s could not be read", getattr(agent, "id", None)
477 )
478 db.rollback()
479 return None
482def recommendations(
483 db: Session, ws: Any, viewer: User, *, agent_id: UUID | None = None
484) -> dict[str, Any]:
485 """What the workspace's (or one agent's) recommendations offer now."""
486 from app.services.knowledge import recommendations as service
488 try:
489 result = service.recommend(db, ws, viewer, agent_id=agent_id)
490 return {"items": jsonable(result.items), "unavailable": result.unavailable}
491 except Exception: # noqa: BLE001 — a snapshot never fails the run
492 logger.warning("Recommendations could not be read for a scenario run")
493 db.rollback()
494 return {"items": [], "unavailable": {"all": "could not be read"}}
497def agent_export(spec: Any, agent_id: UUID, **snapshots: Any) -> dict[str, Any]:
498 """One agent, as the export holds it, with its checks."""
499 agent = {
500 "key": spec.key,
501 "id": str(agent_id),
502 "name": spec.name,
503 "model": spec.model,
504 "cost_profile": getattr(spec.cost_profile, "value", spec.cost_profile),
505 "clarify_scope": spec.clarify_scope,
506 "repositories": list(spec.repositories),
507 **snapshots,
508 }
509 agent["recommendations"] = (snapshots.get("recommendations_after") or {}).get(
510 "items", []
511 )
512 agent["checks"] = check_agent(spec.expect, agent)
513 return agent
516#: A swarm run's answer, as exported.
517SWARM_ANSWER_CHARS = 20000
520#: The tool svc-ai names a cited attached document by (svc-ai
521#: ``util/attachments.TOOL``): a swarm's own piece or earlier answer, not a
522#: source it read.
523ATTACHMENT_TOOL = "attachment"
526def source_key(citation: dict[str, Any]) -> str | None:
527 """What makes two cited sources one: the page's address (case, a
528 trailing slash and a fragment aside), else the document; None for an
529 attached document or a source named only by its title."""
530 if not isinstance(citation, dict) or citation.get("tool") == ATTACHMENT_TOOL:
531 return None
532 url = str(citation.get("url") or "").strip()
533 if url.startswith(("http://", "https://")):
534 return "url:" + url.split("#", 1)[0].rstrip("/").lower()
535 document = str(citation.get("document_id") or "")
536 return f"doc:{document}" if document else None
539def source_keys(run: Any) -> set[str]:
540 """Every source a run cited: its answer's and each task's."""
541 cited = [*(run.citations or [])]
542 for task in run.tasks or []:
543 cited.extend(task.citations or [])
544 return {key for c in cited if (key := source_key(c))}
547def thread_documents(db: Any, run: Any) -> dict[str, list[str]]:
548 """The documents from earlier requests each of a follow-up's tasks was
549 given, by name (``swarms.thread.documents_for``, as its job was built);
550 empty for a first request."""
551 from app.services.swarms import thread
553 if thread.view(run) is None:
554 return {}
555 given: dict[str, list[str]] = {}
556 for task in sorted(run.tasks or [], key=lambda t: t.seq):
557 documents = thread.documents_for(db, run, task)
558 names = [
559 d.name
560 for d in (*documents.previous, *documents.builds_on, *documents.older)
561 ]
562 if names:
563 given[task.handle] = names
564 return given
567def swarm_run_export(
568 run: Any,
569 *,
570 swarm: str,
571 index: int,
572 task: str,
573 expect: Any,
574 duration_ms: int | None,
575 follow_up: int | None = None,
576 given: dict[str, list[str]] | None = None,
577 carried: set[str] | None = None,
578) -> dict[str, Any]:
579 """One swarm run as a reviewer reads it: how it ended, how its lead
580 planned, every task with who did it, what it cost and what it said it
581 could not do — and the checks its file stated.
583 A follow-up (``follow_up``, its number after the run it follows) says
584 where it is in its thread, which earlier pieces each new piece builds
585 on, the earlier documents each task was given (``given``), and which of
586 its answer's sources the thread had cited before (``carried``)."""
587 from app.db.postgres.enums import SwarmEnum
588 from app.services.swarms import thread
589 from app.services.swarms.schemas import TaskBrief
591 kind = SwarmEnum.TaskKind
592 tasks = sorted(run.tasks or [], key=lambda t: t.seq)
593 by_id = {str(t.id): t.handle for t in tasks}
594 plan = run.plan if isinstance(run.plan, dict) else {}
595 pieces = [
596 t
597 for t in tasks
598 if t.kind in (kind.work, kind.plan)
599 and (t.depth or 0) == 1
600 and t.status != SwarmEnum.TaskStatus.cancelled
601 and not TaskBrief.from_stored(t.brief).redoes
602 ]
603 calls = int(run.llm_calls or 0)
604 unpriced = int(run.unpriced_calls or 0)
605 exported = {
606 "swarm": swarm,
607 "index": index,
608 "task": task,
609 "run_id": str(run.id),
610 "status": str(run.status),
611 "answered": str(run.status) in ("completed", "partial"),
612 "wrap_up_reason": run.wrap_up_reason,
613 "error": run.error,
614 "approach": plan.get("approach"),
615 "pieces": len(pieces),
616 "kinds": sorted({str(t.kind) for t in tasks}),
617 "tasks": [
618 {
619 "handle": t.handle,
620 "kind": str(t.kind),
621 "title": t.title,
622 "role": t.role,
623 "agent": t.agent_name,
624 "status": str(t.status),
625 "after": [by_id[d] for d in t.depends_on or [] if d in by_id],
626 "spent_usd": float(t.spent_usd or 0),
627 "error": t.error,
628 }
629 for t in tasks
630 ],
631 "ledger": jsonable(run.ledger or {}),
632 "warnings": list(run.warnings or []),
633 "answer": capped(run.output or "", SWARM_ANSWER_CHARS),
634 "cost": {
635 "usd": float(run.cost_usd) if calls > unpriced else None,
636 "spent_usd": float(run.spent_usd or 0),
637 "llm_calls": calls,
638 "unpriced_calls": unpriced,
639 },
640 "duration_ms": duration_ms,
641 "follow_up": follow_up,
642 "thread": {
643 "seq": int(run.thread_seq or 1),
644 "parent_run_id": str(run.parent_run_id) if run.parent_run_id else None,
645 },
646 "builds_on": {
647 t.handle: list(refs) for t in tasks if (refs := thread.builds_on(t))
648 },
649 "given": given or {},
650 "citations": [
651 {
652 key: c.get(key)
653 for key in ("marker", "title", "url", "tool", "kind")
654 if c.get(key) is not None
655 }
656 for c in run.citations or []
657 if isinstance(c, dict)
658 ],
659 "cites": {
660 "pages": sum(1 for c in run.citations or [] if source_key(c)),
661 "carried": sum(
662 1
663 for c in run.citations or []
664 if (k := source_key(c)) and k in (carried or set())
665 ),
666 },
667 }
668 exported["checks"] = check_swarm_run(expect, exported)
669 return exported
672def swarm_run_label(exported: dict[str, Any]) -> str:
673 """Where a swarm run sits in the file: ``swarm team run 1 follow-up 2``."""
674 label = f"swarm {exported['swarm']} run {exported['index'] + 1}"
675 return (
676 f"{label} follow-up {exported['follow_up']}"
677 if exported.get("follow_up")
678 else label
679 )
682def summary(
683 turns: list[dict], agents: list[dict], swarm_runs: list[dict] | None = None
684) -> dict[str, Any]:
685 """The run at a glance: turns by status, checks, cost, time."""
686 swarm_runs = swarm_runs or []
687 statuses: dict[str, int] = {}
688 for turn in turns:
689 statuses[turn["status"]] = statuses.get(turn["status"], 0) + 1
690 checks = (
691 [
692 {"where": f"{t['conversation']} turn {t['index'] + 1}", **c}
693 for t in turns
694 for c in t.get("checks", [])
695 ]
696 + [
697 {"where": f"agent {a['key']}", **c}
698 for a in agents
699 for c in a.get("checks", [])
700 ]
701 + [
702 {"where": swarm_run_label(r), **c}
703 for r in swarm_runs
704 for c in r.get("checks", [])
705 ]
706 )
707 costs = [
708 t["cost"]["usd"]
709 for t in turns
710 if isinstance(t["cost"].get("usd"), (int, float))
711 ] + [
712 r["cost"]["usd"]
713 for r in swarm_runs
714 if isinstance(r["cost"].get("usd"), (int, float))
715 ]
716 return {
717 "turns": len(turns),
718 "swarm_runs": len(swarm_runs),
719 "by_status": statuses,
720 "checks": len(checks),
721 "checks_passed": sum(1 for c in checks if c["passed"]),
722 "checks_failed": [
723 {k: c[k] for k in ("where", "check", "expected", "actual")}
724 for c in checks
725 if not c["passed"]
726 ],
727 "cost_usd": round(sum(costs), 6) if costs else None,
728 "unpriced_turns": sum(1 for t in turns if t["cost"].get("unpriced_calls")),
729 "duration_ms": sum(t.get("duration_ms") or 0 for t in [*turns, *swarm_runs]),
730 }
733def filename(name: str, created: datetime | None) -> str:
734 """``scenario-run-builtin-knowledge-20261027-1405.json``."""
735 import re
737 slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:60] or "scenario"
738 stamp = f"-{created:%Y%m%d-%H%M}" if created is not None else ""
739 return f"scenario-run-{slug}{stamp}.json"