convergent-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of convergent-cli might be problematic. Click here for more details.

Files changed (83) hide show
  1. convergent_cli/__init__.py +1 -0
  2. convergent_cli/auth.py +227 -0
  3. convergent_cli/build_context.py +225 -0
  4. convergent_cli/calibration_finish.py +310 -0
  5. convergent_cli/calibration_frontier.py +499 -0
  6. convergent_cli/calibration_runner.py +1413 -0
  7. convergent_cli/calibration_send.py +44 -0
  8. convergent_cli/codex_app_server.py +127 -0
  9. convergent_cli/command_tree.py +102 -0
  10. convergent_cli/commands/__init__.py +58 -0
  11. convergent_cli/commands/agents.py +729 -0
  12. convergent_cli/commands/auth.py +117 -0
  13. convergent_cli/commands/calibration.py +3857 -0
  14. convergent_cli/commands/calibration_labels_load.py +627 -0
  15. convergent_cli/commands/capabilities.py +85 -0
  16. convergent_cli/commands/dataset_authoring.py +964 -0
  17. convergent_cli/commands/dataset_import.py +763 -0
  18. convergent_cli/commands/datasets.py +678 -0
  19. convergent_cli/commands/docs.py +120 -0
  20. convergent_cli/commands/doctor.py +124 -0
  21. convergent_cli/commands/environments.py +63 -0
  22. convergent_cli/commands/findings.py +206 -0
  23. convergent_cli/commands/graders.py +803 -0
  24. convergent_cli/commands/harness.py +366 -0
  25. convergent_cli/commands/issues.py +388 -0
  26. convergent_cli/commands/production.py +173 -0
  27. convergent_cli/commands/profile.py +86 -0
  28. convergent_cli/commands/rubrics.py +14 -0
  29. convergent_cli/commands/runs.py +1763 -0
  30. convergent_cli/commands/setup.py +968 -0
  31. convergent_cli/commands/task_qc.py +1041 -0
  32. convergent_cli/commands/task_qc_reports.py +393 -0
  33. convergent_cli/commands/verdicts.py +156 -0
  34. convergent_cli/commands/workspaces.py +170 -0
  35. convergent_cli/commands/worlds.py +292 -0
  36. convergent_cli/confirm.py +59 -0
  37. convergent_cli/control_client.py +141 -0
  38. convergent_cli/customer_client.py +1272 -0
  39. convergent_cli/docs_client.py +165 -0
  40. convergent_cli/errors.py +212 -0
  41. convergent_cli/harness_run.py +1169 -0
  42. convergent_cli/harness_tree.py +854 -0
  43. convergent_cli/installed_agent.py +1071 -0
  44. convergent_cli/json_files.py +23 -0
  45. convergent_cli/local_files.py +64 -0
  46. convergent_cli/main.py +106 -0
  47. convergent_cli/oauth.py +431 -0
  48. convergent_cli/output.py +15 -0
  49. convergent_cli/paging.py +62 -0
  50. convergent_cli/run_calibration.py +361 -0
  51. convergent_cli/run_usage.py +99 -0
  52. convergent_cli/sessions.py +275 -0
  53. convergent_cli/setup_agents.py +190 -0
  54. convergent_cli/setup_auth.py +463 -0
  55. convergent_cli/setup_instrument.py +244 -0
  56. convergent_cli/setup_mcp.py +525 -0
  57. convergent_cli/setup_wizard.py +125 -0
  58. convergent_cli/skill_files/convergent/SKILL.md +25 -0
  59. convergent_cli/skill_files/convergent-instrument/SKILL.md +15 -0
  60. convergent_cli/skill_files/convergent-verify/SKILL.md +15 -0
  61. convergent_cli/skills.py +489 -0
  62. convergent_cli/state.py +297 -0
  63. convergent_cli/transport.py +242 -0
  64. convergent_cli/verdict_feedback.py +161 -0
  65. convergent_cli/verifier_bench_preflight.py +32 -0
  66. convergent_cli/world_docker.py +145 -0
  67. convergent_cli/world_files.py +432 -0
  68. convergent_cli/world_live.py +660 -0
  69. convergent_cli/world_mcp.py +109 -0
  70. convergent_cli/world_probe_requirements.txt +29 -0
  71. convergent_cli/world_template/Dockerfile +10 -0
  72. convergent_cli/world_template/README.md +38 -0
  73. convergent_cli/world_template/convergent.toml +11 -0
  74. convergent_cli/world_template/examples/default/environment/catalog.json +3 -0
  75. convergent_cli/world_template/examples/default/instruction.md +1 -0
  76. convergent_cli/world_template/requirements.txt +1 -0
  77. convergent_cli/world_template/schemas/catalog.json +5 -0
  78. convergent_cli/world_template/server.py +25 -0
  79. convergent_cli-0.1.0.dist-info/METADATA +679 -0
  80. convergent_cli-0.1.0.dist-info/RECORD +83 -0
  81. convergent_cli-0.1.0.dist-info/WHEEL +4 -0
  82. convergent_cli-0.1.0.dist-info/entry_points.txt +2 -0
  83. convergent_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,499 @@
