File size: 62,896 Bytes
fd8b1ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
"""Score replies to the multi-step environments with no judge: a program and the verifier.

    python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F]
                     [--calls-from reply|harness] [--harness-dir DIR]

    REPLIES is a folder with one file per environment, <id>.txt, the whole text of a reply.
    --calls-from harness   the call record is the harness's own: <id>.harness.jsonl, written by
                           harness/mcp_log_proxy.py outside the solver's working directory (in
                           --harness-dir, default REPLIES). A <id>.calls.jsonl beside the reply,
                           when there is one, is read only to catch an edit: it must equal the
                           harness log call for call.
    --calls-from reply     (the earlier set's way) the call record is <id>.calls.jsonl beside the reply:
                           one JSON object a line, {"tool": "<name>", "arguments": {...}}.

    ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address
    beginning http. A task is scored only on the engine it was built on: the verifier's version must
    be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's
    reference.engine_binary_sha256.

The answer card is one JSON object on the reply's last line. Its shape is the family's:

  tradeoff, chain_design   (kind design_to_limit, chained_design)
      {"passing": DESIGN, "failing": DESIGN, "binding": "<constraint id>"}
      DESIGN = {"run": {"request": R, "proof": "<run_seal>"},
                "solve": {"request": R, "proof": "<solution_seal>"}}     (solve only where the task has one)
      Where a constraint is that the run completes and it binds, the failing DESIGN also carries
      "stopped": "<the stop's name>" and "step": <steps_landed>.   R = {"tool": ..., "arguments": {...}}
      The design shapes, one scorer for every group (check.design says which):
        run        a run alone.
        coupled    check.design.chain names a solver and coupling: the run, then a solve handed that sealed run.
        continued  check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of
                   the same card that continues it through from, starting from its sealed final state,
                   DESIGN = {"run": {...}, "next": {"request": R, "proof": "<run_seal>"}}. The next run's template
                   is chain.next_template, chain.template or chain.next; its start fields are chain.carried
                   ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or
                   chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on
                   "next" reads the next run, and a stop constraint judges it.
        solve      check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no
                   run. A binding refusal is named ("stopped") with no step.
        staged     check.design.stages: DESIGN = {"<stage key>": {"request": R, "proof": ...}, ...}, one entry per
                   stage in order; a later stage carries an earlier stage's answer at a named input (handed) or
                   continues an earlier run (continues), bit for bit.
      A constraint's read may carry "index": one entry of an output the verifier returns as a list.
  budget                   (kind budgeted_search)
      {"holds": {"request": R, "proof": "<seal>"},
       "stops": {"request": R, "proof": "<seal>", "stopped": "<stop name>"}}
  forensics
      {"false_rows": {"<row>": "<reason>", ...}}       ({} when every row is genuine)

Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a
solution_seal, short form) and every number judged is read from the verifier's own answer to the
card's request, sent again here, never from the reply.

Scores per environment
----------------------
reward  0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1.
        proofs_hold: every proof on the card verifies. correct: the card is the right answer and
        nothing below under "integrity" failed.
graded  in [0, 1], beside reward.

  Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not
  verify (a copied, nudged, edited or stale proof); a request differs from the task's template other
  than at the design variable; a chained solve not handed its own design's sealed run; no call log;
  a call log beside the reply that differs from the harness log; a harness log whose chain breaks;
  a forbidden tool called; more computing calls than the budget; a request on the card that is not
  among the calls; a forensics answer with no computing call behind it; a task built on another
  engine than the verifier.

  tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the
  passing design meets every constraint and the failing one breaks the named binding constraint
  (budget: holds completes, stops ends with the task's stop, named on the card), on the side the
  task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0.
  With the sides right:

      e     = the length of the smallest interval holding both designs' values and the reference
              boundary (for a bracket that straddles the boundary, its width)
      tol   = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget)
      r     = e / tol
      graded = 1                           when reward is 1 (r <= 1 and the bracket straddles it)
             = 0.5 ** log10(r)             when r > 1: each tenfold of looseness halves the score
                                           (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25)
             = 0.5                         when r <= 1 but the bracket misses the reference boundary
                                           by more than the slack (another crossing than the one asked)

      The decay is smooth and falls monotonically with r, and a near miss scores near the top.

  forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found
  only with its right reason. precision = found / named, recall = found / false rows; an empty
  answer to a table with no false row scores 1. A card that names every row of the table false is
  a blanket answer and scores 0, as do unknown rows and reasons outside the task's list.

Licence: Apache-2.0.
"""
import argparse
import copy
import hashlib
import json
import math
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from ztp_mcp import McpError, StdioVerifier, Verifier  # noqa: E402

FAMILIES = ("tradeoff", "chain_design", "budget", "forensics")
KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"}
NOT_STOPPED = ("completed", "converged")
PREFIX_ENDS = ("__", ".", ":", "/")
VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite",
                  "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset",
                  "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip")
