Coverage for app / services / scenarios / checks.py: 99%

223 statements  

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

1"""What a scenario expected, checked against what happened. 

2 

3One class per expectation, registered by the field of ``schema.TurnExpect``, 

4``schema.AgentExpect`` or ``schema.SwarmRunExpect`` it reads (held to them 

5by the tests). Each reads the turn's, the agent's or the swarm run's export 

6(``export.py``) and says what it expected, 

7what it found, and whether they agree. A failed check is recorded, never 

8fatal: the run is evidence for a person (or Claude) to read, not a gate. 

9""" 

10 

11from __future__ import annotations 

12 

13from abc import ABC, abstractmethod 

14from dataclasses import asdict, dataclass 

15from typing import Any, ClassVar 

16 

17 

18@dataclass(frozen=True) 

19class CheckResult: 

20 check: str 

21 expected: Any 

22 actual: Any 

23 passed: bool 

24 

25 def wire(self) -> dict[str, Any]: 

26 return asdict(self) 

27 

28 

29class Check(ABC): 

30 #: The expectation field it reads. 

31 key: ClassVar[str] 

32 

33 @abstractmethod 

34 def run(self, expected: Any, subject: dict[str, Any]) -> CheckResult: ... 

35 

36 

37TURN_CHECKS: dict[str, Check] = {} 

38AGENT_CHECKS: dict[str, Check] = {} 

39SWARM_CHECKS: dict[str, Check] = {} 

40 

41 

42def _turn(cls: type[Check]) -> type[Check]: 

43 TURN_CHECKS[cls.key] = cls() 

44 return cls 

45 

46 

47def _agent(cls: type[Check]) -> type[Check]: 

48 AGENT_CHECKS[cls.key] = cls() 

49 return cls 

50 

51 

52def _swarm(cls: type[Check]) -> type[Check]: 

53 SWARM_CHECKS[cls.key] = cls() 

54 return cls 

55 

56 

57def _values(items: Any) -> list[str]: 

58 return sorted(str(getattr(i, "value", i)) for i in items or []) 

59 

60 

61# ── A turn ──────────────────────────────────────────────────────────────────── 

62 

63 

64@_turn 

65class Profile(Check): 

66 key = "profile" 

67 

68 def run(self, expected, turn): 

69 actual = turn.get("profile") 

70 return CheckResult(self.key, expected, actual, actual == expected) 

71 

72 

73@_turn 

74class Searched(Check): 

75 """Every kind named was searched (a lane of it ran).""" 

76 

77 key = "searched" 

78 

79 def run(self, expected, turn): 

80 want, ran = _values(expected), sorted(turn.get("searched") or []) 

81 return CheckResult(self.key, want, ran, set(want) <= set(ran)) 

82 

83 

84@_turn 

85class NotSearched(Check): 

86 key = "not_searched" 

87 

88 def run(self, expected, turn): 

89 avoid, ran = _values(expected), sorted(turn.get("searched") or []) 

90 return CheckResult(self.key, avoid, ran, not set(avoid) & set(ran)) 

91 

92 

93@_turn 

94class Cites(Check): 

95 """Every repository named was cited by the answer.""" 

96 

97 key = "cites" 

98 

99 def run(self, expected, turn): 

100 want = sorted(expected or []) 

101 cited = sorted(turn.get("cited_repositories") or []) 

102 return CheckResult(self.key, want, cited, set(want) <= set(cited)) 

103 

104 

105@_turn 

106class NotCites(Check): 

107 key = "not_cites" 

108 

109 def run(self, expected, turn): 

110 avoid = sorted(expected or []) 

111 cited = sorted(turn.get("cited_repositories") or []) 

112 return CheckResult(self.key, avoid, cited, not set(avoid) & set(cited)) 

113 

114 

115@_turn 

116class Quality(Check): 

117 """The quality check's outcome is one of those named.""" 

118 

119 key = "quality" 

120 

121 def run(self, expected, turn): 

122 allowed = _values(expected) 

123 outcome = (turn.get("quality") or {}).get("outcome") 

124 return CheckResult(self.key, allowed, outcome, outcome in allowed) 

125 

126 

127def _worked(call: dict[str, Any]) -> bool: 

128 """A tool call that did its work: not an error, and not the tool's own 

129 refusal, which svc-ai's built-ins word ``[<tool>] …`` and the frame reads 

130 as a success.""" 

131 tool = str(call.get("tool") or "") 

132 preview = str(call.get("output_preview") or "") 

133 return call.get("status") == "success" and not preview.startswith(f"[{tool}]") 

134 

135 

136@_turn 

137class Tools(Check): 

138 """Every tool named was called and did its work.""" 

139 

140 key = "tools" 

141 

142 def run(self, expected, turn): 

143 want = sorted(expected or []) 

144 worked = sorted({c.get("tool") for c in turn.get("tools") or [] if _worked(c)}) 

