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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Comprehensive, matched A/B/C result analysis.

Reports coverage, score, question-type and dataset breakdowns, response/prompt/token
lengths, latency, limit/forced rates, spatial-code size for B/C, score relationships,
and pairwise deltas on exact question intersections. Stored per-question scores are
used directly; ``mean_score`` is not the category-weighted official VSI overall.
"""

from __future__ import annotations

import argparse
import json
import os
import math
import statistics
import random
from collections import Counter, defaultdict
from itertools import combinations
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DEFAULT_DIRS = {h: Path("/root/results") / h for h in "ABCE"}
NUMERIC_FIELDS = (
    "input_token_count",
    "output_token_count",
    "reasoning_token_count",
    "generation_seconds",
    "forced_input_token_count",
)
TEXT_FIELDS = (
    "answer_given",
    "answer_raw",
    "reasoning_text",
    "full_prompt",
    "rendered_prompt",
)


def iter_records(directory):
    root = Path(directory)
    if not root.is_dir():
        return
    for path in sorted(root.rglob("*.json")):
        try:
            with path.open(encoding="utf-8") as stream:
                record = json.load(stream)
        except (OSError, json.JSONDecodeError):
            continue
        if (
            isinstance(record, dict)
            and "question_id" in record
            and "condition" in record
        ):
            yield record


def protocol_selected(protocol, selectors):
    if protocol is None:
        return not selectors
    return not selectors or any(
        protocol == item or ("/" not in item and protocol.startswith(item + "/"))
        for item in selectors
    )


def cell_identity(harness, record):
    protocol = record.get("protocol") or record["condition"].split(":", 1)[0]
    selection = record.get("frame_selection", record.get("input_selection"))
    common = {
        "harness": harness,
        "model": record.get("model"),
        "protocol": protocol,
        "selection": selection,
        "frames": str(record.get("frame_count")),
    }
    if harness in ("B", "C"):
        common.update(
            {
                "format": record.get("spatial_code_format"),
                "depth": record.get("depth"),
                "tracking": record.get("tracking"),
            }
        )
    return tuple(sorted(common.items()))


def identity_dict(identity):
    return dict(identity)


def cell_label(identity):
    d = identity_dict(identity)
    parts = [
        d["harness"],
        d.get("model"),
        d.get("protocol"),
        d.get("selection"),
        d.get("frames"),
    ]
    if d["harness"] in ("B", "C"):
        parts += [d.get("format"), d.get("depth"), d.get("tracking")]
    return "/".join("?" if value is None else str(value) for value in parts)


def comparison_key(identity):
    d = identity_dict(identity)
    return d.get("model"), d.get("protocol"), d.get("selection"), d.get("frames")


def _numbers(records, getter):
    out = []
    for record in records:
        value = getter(record)
        if (
            isinstance(value, (int, float))
            and not isinstance(value, bool)
            and math.isfinite(value)
        ):
            out.append(float(value))
    return out


def numeric_summary(values):
    values = sorted(values)
    if not values:
        return None

    def percentile(p):
        position = (len(values) - 1) * p
        low, high = math.floor(position), math.ceil(position)
        if low == high:
            return values[low]
        return values[low] + (values[high] - values[low]) * (position - low)

    return {
        "n": len(values),
        "mean": statistics.mean(values),
        "median": statistics.median(values),
        "min": values[0],
        "p25": percentile(0.25),
        "p75": percentile(0.75),
        "max": values[-1],
        "stdev": statistics.stdev(values) if len(values) > 1 else 0.0,
    }


def pearson(xs, ys):
    pairs = [
        (float(x), float(y))
        for x, y in zip(xs, ys)
        if isinstance(x, (int, float))
        and isinstance(y, (int, float))
        and not isinstance(x, bool)
        and not isinstance(y, bool)
        and math.isfinite(x)
        and math.isfinite(y)
    ]
    if len(pairs) < 2:
        return None
    x, y = zip(*pairs)
    mx, my = statistics.mean(x), statistics.mean(y)
    dx, dy = [v - mx for v in x], [v - my for v in y]
    denom = math.sqrt(sum(v * v for v in dx) * sum(v * v for v in dy))
    return sum(a * b for a, b in zip(dx, dy)) / denom if denom else None


def spatial_code_bytes(record, cache):
    path = record.get("spatial_code_path")
    if not path:
        return None
    if path not in cache:
        try:
            cache[path] = Path(path).stat().st_size
        except OSError:
            cache[path] = None
    return cache[path]


def breakdown(records, field):
    groups = defaultdict(list)
    for record in records:
        groups[str(record.get(field) or "<missing>")].append(record)
    return {
        name: {
            "count": len(group),
            "mean_score": (
                numeric_summary(_numbers(group, lambda r: r.get("score")))["mean"]
                if _numbers(group, lambda r: r.get("score"))
                else None
            ),
            "scenes": len({r.get("scene") for r in group}),
        }
        for name, group in sorted(groups.items())
    }


def summarize_cell(records, code_cache):
    scores = _numbers(records, lambda r: r.get("score"))
    numeric = {
        field: numeric_summary(_numbers(records, lambda r, f=field: r.get(f)))
        for field in NUMERIC_FIELDS
    }
    text = {
        field
        + "_chars": numeric_summary(
            _numbers(
                records,
                lambda r, f=field: len(r[f]) if isinstance(r.get(f), str) else None,
            )
        )
        for field in TEXT_FIELDS
    }
    code_sizes = _numbers(records, lambda r: spatial_code_bytes(r, code_cache))
    relationships = {}
    measures = {
        **{field: lambda r, f=field: r.get(f) for field in NUMERIC_FIELDS},
        **{
            field
            + "_chars": lambda r, f=field: (
                len(r[f]) if isinstance(r.get(f), str) else None
            )
            for field in TEXT_FIELDS
        },
        "spatial_code_bytes": lambda r: spatial_code_bytes(r, code_cache),
    }
    for name, getter in measures.items():
        pairs = [(r.get("score"), getter(r)) for r in records]
        relationships["score_vs_" + name] = pearson(
            [p[1] for p in pairs], [p[0] for p in pairs]
        )
    return {
        "questions": len(records),
        "unique_question_ids": len({r["question_id"] for r in records}),
        "scenes": len({r.get("scene") for r in records}),
        "mean_score": statistics.mean(scores) if scores else None,
        "score_distribution": numeric_summary(scores),
        "question_types": breakdown(records, "question_type"),
        "datasets": breakdown(records, "dataset"),
        "numeric": numeric,
        "text_lengths": text,
        "rates": {
            "hit_token_limit": (
                statistics.mean(bool(r.get("hit_token_limit")) for r in records)
                if records
                else None
            ),
            "reasoning_hit_limit": (
                statistics.mean(bool(r.get("reasoning_hit_limit")) for r in records)
                if records
                else None
            ),
            "reasoning_present": (
                statistics.mean(
                    bool(r.get("reasoning_text") or r.get("reasoning_raw"))
                    for r in records
                )
                if records
                else None
            ),
            "forced": (
                statistics.mean(bool(r.get("forced")) for r in records)
                if records
                else None
            ),
            "scored": len(scores) / len(records) if records else None,
        },
        "spatial_codes": {
            "records_with_path": sum(bool(r.get("spatial_code_path")) for r in records),
            "unique_paths": len(
                {
                    r.get("spatial_code_path")
                    for r in records
                    if r.get("spatial_code_path")
                }
            ),
            "readable_file_bytes": numeric_summary(code_sizes),
        },
        "relationships": relationships,
    }


def paired_breakdown(x, y, common, field):
    groups = defaultdict(list)
    for qid in common:
        name = str(x[qid].get(field) or y[qid].get(field) or "<missing>")
        groups[name].append(y[qid].get("score") - x[qid].get("score"))
    return {
        name: {"count": len(vals), "mean_delta": statistics.mean(vals)}
        for name, vals in sorted(groups.items())
        if vals
    }


def _scene_bootstrap(x, y, common, iterations=1000, seed=0):
    by_scene = defaultdict(list)
    for qid in common:
        by_scene[str(x[qid].get("scene") or y[qid].get("scene") or "<missing>")].append(
            y[qid]["score"] - x[qid]["score"]
        )
    if not by_scene:
        return {
            "scenes": 0,
            "iterations": iterations,
            "ci_low": None,
            "ci_high": None,
            "p_value": None,
        }
    scenes = sorted(by_scene)
    rng = random.Random(seed)
    draws = []
    for _ in range(iterations):
        values = []
        for _ in scenes:
            values.extend(by_scene[rng.choice(scenes)])
        draws.append(statistics.mean(values))
    draws.sort()
    low = int(0.025 * iterations)
    high = min(iterations - 1, int(0.975 * iterations))
    below = sum(v <= 0 for v in draws) / iterations
    above = sum(v >= 0 for v in draws) / iterations
    return {
        "scenes": len(scenes),
        "iterations": iterations,
        "seed": seed,
        "confidence": 0.95,
        "ci_low": draws[low],
        "ci_high": draws[high],
        "p_value": max(1 / iterations, min(1.0, 2 * min(below, above))),
    }


def paired_report(x_records, y_records):
    x = {
        r["question_id"]: r
        for r in x_records
        if isinstance(r.get("score"), (int, float))
    }
    y = {
        r["question_id"]: r
        for r in y_records
        if isinstance(r.get("score"), (int, float))
    }
    common = sorted(set(x) & set(y))
    deltas = [y[q]["score"] - x[q]["score"] for q in common]
    solved_x = {q for q in common if x[q]["score"] >= 1.0}
    solved_y = {q for q in common if y[q]["score"] >= 1.0}
    union = solved_x | solved_y
    telemetry = {}
    for field in NUMERIC_FIELDS:
        vals = [
            y[q].get(field) - x[q].get(field)
            for q in common
            if isinstance(x[q].get(field), (int, float))
            and isinstance(y[q].get(field), (int, float))
        ]
        telemetry[field + "_delta"] = numeric_summary(vals)
    return {
        "common_questions": len(common),
        "x_full_questions": len(x),
        "y_full_questions": len(y),
        "mean_score_delta_y_minus_x": statistics.mean(deltas) if deltas else None,
        "score_delta_distribution": numeric_summary(deltas),
        "wins_y": sum(d > 0 for d in deltas),
        "ties": sum(d == 0 for d in deltas),
        "wins_x": sum(d < 0 for d in deltas),
        "scene_clustered_bootstrap": _scene_bootstrap(x, y, common),
        "solved_overlap": {
            "x": len(solved_x),
            "y": len(solved_y),
            "both": len(solved_x & solved_y),
            "only_x": len(solved_x - solved_y),
            "only_y": len(solved_y - solved_x),
            "jaccard": len(solved_x & solved_y) / len(union) if union else None,
        },
        "by_question_type": paired_breakdown(x, y, common, "question_type"),
        "by_dataset": paired_breakdown(x, y, common, "dataset"),
        "telemetry_deltas": telemetry,
    }


def analyze(directories=None, protocols=()):
    directories = directories or DEFAULT_DIRS
    cells = defaultdict(list)
    for harness, directory in directories.items():
        for record in iter_records(directory):
            protocol = record.get("protocol") or record["condition"].split(":", 1)[0]
            if protocol_selected(protocol, protocols):
                cells[cell_identity(harness, record)].append(record)
    code_cache = {}
    report = {"cells": {}, "comparison_groups": {}}
    for identity, records in cells.items():
        report["cells"][cell_label(identity)] = {
            "identity": identity_dict(identity),
            "summary": summarize_cell(records, code_cache),
        }
    grouped = defaultdict(list)
    for identity in cells:
        grouped[comparison_key(identity)].append(identity)
    for key, identities in grouped.items():
        name = "/".join("?" if v is None else str(v) for v in key)
        pairs = {}
        for first, second in combinations(sorted(identities, key=cell_label), 2):
            pairs[cell_label(first) + " -> " + cell_label(second)] = paired_report(
                cells[first], cells[second]
            )
        id_sets = [{r["question_id"] for r in cells[i]} for i in identities]
        report["comparison_groups"][name] = {
            "cells": [cell_label(i) for i in identities],
            "all_cell_common_questions": (
                len(set.intersection(*id_sets)) if id_sets else 0
            ),
            "pairwise": pairs,
        }
    return report


def main():
    parser = argparse.ArgumentParser()
    for harness in "abc":
        parser.add_argument(f"--{harness}-results-dir", default=None)
    parser.add_argument(
        "--protocol",
        action="append",
        default=[],
        help="repeatable; select base or thinking protocol families",
    )
    parser.add_argument(
        "--output-dir",
        default=str(ROOT / "reports"),
        help="report directory (default: workspace/reports)",
    )
    parser.add_argument(
        "--json-out",
        default=None,
        help="override the JSON report path (default: <output-dir>/comprehensive.json)",
    )
    args = parser.parse_args()
    dirs = {
        h.upper(): Path(getattr(args, f"{h}_results_dir") or DEFAULT_DIRS[h.upper()])
        for h in "abc"
    }
    report = analyze(dirs, args.protocol)
    text = json.dumps(report, indent=1)
    output_path = (
        Path(args.json_out)
        if args.json_out
        else Path(args.output_dir) / "comprehensive.json"
    )
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(text + "\n", encoding="utf-8")
    print(f"wrote {output_path}")


# --- Modular profile-driven interface (v2) ---

# Built-in, versioned harness profiles.
PROFILE_VERSION = 1
BUILTINS = {
    "A": {
        "letter": "A",
        "kind": "vlm",
        "input_source": "frames",
        "axes": ["model", "protocol", "selection", "frames"],
        "capabilities": ["tokens", "latency", "reasoning", "frames"],
    },
    "B": {
        "letter": "B",
        "kind": "vlm",
        "input_source": "perceived",
        "axes": [
            "model",
            "protocol",
            "format",
            "depth",
            "tracking",
            "selection",
            "frames",
        ],
        "capabilities": ["tokens", "latency", "reasoning", "spatial_code"],
    },
    "C": {
        "letter": "C",
        "kind": "vlm",
        "input_source": "frames_perceived",
        "axes": [
            "model",
            "protocol",
            "format",
            "depth",
            "tracking",
            "selection",
            "frames",
        ],
        "capabilities": ["tokens", "latency", "reasoning", "frames", "spatial_code"],
    },
    "F": {
        "letter": "F",
        "kind": "solver",
        "input_source": "dynamic",
        "axes": [
            "source",
            "depth",
            "tracking",
            "selection",
            "frames",
            "format",
            "spatial_code_model",
        ],
        "capabilities": ["spatial_code", "solver"],
    },
}


def validate_profile(profile):
    p = dict(profile)
    letter = str(p.get("letter", "")).upper()
    if len(letter) != 1 or not letter.isalpha():
        raise ValueError("profile letter must be one alphabetic character")
    p["letter"] = letter
    p.setdefault("kind", "generic")
    p.setdefault("input_source", "unknown")
    p.setdefault("axes", ["model", "protocol"])
    p.setdefault("capabilities", [])
    p["profile_version"] = PROFILE_VERSION
    return p


def load_profile(letter, path=None):
    letter = letter.upper()
    if path:
        p = json.loads(Path(path).read_text())
        p.setdefault("letter", letter)
        if p["letter"].upper() != letter:
            raise ValueError(f"profile letter mismatch for {letter}")
        return validate_profile(p)
    return validate_profile(
        BUILTINS.get(
            letter,
            {
                "letter": letter,
                "kind": "generic",
                "input_source": "unknown",
                "axes": [
                    "model",
                    "protocol",
                    "format",
                    "depth",
                    "tracking",
                    "selection",
                    "frames",
                ],
            },
        )
    )


ANALYSIS_VERSION = 2


def discover_records(letter, directory, profile, protocols=(), spatial_codes_dir=None):
    root = Path(directory)
    records = []
    warnings = []
    if not root.is_dir():
        return records, [{"code": "missing_directory", "path": str(root)}]
    for path in sorted(root.rglob("*.json")):
        if path.name.startswith("_"):
            continue
        try:
            record = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            warnings.append(
                {"code": "unreadable_json", "path": str(path), "detail": str(exc)}
            )
            continue
        if (
            not isinstance(record, dict)
            or record.get("question_id") is None
            or record.get("score") is None
        ):
            warnings.append({"code": "not_question_record", "path": str(path)})
            continue
        record = dict(record)
        record["_result_path"] = str(path)
        record["_relative_path"] = path.relative_to(root).parts
        record = _normalize_record(letter, record, profile)
        code_path = record.get("spatial_code_path")
        if code_path and not Path(code_path).is_file() and spatial_codes_dir:
            marker = "spatial codes/"
            suffix = (
                str(code_path).split(marker, 1)[-1]
                if marker in str(code_path)
                else None
            )
            candidate = Path(spatial_codes_dir) / suffix if suffix else None
            if candidate and candidate.is_file():
                record["spatial_code_path"] = str(candidate)
            else:
                warnings.append(
                    {
                        "code": "unresolved_spatial_code_path",
                        "path": str(path),
                        "recorded_path": str(code_path),
                    }
                )
        if letter != "F" and not protocol_selected(record.get("protocol"), protocols):
            continue
        records.append(record)
    return records, warnings


def _normalize_record(letter, r, profile):
    r["format"] = r.get("spatial_code_format") or r.get("format")
    r["selection"] = (
        r.get("frame_selection") or r.get("input_selection") or r.get("input")
    )
    r["frames"] = r.get("frame_count") or r.get("number_of_frames")
    if not r.get("protocol") and r.get("condition") and letter != "F":
        r["protocol"] = r["condition"].split(":", 1)[0]
    if letter == "F":
        parts = list(r.get("_relative_path", ()))
        top = parts[0].lower() if parts else ""
        r["source"] = "perceived"
        offset = 1
        if top == "perceived":
            r["depth"] = r.get("depth") or (parts[1] if len(parts) > 1 else None)
            offset = 2
        elif top in ("metric", "relative"):
            r["depth"] = r.get("depth") or top
        r["tracking"] = r.get("tracking") or (
            parts[offset] if len(parts) > offset else None
        )
        r["selection"] = r.get("selection") or (
            parts[offset + 1] if len(parts) > offset + 1 else None
        )
        r["frames"] = r.get("frames") or (
            parts[offset + 2] if len(parts) > offset + 2 else None
        )
        candidate = parts[offset + 3] if len(parts) > offset + 3 else None
        if candidate and not candidate.startswith("scene") and len(candidate) != 10:
            r["format"] = r.get("format") or candidate
        r["spatial_code_model"] = r.get("spatial_code_model")
        r["protocol"] = None
    return r


def modular_identity(letter, record, profile):
    values = {"harness": letter}
    for axis in profile["axes"]:
        values[axis] = str(record.get(axis)) if record.get(axis) is not None else None
    return tuple(sorted(values.items()))


def modular_label(identity):
    d = dict(identity)
    return "/".join(
        [d.pop("harness")] + [f"{k}={v or '?'}" for k, v in sorted(d.items())]
    )


def _controlled(first, second, profile):
    a, b = dict(first), dict(second)
    diffs = [axis for axis in profile["axes"] if a.get(axis) != b.get(axis)]
    return len(diffs) == 1, diffs


def _compatible(a, b, profiles):
    x, y = dict(a), dict(b)
    lx, ly = x["harness"], y["harness"]
    warnings = []
    if lx == ly:
        return False, [], ["same_harness"]
    # F source semantics.
    f = x if lx == "F" else y if ly == "F" else None
    other = y if lx == "F" else x
    if f:
        expected = "perceived" if other["harness"] in ("B", "C") else None
        if expected and f.get("source") != expected:
            return False, [], ["incompatible_F_source"]
    shared = []
    for axis in ("model", "format", "depth", "tracking", "selection", "frames"):
        av, bv = x.get(axis), y.get(axis)
        if axis == "model" and f:
            continue
        if av is not None and bv is not None:
            if av != bv:
                return False, [], [f"conflicting_{axis}"]
            shared.append(axis)
        else:
            warnings.append(f"unmatched_{axis}")
    if not f and x.get("protocol") is not None and y.get("protocol") is not None:
        if x["protocol"] != y["protocol"]:
            return False, [], ["conflicting_protocol"]
        shared.append("protocol")
    return True, shared, warnings


def _generated_at():
    return os.environ.get("VSI_ANALYSIS_GENERATED_AT", "reproducible")


def analyze_modular(
    cells, profiles, protocols=(), requested_pairs=(), spatial_codes_dir=None
):
    all_cells = defaultdict(list)
    warnings = {}
    sources = {}
    for letter, directory in cells.items():
        recs, warns = discover_records(
            letter, directory, profiles[letter], protocols, spatial_codes_dir
        )
        warnings[letter] = warns
        sources[letter] = str(directory)
        for r in recs:
            all_cells[modular_identity(letter, r, profiles[letter])].append(r)
    cache = {}
    per = {
        letter: {
            "manifest": {
                "analysis_version": ANALYSIS_VERSION,
                "profile_version": PROFILE_VERSION,
                "generated_at": _generated_at(),
                "letter": letter,
                "profile": profiles[letter],
                "source": sources[letter],
                "protocols": list(protocols),
            },
            "cells": {},
            "within_harness_comparisons": {},
            "integrity_warnings": warnings[letter],
        }
        for letter in cells
    }
    for ident, recs in all_cells.items():
        per[dict(ident)["harness"]]["cells"][modular_label(ident)] = {
            "identity": dict(ident),
            "summary": summarize_cell(recs, cache),
        }
    for letter in cells:
        ids = [i for i in all_cells if dict(i)["harness"] == letter]
        for a, b in combinations(ids, 2):
            ok, diffs = _controlled(a, b, profiles[letter])
            if ok:
                per[letter]["within_harness_comparisons"][
                    modular_label(a) + " -> " + modular_label(b)
                ] = {
                    "varied_axis": diffs[0],
                    **paired_report(all_cells[a], all_cells[b]),
                }
    allowed = {tuple(sorted(p)) for p in requested_pairs}
    cross = {}
    ids = list(all_cells)
    for a, b in combinations(ids, 2):
        letters = tuple(sorted((dict(a)["harness"], dict(b)["harness"])))
        if letters[0] == letters[1] or (allowed and letters not in allowed):
            continue
        ok, shared, warns = _compatible(a, b, profiles)
        if ok:
            cross[modular_label(a) + " -> " + modular_label(b)] = {
                "letters": letters,
                "shared_axes": shared,
                "alignment_warnings": warns,
                **paired_report(all_cells[a], all_cells[b]),
            }
    manifest = {
        "analysis_version": ANALYSIS_VERSION,
        "profile_version": PROFILE_VERSION,
        "generated_at": _generated_at(),
        "letters": sorted(cells),
        "sources": sources,
        "protocols": list(protocols),
        "requested_pairs": [":".join(p) for p in requested_pairs],
    }
    return per, {
        "manifest": manifest,
        "cross_harness_comparisons": cross,
        "harness_summaries": {
            l: {
                "cell_count": len(per[l]["cells"]),
                "warning_count": len(per[l]["integrity_warnings"]),
            }
            for l in per
        },
    }


def parse_assignment(value, option):
    if "=" not in value:
        raise argparse.ArgumentTypeError(f"{option} must be LETTER=PATH")
    letter, path = value.split("=", 1)
    letter = letter.upper()
    if len(letter) != 1 or not letter.isalpha() or letter == "D":
        raise argparse.ArgumentTypeError(
            "letter must be one alphabetic character other than D"
        )
    return letter, path


def export_reports(per, combined, output_dir):
    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)
    paths = []
    for letter, report in sorted(per.items()):
        path = out / f"{letter}_report.json"
        path.write_text(json.dumps(report, indent=1) + "\n")
        paths.append(path)
    if len(per) > 1:
        name = "".join(sorted(per)) + "_report.json"
        path = out / name
        path.write_text(json.dumps(combined, indent=1) + "\n")
        paths.append(path)
    return paths


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--cell",
        action="append",
        default=[],
        help="repeatable LETTER=PATH; D is removed",
    )
    parser.add_argument(
        "--profile", action="append", default=[], help="optional LETTER=profile.json"
    )
    parser.add_argument(
        "--compare",
        action="append",
        default=[],
        help="optional pair restriction, e.g. A:B",
    )
    parser.add_argument(
        "--protocol",
        action="append",
        default=[],
        help="repeatable; select base or thinking protocol families",
    )
    parser.add_argument("--output-dir", default=str(ROOT / "reports"))
    parser.add_argument(
        "--spatial-codes-dir",
        default=None,
        help="optional local root used to rebase stale recorded code paths",
    )
    for h in "abce":
        parser.add_argument(f"--{h}-results-dir", default=None, help=argparse.SUPPRESS)
    args = parser.parse_args()
    cells = dict(parse_assignment(v, "--cell") for v in args.cell)
    for h in "abce":
        value = getattr(args, f"{h}_results_dir")
        if value:
            cells[h.upper()] = value
    if not cells:
        parser.error("provide at least one --cell LETTER=PATH")
    profile_paths = dict(parse_assignment(v, "--profile") for v in args.profile)
    profiles = {
        letter: load_profile(letter, profile_paths.get(letter)) for letter in cells
    }
    pairs = []
    for value in args.compare:
        bits = [x.upper() for x in value.split(":")]
        if len(bits) != 2 or any(x not in cells for x in bits):
            parser.error(f"invalid --compare {value}")
        pairs.append(tuple(bits))
    per, combined = analyze_modular(
        cells, profiles, args.protocol, pairs, args.spatial_codes_dir
    )
    for path in export_reports(per, combined, args.output_dir):
        print(f"wrote {path}")


# Consolidated analysis helpers formerly split across stats/solvability/sufficiency/audits.
def _official_scores(records):
    records = list(records)
    try:
        import importlib.util, os

        path = os.environ.get(
            "HARNESS_OFFICIAL_EVAL",
            "/root/data/thinking-in-space/lmms_eval/tasks/vsibench/utils.py",
        )
        spec = importlib.util.spec_from_file_location(
            "analysis_vsi_official_eval", path
        )
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        docs = [
            {
                "question_type": r["question_type"],
                "ground_truth": r.get("answer_expected"),
                r["metric"]: r["score"],
            }
            for r in records
        ]
        return module.vsibench_aggregate_results(docs)
    except (OSError, ImportError, AttributeError, TypeError):
        scores = [
            r.get("score") for r in records if isinstance(r.get("score"), (int, float))
        ]
        return {
            "overall": statistics.mean(scores) * 100 if scores else None,
            "scoring_mode": "stored_per_question_mean_fallback",
        }


def holm_bonferroni(p_values):
    ordered = sorted(p_values.items(), key=lambda item: item[1])
    total = len(ordered)
    out = {}
    running = 0.0
    for rank, (name, p) in enumerate(ordered):
        running = max(running, min(1.0, (total - rank) * p))
        out[name] = running
    return out


def solved_set_overlap(cells, threshold=1.0):
    maps = {
        name: {r["question_id"]: r.get("score") for r in records}
        for name, records in cells.items()
    }
    common = set.intersection(*(set(m) for m in maps.values())) if maps else set()
    solved = {
        n: {q for q in common if v[q] is not None and v[q] >= threshold}
        for n, v in maps.items()
    }
    pairs = {}
    for a, b in combinations(sorted(solved), 2):
        union = solved[a] | solved[b]
        pairs[f"{a}|{b}"] = {
            "jaccard": len(solved[a] & solved[b]) / len(union) if union else None,
            "both": len(solved[a] & solved[b]),
            f"only_{a}": len(solved[a] - solved[b]),
            f"only_{b}": len(solved[b] - solved[a]),
        }
    return {
        "questions": len(common),
        "solved": {n: len(v) for n, v in solved.items()},
        "pairs": pairs,
    }


def sufficiency_decomposition(vlm_records, solver_records, threshold=1.0, exclude=()):
    cert = {
        r["question_id"]: r.get("score") is not None and r["score"] >= threshold
        for r in solver_records
    }
    buckets = {"certified": [], "uncertified": []}
    for r in vlm_records:
        if r.get("question_type") in set(exclude) or r.get("question_id") not in cert:
            continue
        buckets["certified" if cert[r["question_id"]] else "uncertified"].append(
            r.get("score")
        )

    def summary(vals):
        valid = [v for v in vals if isinstance(v, (int, float))]
        correct = sum(v >= threshold for v in valid)
        return {
            "count": len(vals),
            "mean_score": statistics.mean(valid) if valid else None,
            "vlm_correct": correct,
            "vlm_wrong": len(vals) - correct,
        }

    return {name: summary(vals) for name, vals in buckets.items()}


def solver_depth_table(records):
    try:
        from symbolic import adapters, solver
    except ImportError:
        return {
            "status": "unavailable",
            "reason": "symbolic solver imports unavailable",
        }
    cache = {}
    buckets = defaultdict(list)
    for r in records:
        path = r.get("spatial_code_path")
        if not path:
            continue
        try:
            if path not in cache:
                cache[path] = adapters.adapt_spatial_code(
                    json.loads(Path(path).read_text())
                )
            solver.answer(
                r["question_type"], r["question"], r.get("options"), cache[path]
            )
            depth = solver.LAST_ANSWER_OPS.get("total")
        except (OSError, KeyError, ValueError):
            continue
        if depth is not None and isinstance(r.get("score"), (int, float)):
            buckets[
                (
                    "0-2"
                    if depth <= 2
                    else "3-8" if depth <= 8 else "9-20" if depth <= 20 else "21-inf"
                )
            ].append((depth, r["score"]))
    return {
        k: {
            "count": len(v),
            "mean_depth": statistics.mean(x for x, _ in v),
            "mean_score": statistics.mean(y for _, y in v),
        }
        for k, v in buckets.items()
    }


_NUMBER_RE = __import__("re").compile(r"[-+]?\d+(?:\.\d+)?")


def deterministic_cot_audit(records, tolerance=0.01):
    def nums(value):
        return [float(x) for x in _NUMBER_RE.findall(str(value or ""))]

    audits = []
    cache = {}
    for r in records:
        reasoning = r.get("reasoning_text")
        path = r.get("spatial_code_path")
        if not reasoning or not path:
            continue
        try:
            if path not in cache:
                cache[path] = nums(Path(path).read_text())
        except OSError:
            continue
        sources = (
            cache[path]
            + nums(r.get("question"))
            + sum((nums(x) for x in r.get("options") or []), [])
        )
        cited = nums(reasoning)
        fabricated = [
            v
            for v in cited
            if not (abs(v) <= 12 and v.is_integer())
            and not any(abs(v - x) <= tolerance * max(1, abs(x)) for x in sources)
        ]
        audits.append(
            {
                "question_id": r["question_id"],
                "score": r.get("score"),
                "cited": len(cited),
                "fabricated": len(fabricated),
            }
        )
    wrong = [a for a in audits if a["score"] is not None and a["score"] < 1]
    bad = [a for a in wrong if a["fabricated"]]
    return {
        "audited": len(audits),
        "wrong": len(wrong),
        "wrong_with_fabrication": len(bad),
        "fabrication_share_of_wrong": len(bad) / len(wrong) if wrong else None,
    }


def generate_letter(
    letter,
    results_dir,
    protocols=(),
    output_dir=None,
    spatial_codes_dir=None,
    profile_path=None,
):
    letter = letter.upper()
    profile = load_profile(letter, profile_path)
    per, combined = analyze_modular(
        {letter: Path(results_dir)}, {letter: profile}, protocols, (), spatial_codes_dir
    )
    paths = export_reports(per, combined, output_dir or ROOT / "reports")
    return {"report": per[letter], "path": paths[0]}


def generate(
    cells,
    protocols=(),
    comparisons=(),
    output_dir=None,
    profile_paths=None,
    spatial_codes_dir=None,
):
    normalized = {str(k).upper(): Path(v) for k, v in cells.items()}
    profile_paths = {str(k).upper(): v for k, v in (profile_paths or {}).items()}
    profiles = {l: load_profile(l, profile_paths.get(l)) for l in normalized}
    pairs = []
    for pair in comparisons:
        pair = tuple(
            x.upper() for x in (pair.split(":") if isinstance(pair, str) else pair)
        )
        if len(pair) != 2 or any(x not in normalized for x in pair):
            raise ValueError(f"invalid comparison {pair}")
        pairs.append(pair)
    per, combined = analyze_modular(
        normalized, profiles, protocols, pairs, spatial_codes_dir
    )
    paths = export_reports(per, combined, output_dir or ROOT / "reports")
    return {"letter_reports": per, "combined_report": combined, "paths": paths}


def main():
    parser = argparse.ArgumentParser(
        description="Generate arbitrary mixed letter reports; D is removed."
    )
    parser.add_argument("--cell", action="append", required=True)
    parser.add_argument("--profile", action="append", default=[])
    parser.add_argument("--compare", action="append", default=[])
    parser.add_argument("--protocol", action="append", default=[])
    parser.add_argument("--output-dir", default=str(ROOT / "reports"))
    parser.add_argument("--spatial-codes-dir", default=None)
    args = parser.parse_args()
    cells = dict(parse_assignment(v, "--cell") for v in args.cell)
    profiles = dict(parse_assignment(v, "--profile") for v in args.profile)
    try:
        result = generate(
            cells,
            args.protocol,
            args.compare,
            args.output_dir,
            profiles,
            args.spatial_codes_dir,
        )
    except ValueError as exc:
        parser.error(str(exc))
    for path in result["paths"]:
        print(f"wrote {path}")


if __name__ == "__main__":
    main()