# Calls that read the catalogue compute nothing and are free in a call budget.
FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt")
REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden")
GRADED_DECAY = 0.5          # graded = GRADED_DECAY ** log10(r)
OTHER_CROSSING = 0.5        # right sides, tight, around another crossing than the reference boundary


class Integrity(Exception):
    """The answer cannot be trusted: graded 0 and reward 0."""


class Wrong(Exception):
    """The answer is trusted and wrong: graded 0 and reward 0."""


def load_environments(path):
    with open(path, encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def row_problems(env):
    """What a task row lacks against the shared row contract (empty when none)."""
    out = []
    for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"):
        if key not in env:
            out.append("no %s" % key)
    family = env.get("family")
    if family not in FAMILIES:
        out.append("family %r" % family)
    elif "kind" in env and env["kind"] != KINDS[family]:
        out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family]))
    ref = env.get("reference") or {}
    for key in ("engine_tag", "engine_commit", "engine_binary_sha256"):
        if not ref.get(key):
            out.append("reference.%s missing" % key)
    return out


def file_sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def open_verifier(engine):
    if engine.startswith("http://") or engine.startswith("https://"):
        verifier = Verifier(engine, pause_s=0.5)
        verifier.binary_sha256 = None
    else:
        if not os.path.isfile(engine):
            sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine)
        verifier = StdioVerifier([engine])
        verifier.binary_sha256 = file_sha256(engine)
    try:
        verifier.connect()
    except McpError as problem:
        sys.exit("the verifier failed, so nothing was scored: %s" % problem)
    if not isinstance(verifier.server, dict) or not verifier.server.get("name"):
        close_verifier(verifier)
        sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine)
    return verifier


def close_verifier(verifier):
    if hasattr(verifier, "close"):
        verifier.close()


# ------------------------------------------------------------------------------------------
# reading the reply and the call logs
# ------------------------------------------------------------------------------------------
def _no_constant(name):
    raise ValueError("%s is not a number" % name)


def read_card(reply):
    """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over."""
    lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()]
    while lines and lines[-1].startswith("```"):
        lines.pop()
    if not lines:
        return None, "the reply is empty"
    try:
        card = json.loads(lines[-1], parse_constant=_no_constant)
    except ValueError:
        return None, "the last line is not one JSON object"
    if not isinstance(card, dict):
        return None, "the last line is not one JSON object"
    return card, None


def tool_name(name):
    """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve)."""
    if not isinstance(name, str):
        return None
    if name in VERIFIER_TOOLS:
        return name
    for tool in VERIFIER_TOOLS:
        for joint in PREFIX_ENDS:
            if name.endswith(joint + tool):
                return tool
    return name


def without_readout(arguments):
    """A run's arguments as sealed: a readout is not part of a run's seal."""
    if not isinstance(arguments, dict):
        return arguments
    return {k: v for k, v in arguments.items() if k != "readout"}


def numbers_by_value(value):
    """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept."""
    if isinstance(value, dict):
        return {k: numbers_by_value(v) for k, v in value.items()}
    if isinstance(value, list):
        return [numbers_by_value(v) for v in value]
    if isinstance(value, int) and not isinstance(value, bool):
        return float(value)
    return value


def canonical(arguments):
    """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value."""
    return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":"))


def _arguments(one):
    arguments = one.get("arguments")
    if isinstance(arguments, str):
        try:
            arguments = json.loads(arguments)
        except ValueError:
            arguments = {}
    return arguments if isinstance(arguments, dict) else {}


def read_calls(path):
    """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log."""
    if not path or not os.path.isfile(path):
        return None
    calls = []
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                one = json.loads(line)
            except ValueError:
                continue
            if isinstance(one, dict):
                calls.append((tool_name(one.get("tool")), _arguments(one)))
    return calls


def chain_of(previous, entry):
    payload = json.dumps(entry, sort_keys=True, separators=(",", ":"))
    return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest()


def read_harness_log(path):
    """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log;
    problem names the first line whose chain does not follow (an edit, a line taken out or put in)."""
    if not path or not os.path.isfile(path):
        return None, None
    calls, previous = [], None
    with open(path, encoding="utf-8", errors="replace") as f:
        for number_, line in enumerate(f, 1):
            if not line.strip():
                continue
            try:
                entry = json.loads(line)
            except ValueError:
                return calls, "line %d of the harness log is not JSON" % number_
            if not isinstance(entry, dict) or "chain" not in entry:
                return calls, "line %d of the harness log carries no chain" % number_
            chain = entry.pop("chain")
            if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1:
                return calls, "the harness log's chain breaks at line %d" % number_
            previous = chain
            calls.append((tool_name(entry.get("tool")), _arguments(entry)))
    return calls, None


def write_harness_log(path, calls):
    """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)]."""
    previous = None
    with open(path, "w", encoding="utf-8") as f:
        for seq, (tool, arguments) in enumerate(calls, 1):
            entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None,
                     "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False}
            entry["chain"] = chain_of(previous, entry)
            previous = entry["chain"]
            f.write(json.dumps(entry, sort_keys=True) + "\n")