145 return CheckResult(self.key, want, worked, set(want) <= set(worked)) 

146 

147 

148@_turn 

149class NotTools(Check): 

150 """No tool named was called at all.""" 

151 

152 key = "not_tools" 

153 

154 def run(self, expected, turn): 

155 avoid = sorted(expected or []) 

156 called = sorted({c.get("tool") for c in turn.get("tools") or []}) 

157 return CheckResult(self.key, avoid, called, not set(avoid) & set(called)) 

158 

159 

160@_turn 

161class Artifacts(Check): 

162 """The answer holds a fence of each kind named, well-formed and made by 

163 its render tool; the actual names each kind's problem when not.""" 

164 

165 key = "artifacts" 

166 

167 def run(self, expected, turn): 

168 want = _values(expected) 

169 held = turn.get("artifacts") or [] 

170 actual: dict[str, str] = {} 

171 for kind in want: 

172 of_kind = [a for a in held if a.get("kind") == kind] 

173 good = [a for a in of_kind if a.get("valid") and a.get("from_tool")] 

174 if good: 

175 actual[kind] = "ok" 

176 elif not of_kind: 

177 actual[kind] = "missing" 

178 elif not any(a.get("valid") for a in of_kind): 

179 actual[kind] = "invalid: " + "; ".join(of_kind[0].get("problems") or []) 

180 else: 

181 actual[kind] = "written by hand, not by its tool" 

182 passed = all(v == "ok" for v in actual.values()) 

183 return CheckResult(self.key, want, actual, passed) 

184 

185 

186@_turn 

187class NotArtifacts(Check): 

188 key = "not_artifacts" 

189 

190 def run(self, expected, turn): 

191 avoid = _values(expected) 

192 held = sorted({a.get("kind") for a in turn.get("artifacts") or []}) 

193 return CheckResult(self.key, avoid, held, not set(avoid) & set(held)) 

194 

195 

196@_turn 

197class Document(Check): 

198 """The answer's first document renders to a PDF of at least the pages 

199 asked, drawing at least the images asked (or every image it links) and 

200 a visual of each kind asked.""" 

201 

202 key = "document" 

203 

204 def run(self, expected, turn): 

205 want = {k: v for k, v in (expected or {}).items() if v not in (None, False, [])} 

206 found = (turn.get("documents") or [None])[0] 

207 if found is None: 

208 return CheckResult(self.key, want, "no document", False) 

209 pdf = found.get("pdf") or {} 

210 images = found.get("images") or {} 

211 drawn = { 

212 row["kind"]: row.get("drawn") or 0 

213 for row in found.get("visuals") or [] 

214 if isinstance(row, dict) and row.get("kind") 

215 } 

216 actual = { 

217 "pdf": pdf.get("error") is None, 

218 "pages": pdf.get("pages"), 

219 "images_embedded": images.get("embedded"), 

220 "images_linked": images.get("linked"), 

221 **({"pdf_error": pdf["error"]} if pdf.get("error") else {}), 

222 **({"images_missing": images["missing"]} if images.get("missing") else {}), 

223 **({"visuals_drawn": drawn} if want.get("visuals") or drawn else {}), 

224 } 

225 passed = ( 

226 (not want.get("pdf") or actual["pdf"]) 

227 and ( 

228 want.get("min_pages") is None 

229 or (actual["pages"] or 0) >= want["min_pages"] 

230 ) 

231 and ( 

232 want.get("min_images") is None 

233 or (actual["images_embedded"] or 0) >= want["min_images"] 

234 ) 

235 and (not want.get("all_images") or not images.get("missing")) 

236 and all(drawn.get(kind, 0) >= 1 for kind in want.get("visuals") or []) 

237 ) 

238 return CheckResult(self.key, want, actual, bool(passed)) 

239 

240 

241@_turn 

242class Asks(Check): 

243 """True: the turn paused to ask the person. False: it did not.""" 

244 

245 key = "asks" 

246 

247 def run(self, expected, turn): 

248 asked = bool(turn.get("pauses")) 

249 return CheckResult(self.key, expected, asked, asked == expected) 

250 

251 

252@_turn 

253class Command(Check): 

254 """The person's message ran the chat command target named, by slug.""" 

255 

256 key = "command" 

257 

258 def run(self, expected, turn): 

259 actual = (turn.get("command") or {}).get("slug") 

260 return CheckResult(self.key, expected, actual, actual == expected) 

261 

262 

263# ── An agent ────────────────────────────────────────────────────────────────── 

264 

265 

266@_agent 

267class SuggestsFirst(Check): 

268 """For each kind named, the built-in its context panel suggested first, 

269 before any turn.""" 

270 

271 key = "suggests_first" 

272 

273 def run(self, expected, agent): 

274 want = {str(getattr(k, "value", k)): v for k, v in (expected or {}).items()} 

275 readings = { 

276 r.get("category"): r for r in agent.get("context_before") or [] if r 

277 } 