1
+ """Rank many calibration treatments against one baseline on cost and quality.
2
+
3
+ Each candidate, and the noise-floor treatment when one is named, is read one
4
+ at a time through the existing compare route. Every figure comes from that
5
+ response: the pooled (or one batch's) micro TPR and TNR deltas with their
6
+ paired intervals, and a cost with its basis. The cost is the whole run's
7
+ production-equivalent cost per trace, or with ``--batch`` that batch's recorded
8
+ call cost when compare reports one. When one arm grades a strict subset of the
9
+ other's batches, compare's production-equivalent pair covers only the shared
10
+ batches; that row is labelled ``batch subset`` and is not ranked. Only rows
11
+ whose cost has the baseline's scope are ranked against each other.
12
+ Nothing here reads trace ids, labels or per-trace data, and nothing decides a
13
+ swap.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import sys
20
+ import urllib.parse
21
+ from collections.abc import Callable, Mapping, Sequence
22
+ from typing import Any, TypeGuard
23
+
24
+ from convergent_cli.calibration_runner import require_treatment
25
+ from convergent_cli.command_tree import CommandCatalog, CommandInfo, Effect, Plane
26
+ from convergent_cli.errors import ControlRefusedError, ExitCode, NetworkError
27
+ from convergent_cli.output import emit_json
28
+
29
+ Read = Callable[[str, Mapping[str, str] | None], Mapping[str, object]]
30
+ Row = dict[str, Any]
31
+
32
+ _TREATMENTS_PATH = "/v1/staff/calibration/treatments"
33
+ _PLACED_COST_BASES = ("exact", "upper bound")
34
+ NOT_MEASURED = "not measured"
35
+ _DESCRIPTION = (
36
+ "Read compare for each candidate against the baseline, then print one row per "
37
+ "treatment with its TPR and TNR deltas, its cost, whether both deltas sit inside the "
38
+ "noise-floor intervals, and whether it is on the cost and quality frontier. TPR and "
39
+ "TNR count equally, and a row with unknown cost is never on the frontier. The cost is"
40
+ " the whole run's production-equivalent cost per trace (cost_scope=whole run). With "
41
+ "--batch it is that batch's recorded call cost (cost_scope=batch) when compare "
42
+ "reports one. A candidate that grades a different batch set than the baseline has a "
43
+ "cost over the shared batches only (cost_scope=batch subset); compare it with "
44
+ "--batch. Only rows whose cost_scope matches the baseline's are ranked. This ranks "
45
+ "treatments. It does not decide swaps: the evaluator swap bar (#8742) governs "
46
+ "replacement, and production results are not read until it is signed off."
47
+ )
48
+
49
+
50
+ def register(
51
+ commands: Any,
52
+ catalog: CommandCatalog,
53
+ *,
54
+ read: Read,
55
+ warn: Callable[[Mapping[str, object]], None],
56
+ ) -> None:
57
+ summary = "Rank candidate treatments against one baseline on cost and quality."
58
+ parser = commands.add_parser("frontier", help=summary, description=_DESCRIPTION)
59
+ parser.add_argument("candidates", nargs="+", help="Candidate treatment names.")
60
+ parser.add_argument("--baseline", required=True, help="Baseline treatment name.")
61
+ parser.add_argument(
62
+ "--noise-floor",
63
+ help="A rerun of the baseline. Its intervals decide within_noise.",
64
+ )
65
+ parser.add_argument("--batch", help="Read deltas from this batch member only.")
66
+ parser.add_argument(
67
+ "--basis",
68
+ choices=("post_audit", "pre_audit"),
69
+ default="post_audit",
70
+ help="Count each comparison from the stored or the pre-audit verdict.",
71
+ )
72
+ parser.add_argument(
73
+ "--format",
74
+ choices=("text", "json"),
75
+ default="text",
76
+ help="Print the rows as text or as a JSON array.",
77
+ )
78
+ catalog.bind(
79
+ parser=parser,
80
+ handler=lambda args: _frontier(args, read, warn),
81
+ info=CommandInfo(
82
+ path=("calibration", "frontier"),
83
+ description=summary,
84
+ plane=Plane.CONTROL,
85
+ requires_session=True,
86
+ effect=Effect.READ,
87
+ ),
88
+ )
89
+
90
+
91
+ def _frontier(
92
+ args: argparse.Namespace,
93
+ read: Read,
94
+ warn: Callable[[Mapping[str, object]], None],
95
+ ) -> int:
96
+ baseline = require_treatment(args.baseline)
97
+ names = [require_treatment(name, label="candidate treatment") for name in args.candidates]
98
+ candidates = list(dict.fromkeys(names))
99
+ for name in candidates:
100
+ if names.count(name) > 1:
101
+ print(f"cv: warning: {name} is listed more than once; reading it once", file=sys.stderr)
102
+ noise = (
103
+ require_treatment(args.noise_floor, label="noise-floor treatment")
104
+ if args.noise_floor
105
+ else None
106
+ )
107
+ params = {"basis": args.basis} if args.basis == "pre_audit" else None
108
+
109
+ def compare(candidate: str) -> Mapping[str, object] | str:
110
+ path = (
111
+ f"{_TREATMENTS_PATH}/{urllib.parse.quote(baseline, safe='')}"
112
+ f"/comparisons/{urllib.parse.quote(candidate, safe='')}"
113
+ )
114
+ try:
115
+ payload = read(path, params)
116
+ except ControlRefusedError as exc:
117
+ return str(exc)
118
+ except NetworkError as exc:
119
+ return f"request_failed: {exc}"
120
+ warn(payload)
121
+ return payload
122
+
123
+ noise_result = compare(noise) if noise is not None else None
124
+ results = {name: compare(name) for name in candidates}
125
+ rows = frontier_rows(baseline, results, args.batch, noise=noise, noise_result=noise_result)
126
+ subset = [row["treatment"] for row in rows if row["cost_scope"] == "batch subset"]
127
+ if subset:
128
+ print(
129
+ f"cv: warning: {', '.join(subset)} grade a different batch set than the baseline, "
130
+ "so their cost covers only the shared batches and they are not ranked. "
131
+ "Compare one batch with --batch.",
132
+ file=sys.stderr,
133
+ )
134
+ if args.format == "json":
135
+ emit_json(rows)
136
+ else:
137
+ print(_text(rows, baseline, noise, args), end="")
138
+ if all(row["reason"] is not None for row in rows if row["role"] == "candidate"):
139
+ print("cv: every candidate failed", file=sys.stderr)
140
+ return int(ExitCode.REFUSAL)
141
+ return 0
142
+
143
+
144
+ def frontier_rows(
145
+ baseline: str,
146
+ results: Mapping[str, Mapping[str, object] | str],
147
+ batch: str | None,
148
+ *,
149
+ noise: str | None = None,
150
+ noise_result: Mapping[str, object] | str | None = None,
151
+ ) -> list[Row]:
152
+ """Baseline, noise-floor and candidate rows, each built from one compare response."""
153
+
154
+ rows = [_baseline_row(baseline, [*results.values(), noise_result], batch)]
155
+ noise_row = None
156
+ if noise is not None and noise_result is not None:
157
+ noise_row = _compared_row(noise, "noise_floor", noise_result, batch)
158
+ rows.append(noise_row)
159
+ for name, result in results.items():
160
+ row = _compared_row(name, "candidate", result, batch)
161
+ if row["reason"] is None:
162
+ row["within_noise"] = _within_noise(row, noise_row)
163
+ rows.append(row)
164
+ scope = rows[0]["cost_scope"]
165
+ placed = [
166
+ (row, position)
167
+ for row in rows
168
+ if row["role"] != "noise_floor" and (position := _position(row, scope)) is not None
169
+ ]
170
+ for row in rows:
171
+ if row["role"] == "noise_floor":
172
+ continue
173
+ mine = _position(row, scope)
174
+ row["frontier"] = mine is not None and not any(
175
+ _dominates(theirs, mine) for other, theirs in placed if other is not row
176
+ )
177
+ return rows
178
+
179
+
180
+ def _row(treatment: str, role: str) -> Row:
181
+ return {
182
+ "treatment": treatment,
183
+ "role": role,
184
+ "changed_dimensions": [],
185
+ "delta_tpr": None,
186
+ "delta_tnr": None,
187
+ "cost_usd": None,
188
+ "cost_basis": "unknown",
189
+ "extraction_usd": None,
190
+ "extraction_cost_basis": "unknown",
191
+ "grading_usd": None,
192
+ "grading_cost_basis": "unknown",
193
+ "price_basis_label": "price basis unconfirmed",
194
+ "cost_scope": "whole run",
195
+ "within_noise": None,
196
+ "frontier": None,
197
+ "reason": None,
198
+ }
199
+
200
+
201
+ def _baseline_row(
202
+ baseline: str, results: Sequence[Mapping[str, object] | str | None], batch: str | None
203
+ ) -> Row:
204
+ """Zero deltas. The cost is the batch's when any compare reports it, else the whole run's."""
205
+
206
+ row = _row(baseline, "baseline")
207
+ zero = {"point": 0.0, "lower": None, "upper": None}
208
+ row["delta_tpr"] = zero
209
+ row["delta_tnr"] = dict(zero)
210
+ costs = [_cost(result, "baseline", batch) for result in results if isinstance(result, Mapping)]
211
+ chosen = next((cost for cost in costs if cost[2] == "batch"), costs[0] if costs else None)
212
+ if chosen is not None:
213
+ row["cost_usd"], row["cost_basis"], row["cost_scope"] = chosen
214
+ row["latency"] = next(
215
+ (
216
+ _latency(result, "baseline", batch)
217
+ for result in results
218
+ if isinstance(result, Mapping) and _latency(result, "baseline", batch) is not None
219
+ ),
220
+ None,
221
+ )
222
+ if row["latency"] is None:
223
+ row.pop("latency")
224
+ source = next((result for result in results if isinstance(result, Mapping)), None)
225
+ if source is not None:
226
+ _split(row, source, "baseline", batch)
227
+ return row
228
+
229
+
230
+ def _compared_row(
231
+ treatment: str, role: str, result: Mapping[str, object] | str, batch: str | None
232
+ ) -> Row:
233
+ row = _row(treatment, role)
234
+ if isinstance(result, str):
235
+ row["reason"] = result
236
+ return row
237
+ row["changed_dimensions"] = [
238
+ str(dimension.get("dimension")) for dimension in _mappings(result.get("changed_dimensions"))
239
+ ]
240
+ row["cost_usd"], row["cost_basis"], row["cost_scope"] = _cost(result, "candidate", batch)
241
+ if result.get("latency") is not None:
242
+ row["latency"] = _latency(result, "candidate", batch)
243
+ _split(row, result, "candidate", batch)
244
+ source: object = result.get("pooled")
245
+ if batch is not None:
246
+ match = next(
247
+ (
248
+ item
249
+ for item in _mappings(result.get("batches"))
250
+ if item.get("batch_member_id") == batch
251
+ ),
252
+ None,
253
+ )
254
+ if match is None:
255
+ row["reason"] = f"batch {batch} is not in this comparison"
256
+ return row
257
+ if match.get("comparable") is not True:
258
+ row["reason"] = f"batch {batch} is not comparable: {match.get('reason')}"
259
+ return row
260
+ source = match.get("difference")
261
+ if isinstance(source, Mapping):
262
+ row["delta_tpr"] = _interval(source.get("tpr"))
263
+ row["delta_tnr"] = _interval(source.get("tnr"))
264
+ return row
265
+
266
+
267
+ def _interval(metric: object) -> dict[str, object] | None:
268
+ micro = metric.get("micro") if isinstance(metric, Mapping) else None
269
+ if not isinstance(micro, Mapping):
270
+ return None
271
+ return {key: micro.get(key) for key in ("point", "lower", "upper")}
272
+
273
+
274
+ def _cost(
275
+ payload: Mapping[str, object], side: str, batch: str | None
276
+ ) -> tuple[float | None, str, str]:
277
+ """Amount, basis and scope: the batch's call cost when present, else the whole run's.
278
+
279
+ Whole-arm ranking uses the total per trace regardless of compare's legacy
280
+ subset cost delta. Batch ranking uses that batch's production split. Exact
281
+ and upper-bound costs are placed. Lower bounds are displayed but never ranked.
282
+ """
283
+
284
+ if batch is not None:
285
+ call = next(
286
+ (
287
+ row
288
+ for row in _mappings(payload.get("batch_production_costs"))
289
+ if row.get("batch_member_id") == batch
290
+ ),
291
+ None,
292
+ )
293
+ split = call.get("cost") if call is not None else None
294
+ total = split.get("total") if isinstance(split, Mapping) else None
295
+ cost = total.get(side) if isinstance(total, Mapping) else None
296
+ if isinstance(cost, Mapping):
297
+ return (*_placed_amount(cost.get("amount"), cost.get("cost_basis")), "batch")
298
+ amount = _arm_production_equivalent(payload, side)
299
+ arm = payload.get(f"{side}_arm_cost")
300
+ if isinstance(arm, Mapping) and isinstance(arm.get("total_per_trace"), Mapping):
301
+ amount = arm["total_per_trace"]
302
+ return (*_placed_amount(amount.get("amount"), amount.get("cost_basis")), "whole run")
303
+
304
+
305
+ def _split(row: Row, payload: Mapping[str, object], side: str, batch: str | None) -> None:
306
+ if batch is not None and row["cost_scope"] == "batch":
307
+ matched = next(
308
+ (
309
+ entry
310
+ for entry in _mappings(payload.get("batch_production_costs"))
311
+ if entry.get("batch_member_id") == batch
312
+ ),
313
+ {},
314
+ )
315
+ cost = matched.get("cost")
316
+ if isinstance(cost, Mapping):
317
+ for name in ("extraction", "grading"):
318
+ delta = cost.get(name)
319
+ part = delta.get(side) if isinstance(delta, Mapping) else None
320
+ if isinstance(part, Mapping):
321
+ row[f"{name}_usd"], row[f"{name}_cost_basis"] = _placed_amount(
322
+ part.get("amount"), part.get("cost_basis")
323
+ )
324
+ return
325
+ arm = payload.get(f"{side}_arm_cost")
326
+ if not isinstance(arm, Mapping):
327
+ return
328
+ distribution = arm.get("distribution")
329
+ if isinstance(distribution, Mapping):
330
+ total = distribution.get("total")
331
+ p90 = total.get("p90") if isinstance(total, Mapping) else None
332
+ row["p90_total_usd"] = p90.get("amount") if isinstance(p90, Mapping) else None
333
+ row["p90_total_precision"] = p90.get("precision") if isinstance(p90, Mapping) else "unknown"
334
+ for name, key in (
335
+ ("extraction", "extraction_per_trace"),
336
+ ("grading", "grading_per_production_grade"),
337
+ ):
338
+ part = arm.get(key)
339
+ if isinstance(part, Mapping):
340
+ row[f"{name}_usd"], row[f"{name}_cost_basis"] = _placed_amount(
341
+ part.get("amount"), part.get("cost_basis")
342
+ )
343
+ row["price_basis_label"] = part.get("price_basis_label", "price basis unconfirmed")
344
+
345
+
346
+ def _arm_production_equivalent(payload: Mapping[str, object], side: str) -> Mapping[str, object]:
347
+ arm = payload.get(f"{side}_arm_cost")
348
+ amount = arm.get("production_equivalent_per_trace") if isinstance(arm, Mapping) else None
349
+ return amount if isinstance(amount, Mapping) else {}
350
+
351
+
352
+ def _placed_amount(value: object, basis: object) -> tuple[float | None, str]:
353
+ if basis in (*_PLACED_COST_BASES, "lower bound") and _is_number(value):
354
+ return float(value), str(basis)
355
+ return None, "unknown"
356
+
357
+
358
+ def _within_noise(row: Row, noise_row: Row | None) -> bool | str:
359
+ """Both delta points inside the noise floor's paired intervals."""
360
+
361
+ if noise_row is None or noise_row["reason"] is not None:
362
+ return NOT_MEASURED
363
+ checks: list[bool] = []
364
+ for key in ("delta_tpr", "delta_tnr"):
365
+ delta = row[key] or {}
366
+ bounds = noise_row[key] or {}
367
+ point, lower, upper = delta.get("point"), bounds.get("lower"), bounds.get("upper")
368
+ if not (_is_number(point) and _is_number(lower) and _is_number(upper)):
369
+ return NOT_MEASURED
370
+ checks.append(lower <= point <= upper)
371
+ return all(checks)
372
+
373
+
374
+ def _position(row: Row, scope: str) -> tuple[float, float, float] | None:
375
+ """Negated cost, delta TPR and delta TNR, so larger is better on all three.
376
+
377
+ A row with a reason, an unknown cost, a cost of another scope than the
378
+ baseline's, or an unknown delta has no position.
379
+ """
380
+
381
+ cost = row["cost_usd"]
382
+ tpr, tnr = _point(row, "delta_tpr"), _point(row, "delta_tnr")
383
+ if (
384
+ row["reason"] is not None
385
+ or row["cost_scope"] != scope
386
+ or row["cost_basis"] not in _PLACED_COST_BASES
387
+ ):
388
+ return None
389
+ if cost is None or tpr is None or tnr is None:
390
+ return None
391
+ return (-cost, tpr, tnr)
392
+
393
+
394
+ def _dominates(theirs: tuple[float, ...], mine: tuple[float, ...]) -> bool:
395
+ """At least as cheap and as good on both deltas, and strictly better on one."""
396
+
397
+ return theirs != mine and all(a >= b for a, b in zip(theirs, mine, strict=True))
398
+
399
+
400
+ def _point(row: Row, key: str) -> float | None:
401
+ delta = row[key]
402
+ point = delta.get("point") if isinstance(delta, Mapping) else None
403
+ return float(point) if _is_number(point) else None
404
+
405
+
406
+ def _text(rows: Sequence[Row], baseline: str, noise: str | None, args: argparse.Namespace) -> str:
407
+ heading = f"frontier baseline={baseline} noise_floor={noise or NOT_MEASURED} basis={args.basis}"
408
+ if args.batch:
409
+ heading += f" batch={args.batch}"
410
+ lines = [heading, "note=This ranks treatments. The swap bar decides replacement."]
411
+ has_latency = any(row.get("latency") is not None for row in rows)
412
+ for row in rows:
413
+ bits = [f"treatment={row['treatment']}", f"role={row['role']}"]
414
+ if row["reason"] is not None:
415
+ lines.append(" ".join([*bits, f"reason={row['reason']}"]))
416
+ continue
417
+ bits.append("changed=" + (",".join(row["changed_dimensions"]) or "none"))
418
+ bits.append(f"delta_tpr={_delta_text(row['delta_tpr'])}")
419
+ bits.append(f"delta_tnr={_delta_text(row['delta_tnr'])}")
420
+ cost = row["cost_usd"]
421
+ bits.append(
422
+ "cost unknown" if cost is None else f"cost_usd={_number(cost)} {row['cost_basis']}"
423
+ )
424
+ if "p90_total_usd" in row:
425
+ p90 = row["p90_total_usd"]
426
+ bits.append(
427
+ f"p90_total_usd={_number(p90) if _is_number(p90) else 'unknown'} "
428
+ f"precision={row['p90_total_precision']}"
429
+ )
430
+ bits.append(f"cost_scope={row['cost_scope']}")
431
+ if has_latency:
432
+ latency = row.get("latency")
433
+ if latency is not None:
434
+ bits.append("latency_basis=bucket_upper_bound latency_scope=batch_executions")
435
+ for name in ("p50", "p90"):
436
+ value = latency.get(f"{name}_seconds") if isinstance(latency, Mapping) else None
437
+ shown = (
438
+ _number(value)
439
+ if _is_number(value)
440
+ else (
441
+ ">1800 s"
442
+ if isinstance(latency, Mapping) and latency.get("overflow")
443
+ else "unknown"
444
+ )
445
+ )
446
+ bits.append(f"latency_{name}_seconds={shown}")
447
+ for name in ("extraction", "grading"):
448
+ amount = row[f"{name}_usd"]
449
+ bits.append(
450
+ f"{name}_usd={_number(amount) if amount is not None else 'unknown'} "
451
+ f"{row[f'{name}_cost_basis']}"
452
+ )
453
+ bits.append(row["price_basis_label"])
454
+ if row["role"] == "candidate":
455
+ bits.append(f"within_noise={_flag(row['within_noise'])}")
456
+ if row["role"] != "noise_floor":
457
+ bits.append(f"frontier={_flag(row['frontier'])}")
458
+ lines.append(" ".join(bits))
459
+ return "\n".join(lines) + "\n"
460
+
461
+
462
+ def _delta_text(delta: object) -> str:
463
+ if not isinstance(delta, Mapping) or not _is_number(delta.get("point")):
464
+ return "unknown"
465
+ text = _number(delta["point"])
466
+ lower, upper = delta.get("lower"), delta.get("upper")
467
+ if _is_number(lower) and _is_number(upper):
468
+ text += f" [{_number(lower)}, {_number(upper)}]"
469
+ return text
470
+
471
+
472
+ def _flag(value: object) -> str:
473
+ return str(value).lower() if isinstance(value, bool) else str(value)
474
+
475
+
476
+ def _number(value: float) -> str:
477
+ return f"{value:.6g}"
478
+
479
+
480
+ def _is_number(value: object) -> TypeGuard[int | float]:
481
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
482
+
483
+
484
+ def _mappings(value: object) -> list[Mapping[str, object]]:
485
+ return [item for item in value if isinstance(item, Mapping)] if isinstance(value, list) else []
486
+
487
+
488
+ def _latency(payload: Mapping[str, object], side: str, batch: str | None) -> object:
489
+ comparison = payload.get("latency")
490
+ if batch is not None:
491
+ comparison = next(
492
+ (
493
+ row.get("latency")
494
+ for row in _mappings(payload.get("batch_call_costs"))
495
+ if row.get("batch_member_id") == batch
496
+ ),
497
+ None,
498
+ )
499
+ return comparison.get(side) if isinstance(comparison, Mapping) else None