# ------------------------------------------------------------------------------------------
# the verifier, asked again
# ------------------------------------------------------------------------------------------
def stop_name_in(sentence):
    names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "")
    return names[-1] if names else None


class Replay:
    """The verifier, with every answer remembered: the same request is sent once."""

    def __init__(self, verifier):
        self.verifier = verifier
        self.seen = {}
        server = getattr(verifier, "server", None) or {}
        self.version = server.get("version")
        self.binary_sha256 = getattr(verifier, "binary_sha256", None)

    def call(self, tool, arguments):
        key = tool + "\x00" + json.dumps(arguments, sort_keys=True)
        if key not in self.seen:
            try:
                self.seen[key] = self.verifier.call_json(tool, arguments)
            except McpError as problem:
                if not str(problem).startswith("protocol error"):
                    raise SystemExit("the verifier failed, so nothing was scored: %s" % problem)
                self.seen[key] = ("the verifier did not take the request: %s" % problem, True)
        return self.seen[key]

    def answer(self, tool, arguments, readout=None):
        """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}."""
        arguments = copy.deepcopy(without_readout(arguments))
        if readout is not None and tool == "run_trajectory":
            arguments["readout"] = readout
        body, is_error = self.call(tool, arguments)
        if is_error or not isinstance(body, dict):
            sentence = body if isinstance(body, str) else json.dumps(body)
            return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence),
                    "proof": None, "body": None, "sentence": sentence}
        outcome = body.get("outcome")
        stopped = outcome not in NOT_STOPPED
        return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None,
                "proof": body.get("run_seal") or body.get("solution_seal"), "body": body,
                "sentence": body.get("reject_detail")}

    def proof_holds(self, tool, arguments, proof):
        """(holds, words): the card's seal verified by verify_tape or verify_solution, short form."""
        if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof):
            return False, "the proof is not a SHA-384 seal of 96 hex digits"
        if tool == "run_trajectory":
            body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof})
        elif tool == "solve":
            body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof})
        else:
            return False, "a proof is verified for run_trajectory or solve only, not %s" % tool
        if is_error or not isinstance(body, dict):
            return False, "the verifier would not verify it: %s" % (str(body)[:200])
        if body.get("holds") is True:
            return True, None
        return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause")


def engine_problem(env, replay):
    """None when the verifier is the engine the task was built on; else what differs."""
    ref = env.get("reference") or {}
    tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v")
    if not tag:
        return "the task names no engine it was built on"
    if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag:
        return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version"))
    if replay.version != tag:
        return "the task was built on engine %s; the verifier is %s" % (tag, replay.version)
    want = ref.get("engine_binary_sha256")
    if replay.binary_sha256 and want and replay.binary_sha256 != want:
        return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12])
    return None


# ------------------------------------------------------------------------------------------
# requests and their inputs
# ------------------------------------------------------------------------------------------
_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)")


def get_path(obj, path):
    here = obj
    for part in path.split("."):
        found = _PART.fullmatch(part)
        if not found or not isinstance(here, dict) or found.group(1) not in here:
            return None
        here = here[found.group(1)]
        for index in re.findall(r"\[(\d+)\]", found.group(2)):
            if not isinstance(here, list) or int(index) >= len(here):
                return None
            here = here[int(index)]
    return here


def set_path(obj, path, value):
    parts = path.split(".")
    here = obj
    for i, part in enumerate(parts):
        m = _PART.fullmatch(part)
        name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))]
        last = i == len(parts) - 1
        if not idx:
            if last:
                here[name] = value
            else:
                here = here[name]
        else:
            here = here[name]
            for j, k in enumerate(idx):
                if last and j == len(idx) - 1:
                    here[k] = value
                else:
                    here = here[k]


def number(value):
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def differs(template, given, free, where=""):
    """The first place where a request differs from the task's, other than the free places. None when none."""
    if where in free:
        return None
    if isinstance(template, dict):
        if not isinstance(given, dict):
            return where or "the request"
        for key in set(template) | set(given):
            place = "%s.%s" % (where, key) if where else key
            if place in free:
                continue
            if key not in given or key not in template:
                return place
            found = differs(template[key], given[key], free, place)
            if found:
                return found
        return None
    if isinstance(template, list):
        if not isinstance(given, list) or len(given) != len(template):
            return where
        for index, (a, b) in enumerate(zip(template, given)):
            found = differs(a, b, free, "%s[%d]" % (where, index))
            if found:
                return found
        return None
    if number(template) and number(given):
        return None if float(template) == float(given) else where
    return None if template == given else where


def design_value(variable, run_arguments, solve_arguments, next_arguments=None):
    """The design variable of one design, read from its requests (on: run, solve, or next, a continued run)."""
    kind = variable["kind"]
    if kind == "path":
        on = variable.get("on", "run")
        source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {}
        value = get_path(source, variable["path"])
        for place in variable.get("also") or []:
            again = get_path(source, place)
            if not (number(again) and number(value) and float(again) == float(value)):
                return None
        return float(value) if number(value) else None
    if kind == "entry_angle_deg":
        radial = get_path(run_arguments or {}, "initial.radial_speed_m_s")
        transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s")
        if not (number(radial) and number(transverse)) or transverse <= 0:
            return None
        speed = math.hypot(radial, transverse)
        if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]:
            return None
        return math.degrees(math.atan2(-radial, transverse))
    return None