278 actual = { 

279 kind: next( 

280 ( 

281 s.get("name") 

282 for s in readings.get(kind, {}).get("suggestions") or [] 

283 ), 

284 None, 

285 ) 

286 for kind in want 

287 } 

288 return CheckResult(self.key, want, actual, actual == want) 

289 

290 

291@_agent 

292class Recommends(Check): 

293 """Each recommendation kind named was offered for the agent once its 

294 turns were done.""" 

295 

296 key = "recommends" 

297 

298 def run(self, expected, agent): 

299 want = sorted(expected or []) 

300 offered = sorted({r.get("kind") for r in agent.get("recommendations") or []}) 

301 return CheckResult(self.key, want, offered, set(want) <= set(offered)) 

302 

303 

304# ── A swarm run ────────────────────────────────────────────────────────────── 

305 

306 

307@_swarm 

308class SwarmStatus(Check): 

309 key = "status" 

310 

311 def run(self, expected, run): 

312 want = _values(expected) 

313 return CheckResult(self.key, want, run.get("status"), run.get("status") in want) 

314 

315 

316@_swarm 

317class Answered(Check): 

318 key = "answered" 

319 

320 def run(self, expected, run): 

321 found = bool(run.get("answered")) 

322 return CheckResult(self.key, expected, found, found is bool(expected)) 

323 

324 

325@_swarm 

326class Approach(Check): 

327 key = "approach" 

328 

329 def run(self, expected, run): 

330 want = str(getattr(expected, "value", expected)) 

331 return CheckResult( 

332 self.key, want, run.get("approach"), run.get("approach") == want 

333 ) 

334 

335 

336@_swarm 

337class MinPieces(Check): 

338 key = "min_pieces" 

339 

340 def run(self, expected, run): 

341 found = int(run.get("pieces") or 0) 

342 return CheckResult(self.key, expected, found, found >= expected) 

343 

344 

345@_swarm 

346class MaxPieces(Check): 

347 key = "max_pieces" 

348 

349 def run(self, expected, run): 

350 found = int(run.get("pieces") or 0) 

351 return CheckResult(self.key, expected, found, found <= expected) 

352 

353 

354@_swarm 

355class Kinds(Check): 

356 key = "kinds" 

357 

358 def run(self, expected, run): 

359 want = _values(expected) 

360 held = sorted(run.get("kinds") or []) 

361 return CheckResult(self.key, want, held, set(want) <= set(held)) 

362 

363 

364@_swarm 

365class MaxCost(Check): 

366 key = "max_cost_usd" 

367 

368 def run(self, expected, run): 

369 spent = (run.get("cost") or {}).get("spent_usd") 

370 passed = isinstance(spent, (int, float)) and spent <= expected 

371 return CheckResult(self.key, expected, spent, passed) 

372 

373 

374@_swarm 

375class CitesPages(Check): 

376 """Its answer cites a page or a document a piece read, not only the 

377 team's own pieces (``export.source_key``).""" 

378 

379 key = "cites_pages" 

380 

381 def run(self, expected, run): 

382 pages = int((run.get("cites") or {}).get("pages") or 0) 

383 return CheckResult(self.key, expected, pages, (pages > 0) == bool(expected)) 

384 

385 

386@_swarm 

387class MinBuildsOn(Check): 

388 """A follow-up's plan builds pieces on the request before's: how many 

389 of its pieces name one.""" 

390 

391 key = "min_builds_on" 

392 

393 def run(self, expected, run): 

394 building = len(run.get("builds_on") or {}) 

395 return CheckResult(self.key, expected, building, building >= expected) 

396 

397 

398@_swarm 

399class CitesCarried(Check): 

400 """A follow-up's answer cites a source an earlier request of its thread 

401 cited: carried through, not lost.""" 

402 

403 key = "cites_carried" 

404 

405 def run(self, expected, run): 

406 carried = int((run.get("cites") or {}).get("carried") or 0) 

407 return CheckResult(self.key, expected, carried, (carried > 0) == bool(expected)) 

408 

409 

410def _run(checks: dict[str, Check], expect: Any, subject: dict) -> list[dict]: 

411 fields = expect.model_dump() if hasattr(expect, "model_dump") else dict(expect) 

412 return [ 

413 checks[key].run(value, subject).wire() 

414 for key, value in fields.items() 

415 if value not in (None, [], {}) and key in checks 

416 ] 

417 

418 

419def check_turn(expect: Any, turn: dict[str, Any]) -> list[dict]: 

420 """Every expectation the turn states, checked; none stated, none run.""" 

421 return _run(TURN_CHECKS, expect, turn) 

422 

423 

424def check_agent(expect: Any, agent: dict[str, Any]) -> list[dict]: 

425 return _run(AGENT_CHECKS, expect, agent) 

426 

427 

428def check_swarm_run(expect: Any, run: dict[str, Any]) -> list[dict]: 

429 return _run(SWARM_CHECKS, expect, run)