def variable_places(variable):
    if variable["kind"] == "entry_angle_deg":
        return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"}
    if variable["kind"] == "path" and variable.get("on", "run") == "run":
        return {variable["path"]} | set(variable.get("also") or [])
    return set()


def read_value(read, answer):
    """One number from a replayed answer: final, result, or the extreme of a run's readout."""
    body = answer["body"]
    if body is None:
        return None
    kind = read["kind"]
    value = None
    if kind == "final":
        value = (body.get("final_state") or {}).get(read["quantity"])
    elif kind == "result":
        value = (body.get("result") or {}).get(read["quantity"])
    elif kind == "flag_extent":
        # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it
        value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or []
                     if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0])
    elif kind == "extreme":
        for quantity in (body.get("readout") or {}).get("quantities") or []:
            if quantity.get("quantity") == read["quantity"]:
                value = quantity.get(read["which"])
    if "index" in read:
        # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points)
        k = read["index"]
        value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None
    return value if number(value) else None


def readout_for(constraints, on="run"):
    """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key)."""
    quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"})
    return {"quantities": quantities} if quantities else None


def design_shape(spec):
    """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged."""
    if spec.get("stages"):
        return "staged"
    if spec.get("tool") == "solve" or spec.get("kind") == "solve":
        return "solve"
    chain = spec.get("chain") or {}
    if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue":
        return "continued"
    return "coupled" if chain else "run"


def continuation_of(spec):
    """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it},
    next outcomes, the next run's places that also hold a first-run design value)."""
    chain = spec["chain"]
    template = chain.get("next_template") or chain.get("template") or chain.get("next")
    if "carried" in chain:                                          # group 1
        carried = dict(chain["carried"])
    elif "handed" in chain:                                         # group 4
        named = chain.get("handed_from") or {}
        carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]}
    else:                                                           # group 5
        carried = {k: "final_state." + k for k in chain.get("carry") or []}
        if chain.get("clock"):
            carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"]
    outcomes = chain.get("next_outcomes") or spec["run_outcomes"]
    return template, carried, outcomes, list(chain.get("next_also") or [])


def meets(constraint, value):
    if value is None:
        return False
    return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"]


def history_layout_problem(layout, parameters, frames_count):
    """None when the arrays of a chained solve are laid out as the task states; else what is not."""
    if layout is None:
        return None
    if layout["kind"] == "stardust_slab":
        names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s",
                 "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2")
        columns = [parameters.get(name) for name in names]
        if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns):
            return "the history columns are not all lists of numbers"
        time, pressure, coefficient, enthalpy, radiative = columns
        rows = frames_count + 3
        if any(len(c) != rows for c in columns):
            return "the history has not one row before the %d frames handed and two after them" % frames_count
        if time[0] != 0.0 or coefficient[0] != 0.0:
            return "row 0 is not at 0 s with no heating"
        if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]:
            return "row 0 does not repeat the first frame's pressure and enthalpy"
        if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]:
            return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"]
        if coefficient[-2] != 0.0 or coefficient[-1] != 0.0:
            return "the stream is not off after the frames"
        if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]:
            return "the rows after the frames do not hold the last frame's pressure and enthalpy"
        if any(v != 0.0 for v in radiative):
            return "a row of the history holds radiative heating"
        return None
    if layout["kind"] == "triga_element":
        return None      # every array is handed by the coupling and held to its bits by the verifier
    return "an unknown layout"


# ------------------------------------------------------------------------------------------
# the call record
# ------------------------------------------------------------------------------------------
def card_requests(env, card):
    """Every request on the card, [(tool, arguments)], read leniently (for the call log)."""
    out = []

    def take(part):
        if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict):
            out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"]))

    if env["family"] in ("tradeoff", "chain_design"):
        stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []]
        for side in ("passing", "failing"):
            design = card.get(side) if isinstance(card.get(side), dict) else {}
            for key in stages or ("run", "solve", "next"):
                take(design.get(key))
    elif env["family"] == "budget":
        take(card.get("holds"))
        take(card.get("stops"))
    return out


def sequence(calls):
    return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls]


def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row):
    """None when the call record holds; else why not (an integrity failure)."""
    check = env["check"]
    if calls_from == "harness":
        if calls is None:
            return "no harness call log: every attempt is scored with the calls the harness recorded"
        if log_problem:
            return log_problem
        if reply_calls is not None and sequence(reply_calls) != sequence(calls):
            return "the call log beside the reply differs from the harness log"
    elif calls is None:
        return "no call log: every environment is scored with the agent's calls"
    calls = [(tool_name(t), a) for t, a in calls]
    banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])})
    if banned:
        return "the log holds calls of %s, which the task rules out" % ", ".join(banned)
    computing = [(t, a) for t, a in calls if t not in FREE_TOOLS]
    row["computing_calls"] = len(computing)
    if check.get("budget") and len(computing) > check["budget"]:
        return "%d computing calls; the budget is %d" % (len(computing), check["budget"])
    sent = {(t, canonical(a)) for t, a in computing}
    for tool, arguments in card_requests(env, card):
        if (tool, canonical(arguments)) not in sent:
            return "a %s request on the card is not among the calls in the log" % tool
    if env["family"] == "forensics" and not computing:
        return "no computing call behind the answer: the table was not put to the verifier"
    return None


# ------------------------------------------------------------------------------------------
# the families
# ------------------------------------------------------------------------------------------
def request_of(part, tool, what):
    """The arguments of one request on the card (Integrity when it is not one)."""
    if not isinstance(part, dict):
        raise Integrity("%s is missing" % what)
    request = part.get("request")
    if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)):
        raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what)
    if tool_name(request.get("tool")) != tool:
        raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool))
    return request["arguments"]


def score_design(env, design, which, replay, proofs):
    """One design of a boundary family: facts {x, met, values, stopped, steps_landed}."""
    check = env["check"]
    spec = check["design"]
    shape = design_shape(spec)
    if shape in ("solve", "staged", "continued") and not isinstance(design, dict):
        raise Integrity("the %s design is missing" % which)
    if shape == "solve":
        return score_solve_design(env, design, which, replay, proofs)
    if shape == "staged":
        return score_staged_design(env, design, which, replay, proofs)
    if shape == "continued":
        return score_continued_design(env, design, which, replay, proofs)
    chain = spec.get("chain")
    run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory",
                          "the %s design's run" % which)
    free = set(spec.get("free") or []) | variable_places(spec["variable"])
    where = differs(spec["template"], without_readout(run_args), free)
    if where:
        raise Integrity("the %s design's run differs from the task's at %s" % (which, where))
    for place in spec.get("free") or []:
        if place.endswith(".steps"):
            steps = get_path(run_args, place)
            if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)):
                raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place))
    run_proof = design["run"].get("proof")
    holds, words = replay.proof_holds("run_trajectory", run_args, run_proof)
    proofs.append(holds)
    if not holds:
        raise Integrity("the %s design's run_seal: %s" % (which, words))
    run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"]))
    stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"]
    stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names
    if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name:
        raise Wrong("the %s design's run comes back %s%s, not %s" % (
            which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"])))
    solve_args, solve = None, None
    if chain:
        solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which)
        if solve_args.get("solver") != chain["solver"]:
            raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver")))
        handed = solve_args.get("from")
        if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]:
            raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"]))
        if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof:
            raise Integrity("the %s design's solve is not handed the design's own sealed run" % which)
        parameters = solve_args.get("parameters")
        if not isinstance(parameters, dict):
            raise Integrity("the %s design's solve has no parameters" % which)
        solve_free = set(chain.get("handed") or [])
        if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve":
            solve_free.add(spec["variable"]["path"].split(".", 1)[1])
        where = differs(chain["parameters"], parameters, solve_free)
        if where:
            raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where))
        frames = len((run["body"] or {}).get("frames") or [])
        problem = history_layout_problem(chain.get("layout"), parameters, frames)
        if problem:
            raise Integrity("the %s design's solve: %s" % (which, problem))
        holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof"))
        proofs.append(holds)
        if not holds:
            raise Integrity("the %s design's solution_seal: %s" % (which, words))
        solve = replay.answer("solve", solve_args)
        if solve["outcome"] != "converged":
            raise Wrong("the %s design's solve comes back %s%s, not converged" % (
                which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else ""))
    x = design_value(spec["variable"], run_args, solve_args)
    if x is None:
        raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", "")))
    met, values = {}, {}
    for constraint in check["constraints"]:
        if constraint["on"] == "outcome":
            values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"])
            met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"])
            continue
        value = read_value(constraint["read"], run if constraint["on"] == "run" else solve)
        values[constraint["id"]] = value
        met[constraint["id"]] = meets(constraint, value)
    facts = {"x": x, "met": met, "values": values}
    if run["outcome"] not in NOT_STOPPED and run["body"]:
        facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed")
    return facts


def halted(answer, stop, staged=False):
    """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that
    is not completed or converged (group 3's rule, kept as built)."""
    if staged:
        return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop
    return answer["outcome"] == "refused" and answer["stop"] == stop


def constraint_facts(check, answers, judged, staged=False):
    """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop
    constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design."""
    met, values = {}, {}
    for c in check["constraints"]:
        if c["on"] == "outcome":
            a = answers.get(c["stage"]) if c.get("stage") else judged
            values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"]))
            met[c["id"]] = a is not None and not halted(a, c["stop"], staged)
            continue
        a = answers.get(c["on"])
        value = read_value(c["read"], a) if a is not None else None
        values[c["id"]] = value
        met[c["id"]] = meets(c, value) if c.get("limit") is not None else None
    return met, values


def stopped_by(answer, constraints, stage=None):
    """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given)."""
    return any(halted(answer, c["stop"], stage is not None) for c in constraints
               if c["on"] == "outcome" and (stage is None or c.get("stage") == stage))


def score_solve_design(env, design, which, replay, proofs):
    """One design that is one solve and no run (check.design.tool or kind "solve")."""
    check = env["check"]
    spec = check["design"]
    var = spec["variable"]
    solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which)
    if solve_args.get("solver") != spec["template"].get("solver"):
        raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver")))
    free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or [])
    where = differs(spec["template"], solve_args, free)
    if where:
        raise Integrity("the %s design's solve differs from the task's at %s" % (which, where))
    holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof"))
    proofs.append(holds)
    if not holds:
        raise Integrity("the %s design's solution_seal: %s" % (which, words))
    solve = replay.answer("solve", solve_args)
    if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]):
        raise Wrong("the %s design's solve comes back %s%s, not %s" % (
            which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"])))
    x = design_value(dict(var, on="solve"), None, solve_args)
    if x is None:
        raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", "")))
    met, values = constraint_facts(check, {"solve": solve}, solve)
    facts = {"x": x, "met": met, "values": values}
    if solve["outcome"] not in NOT_STOPPED and solve["body"]:
        facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True
    return facts


def score_continued_design(env, design, which, replay, proofs):
    """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes
    the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer
    also holds each carried start field to the first run's answer, bit for bit."""
    check = env["check"]
    spec = check["design"]
    var = spec["variable"]
    on_next = var["kind"] == "path" and var.get("on") == "next"
    template, carried, next_outcomes, next_also = continuation_of(spec)
    run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which)
    free = set(spec.get("free") or []) | (set() if on_next else variable_places(var))
    where = differs(spec["template"], without_readout(run_args), free)
    if where:
        raise Integrity("the %s design's run differs from the task's at %s" % (which, where))
    run_proof = design["run"].get("proof")
    holds, words = replay.proof_holds("run_trajectory", run_args, run_proof)
    proofs.append(holds)
    if not holds:
        raise Integrity("the %s design's run_seal: %s" % (which, words))
    run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run"))
    if run["outcome"] not in spec["run_outcomes"]:
        raise Wrong("the %s design's first run comes back %s%s, not %s" % (
            which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"])))
    next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which)
    handed = next_args.get("from")
    if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args)
            or handed.get("run_seal") != run_proof):
        raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which)
    next_free = {"initial." + name for name in carried} | {"from"} | set(next_also)
    if on_next:
        next_free |= {var["path"]} | set(var.get("also") or [])
    where = differs(template, without_readout(next_args), next_free)
    if where:
        raise Integrity("the %s design's next run differs from the task's at %s" % (which, where))
    start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {}
    for name, source in carried.items():
        held, given = get_path(run["body"] or {}, source), start.get(name)
        if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))):
            raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source))
    holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof"))
    proofs.append(holds)
    if not holds:
        raise Integrity("the %s design's next run_seal: %s" % (which, words))
    nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next"))
    if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]):
        raise Wrong("the %s design's next run comes back %s%s, not %s" % (
            which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes)))
    x = design_value(var, run_args, None, next_args)
    if x is None:
        raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", "")))
    for place in next_also:
        again = get_path(next_args, place)
        if not (number(again) and float(again) == float(x)):
            raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place))
    met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt)
    facts = {"x": x, "met": met, "values": values}
    if nxt["outcome"] not in NOT_STOPPED and nxt["body"]:
        facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed")
    return facts


def build_stage_request(spec, stage, x, answers, requests):
    """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from
    earlier stages' answers, and a continuation's start and from (used by run_reference.py)."""
    q = copy.deepcopy(stage["template"])
    var = spec["variable"]
    if var.get("stage") == stage["key"]:
        for place in [var["path"]] + list(var.get("also") or []):
            set_path(q, place, x)
    for h in stage.get("handed") or []:
        set_path(q, h["to"], read_value(h["read"], answers[h["from"]]))
    if stage.get("continues"):
        parent = stage["continues"]
        final = answers[parent]["body"]["final_state"]
        q["initial"] = {k: final[k] for k in stage["template"]["initial"]}
        q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]}
    return q


def score_staged_design(env, design, which, replay, proofs):
    """One staged design (check.design.stages): each stage a run or a solve, in order."""
    check = env["check"]
    spec = check["design"]
    var = spec["variable"]
    stages = spec["stages"]
    answers, requests, facts = {}, {}, {}
    for i, stage in enumerate(stages):
        key, tool = stage["key"], stage["tool"]
        sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key)))
        free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []}
        if var.get("stage") == key:
            free |= {var["path"]} | set(var.get("also") or [])
        if stage.get("continues"):
            free |= {"initial", "from"}
        where = differs(stage["template"], sent, free)
        if where:
            raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where))
        for h in stage.get("handed") or []:
            want = read_value(h["read"], answers[h["from"]])
            got = get_path(sent, h["to"])
            if want is None or not number(got) or float(got) != float(want):
                raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % (
                    which, key, h["from"], h["read"]["quantity"], h["to"]))
        if stage.get("continues"):
            parent = stage["continues"]
            handed = sent.get("from")
            if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent])
                    or handed.get("run_seal") != design[parent].get("proof")):
                raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent))
            final = (answers[parent]["body"] or {}).get("final_state") or {}
            start = sent.get("initial")
            keys = set(stage["template"]["initial"])
            if not isinstance(start, dict) or set(start) != keys or any(
                    not number(start[k]) or float(start[k]) != final.get(k) for k in keys):
                raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent))
        holds, words = replay.proof_holds(tool, sent, design[key].get("proof"))
        proofs.append(holds)
        if not holds:
            raise Integrity("the %s design's %s proof: %s" % (which, key, words))
        answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None)
        named = stopped_by(answer, check["constraints"], stage=key)
        if answer["outcome"] not in stage["outcomes"] and not named:
            raise Wrong("the %s design's %s comes back %s%s, not %s" % (
                which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"])))
        answers[key], requests[key] = answer, sent
        if named:
            facts["stopped"], facts["stopped_stage"] = answer["stop"], key
            facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None
            facts["no_step"] = tool != "run_trajectory"
            if i != len(stages) - 1:
                raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"]))
    x = design_value(dict(var, on="run"), requests.get(var["stage"]), None)
    if x is None:
        raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", "")))
    met, values = constraint_facts(check, answers, None, staged=True)
    facts.update({"x": x, "met": met, "values": values})
    return facts


def grade_bracket(a, b, star, tol, slack, row):
    """(reward_ok, graded) for a bracket [a, b] with its sides right."""
    width = abs(b - a)
    straddles = min(a, b) - slack <= star <= max(a, b) + slack
    within = width <= tol * (1 + 1e-9)
    e = max(a, b, star) - min(a, b, star)
    r = e / tol if tol > 0 else float("inf")
    row["width"], row["width_ratio"] = width, r
    if within and straddles:
        return True, 1.0
    if r <= 1:
        return False, OTHER_CROSSING
    return False, GRADED_DECAY ** math.log10(r)


def score_boundary(env, card, replay, row, proofs):
    check, reference = env["check"], env["reference"]
    passing = score_design(env, card.get("passing"), "passing", replay, proofs)
    failing = score_design(env, card.get("failing"), "failing", replay, proofs)
    row["passing"], row["failing"] = passing, failing
    span = check["design"].get("range")
    if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])):
        raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span))
    broken = [c for c, ok in passing["met"].items() if not ok]
    if broken:
        raise Wrong("the passing design breaks %s" % ", ".join(broken))
    broken = [c for c, ok in failing["met"].items() if not ok]
    if not broken:
        raise Wrong("the failing design meets every constraint")
    binding = card.get("binding")
    if binding != reference["binding"]:
        raise Wrong("binding names %r; the constraint that binds is another" % (binding,))
    if binding not in broken:
        raise Wrong("the failing design does not break %s, the constraint named binding" % binding)
    if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]:
        said = card.get("failing") or {}
        if said.get("stopped") != failing.get("stopped"):
            raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped")))
        if failing.get("no_step"):
            pass        # a solve that is refused has no step: its stop's name is stated
        elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")):
            raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step")))
    spec = check["design"]
    xp, xf = passing["x"], failing["x"]
    if spec["direction"] == "largest" and not xf > xp:
        raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one")
    if spec["direction"] == "smallest" and not xf < xp:
        raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one")
    ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row)
    if not ok:
        return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % (
            abs(xf - xp), spec["tolerance"])
    return 1.0, None


def score_budget(env, card, replay, row, proofs):
    check, reference = env["check"], env["reference"]
    template, path, tool = check["template"], check["variable"], check["tool"]
    sides = {}
    for side in ("holds", "stops"):
        arguments = request_of(card.get(side), tool, side)
        also = check.get("also") or []
        where = differs(template, without_readout(arguments), {path} | set(also))
        if where:
            raise Integrity("the %s request differs from the task's at %s" % (side, where))
        x = get_path(arguments, path)
        if not number(x):
            raise Integrity("the %s request has no number at %s" % (side, path))
        for place in also:
            again = get_path(arguments, place)
            if not (number(again) and float(again) == float(x)):
                raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path))
        holds, words = replay.proof_holds(tool, arguments, card[side].get("proof"))
        proofs.append(holds)
        sides[side] = (float(x), arguments, holds, words)
    for side in ("holds", "stops"):
        if not sides[side][2]:
            raise Integrity("the %s seal: %s" % (side, sides[side][3]))
    held = replay.answer(tool, sides["holds"][1])
    stopped = replay.answer(tool, sides["stops"][1])
    row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"])
    if held["outcome"] not in NOT_STOPPED:
        raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"]))
    if stopped["stop"] != check["stop"]:
        raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"]))
    if card["stops"].get("stopped") != check["stop"]:
        raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"]))
    xh, xs = sides["holds"][0], sides["stops"][0]
    star = reference["boundary"]
    row["holds_value"], row["stops_value"] = xh, xs
    tol = check["relative_width"] * abs(star)
    ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row)
    if not ok:
        return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % (
            abs(xs - xh), check["relative_width"])
    return 1.0, None


def forensics_f1(env, named):
    """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer."""
    if not isinstance(named, dict):
        return 0.0, "false_rows is not an object of row and reason"
    rows = [c["row"] for c in env["check"]["rows"]]
    truth = env["reference"]["false_rows"]
    unknown = [r for r in named if r not in set(rows)]
    if unknown:
        return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown))
    reasons = env["check"].get("reasons") or REASONS
    bad = [r for r, why in named.items() if why not in reasons]
    if bad:
        return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons))
    if rows and set(named) == set(rows):
        return 0.0, "every row of the table is named false: a blanket answer"
    found = sum(1 for r, why in named.items() if truth.get(r) == why)
    if not truth and not named:
        return 1.0, None
    precision = found / len(named) if named else 0.0
    recall = found / len(truth) if truth else 0.0
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
    if f1 >= 1.0:
        return 1.0, None
    missed = sorted(set(truth) - set(named))
    wrongly = sorted(set(named) - set(truth))
    wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r])
    said = []
    if missed:
        said.append("%d false row(s) not named" % len(missed))
    if wrongly:
        said.append("%d genuine row(s) named false" % len(wrongly))
    if wrong_reason:
        said.append("%d false row(s) with another reason" % len(wrong_reason))
    return f1, "; ".join(said)


def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None):
    """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record);
    reply_calls: the reply-side log, compared with calls under calls_from="harness"."""
    row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from,
           "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None}
    card, problem = read_card(reply)
    if problem:
        row.update(verdict="no_card", reason=problem)
        return row
    proofs = []
    try:
        problem = engine_problem(env, replay)
        if problem:
            raise Integrity(problem)
        problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row)
        if problem:
            raise Integrity(problem)
        family = env["family"]
        if family in ("tradeoff", "chain_design"):
            graded, reason = score_boundary(env, card, replay, row, proofs)
        elif family == "budget":
            graded, reason = score_budget(env, card, replay, row, proofs)
        elif family == "forensics":
            named = card.get("false_rows")
            if isinstance(named, dict):
                row["named"] = named
            graded, reason = forensics_f1(env, named)
            proofs = [True]
            if reason and graded == 0.0 and not isinstance(named, dict):
                raise Wrong(reason)
        else:
            raise Wrong("unknown family %s" % family)
    except Integrity as problem:
        row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs)))
        return row
    except Wrong as problem:
        row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs)))
        return row
    proofs_hold = int(bool(proofs) and all(proofs))
    correct = int(graded >= 1.0 and reason is None)
    row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1),
               graded=round(graded, 6) if proofs_hold else 0.0,
               verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason)
    return row


def records_for(folder, env_id, calls_from, harness_dir=None):
    """(calls, reply_calls, log_problem) for one environment's reply in folder."""
    reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl"))
    if calls_from == "harness":
        calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl"))
        return calls, reply_calls, log_problem
    return reply_calls, None, None


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("replies")
    parser.add_argument("--engine", required=True)
    parser.add_argument("--only")
    parser.add_argument("--environments", required=True)
    parser.add_argument("--out")
    parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness")
    parser.add_argument("--harness-dir")
    parser.add_argument("--quiet", action="store_true")
    args = parser.parse_args()
    environments = load_environments(args.environments)
    if args.only:
        wanted = set(args.only.split(","))
        environments = [e for e in environments if e["id"] in wanted]
        missing = wanted - {e["id"] for e in environments}
        if missing:
            sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments))
    for env in environments:
        for problem in row_problems(env):
            print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr)
    verifier = open_verifier(args.engine)
    replay = Replay(verifier)
    rows = []
    try:
        for env in environments:
            path = os.path.join(args.replies, env["id"] + ".txt")
            reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else ""
            calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir)
            row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem)
            rows.append(row)
            if not args.quiet:
                print("%-58s reward %d  graded %.4f  %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"],
                                                                 row["reason"] or ""), flush=True)
            replay.seen.clear()
    finally:
        close_verifier(verifier)
    if args.out:
        with open(args.out, "w", encoding="utf-8") as f:
            for row in rows:
                f.write(json.dumps(row) + "\n")
    total = len(rows)
    print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % (
        total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows),
        sum(r["graded"] for r in rows) / total if total else 0.0,
        sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows)))
    by = {}
    for r in rows:
        by.setdefault(r["family"], []).append(r)
    for family in FAMILIES:
        if family in by:
            print("  %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]),
                                                                 sum(r["graded"] for r in by[family]) / len(by[family])))


if __name__ == "__main__":
    main()