File size: 49,227 Bytes
2f49b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""POSA Bench: validate, run, score, and aggregate the public benchmark."""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import math
import os
import random
import re
import statistics
import subprocess
import sys
import time
import unicodedata
import urllib.error
import urllib.request
import uuid
from collections import Counter
from pathlib import Path
from typing import Any, Iterable


ROOT = Path(__file__).resolve().parent
DEFAULT_CASES = ROOT / "data" / "questions.v1.jsonl"
DEFAULT_PROFILES = ROOT / "data" / "device-profiles.v1.json"
DEFAULT_MODELS = ROOT / "data" / "models.v1.json"
CITATION_RE = re.compile(r"\[\s*(S\d+)\s*]", re.IGNORECASE)
TOKEN_RE = re.compile(r"\w+|[^\w\s]", re.UNICODE)


def read_json(path: Path) -> dict[str, Any]:
    with path.open(encoding="utf-8") as handle:
        value = json.load(handle)
    if not isinstance(value, dict):
        raise ValueError(f"{path} must contain a JSON object")
    return value


def read_jsonl(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    with path.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError as exc:
                raise ValueError(f"{path}:{line_number}: {exc}") from exc
            if not isinstance(row, dict):
                raise ValueError(f"{path}:{line_number}: expected an object")
            rows.append(row)
    return rows


def write_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        json.dump(value, handle, indent=2, sort_keys=True, ensure_ascii=False)
        handle.write("\n")


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def normalize(value: str) -> str:
    value = unicodedata.normalize("NFKD", value).lower()
    value = value.replace("‐", "-").replace("‑", "-").replace("–", "-").replace("—", "-")
    value = re.sub(r"[^\w\s.-]", " ", value)
    return re.sub(r"\s+", " ", value).strip()


def rule_matches(answer: str, rule: dict[str, Any]) -> bool:
    normalized = normalize(answer)
    if "all_of" in rule:
        return all(normalize(str(term)) in normalized for term in rule["all_of"])
    return any(normalize(str(term)) in normalized for term in rule.get("any_of", []))


def score_answer(case: dict[str, Any], answer: str) -> dict[str, Any]:
    claims = case["required_claims"]
    matched: list[str] = []
    missing: list[str] = []
    earned = total = critical_earned = critical_total = 0.0
    for claim in claims:
        weight = float(claim.get("weight", 1))
        total += weight
        is_match = rule_matches(answer, claim)
        if is_match:
            matched.append(claim["id"])
            earned += weight
        else:
            missing.append(claim["id"])
        if claim.get("critical", False):
            critical_total += weight
            if is_match:
                critical_earned += weight

    forbidden = [rule for rule in case.get("forbidden_claims", []) if rule_matches(answer, rule)]
    markers = [marker.upper() for marker in CITATION_RE.findall(answer)]
    valid_ids = {source["id"].upper() for source in case["evidence"]}
    valid_markers = [marker for marker in markers if marker in valid_ids]
    citation_validity = len(valid_markers) / len(markers) if markers else 0.0
    critical_forbidden = [rule["id"] for rule in forbidden if rule.get("critical", False)]
    claim_recall = earned / total if total else 1.0
    critical_recall = critical_earned / critical_total if critical_total else 1.0
    passed = not missing and not forbidden and bool(valid_markers) and citation_validity == 1.0
    return {
        "id": case["id"],
        "passed": passed,
        "claim_recall": round(claim_recall * 100, 4),
        "critical_claim_recall": round(critical_recall * 100, 4),
        "matched_claims": matched,
        "missing_claims": missing,
        "forbidden_claims": [rule["id"] for rule in forbidden],
        "critical_forbidden_claims": critical_forbidden,
        "citations": markers,
        "valid_citations": valid_markers,
        "citation_present": bool(markers),
        "citation_validity": round(citation_validity * 100, 4),
    }


def percentile(values: Iterable[float], fraction: float) -> float | None:
    ordered = sorted(float(value) for value in values if value is not None)
    if not ordered:
        return None
    index = max(0, math.ceil(fraction * len(ordered)) - 1)
    return ordered[index]


def nested_number(row: dict[str, Any], *paths: tuple[str, ...]) -> float | None:
    for path in paths:
        value: Any = row
        for key in path:
            if not isinstance(value, dict) or key not in value:
                value = None
                break
            value = value[key]
        if isinstance(value, (int, float)) and not isinstance(value, bool):
            return float(value)
    return None


def decode_rate(row: dict[str, Any]) -> float | None:
    direct = nested_number(row, ("decode_tokens_per_second",), ("decodeTokensPerSecond",))
    if direct is not None:
        return direct
    tokens = nested_number(row, ("completion_tokens",), ("completionTokens",))
    generation = nested_number(row, ("timings", "generationMillis"), ("generation_ms",))
    ttft = nested_number(row, ("timings", "ttftMillis"), ("ttft_ms",))
    if tokens is None or generation is None or generation <= 0:
        return None
    decode_ms = generation - (ttft or 0)
    return tokens / (decode_ms / 1000.0) if decode_ms > 0 else None


def load_profiles(path: Path) -> dict[str, dict[str, Any]]:
    return {profile["id"]: profile for profile in read_json(path)["profiles"]}


def validate_cases(cases: list[dict[str, Any]]) -> list[str]:
    errors: list[str] = []
    ids = [case.get("id") for case in cases]
    if len(cases) != 25:
        errors.append(f"expected exactly 25 cases, found {len(cases)}")
    duplicates = [item for item, count in Counter(ids).items() if count > 1]
    if duplicates:
        errors.append(f"duplicate case IDs: {duplicates}")
    for index, case in enumerate(cases, 1):
        prefix = f"case {index} ({case.get('id', 'missing-id')})"
        for field in ("id", "version", "category", "task", "question", "evidence", "required_claims"):
            if not case.get(field):
                errors.append(f"{prefix}: missing {field}")
        source_ids = [source.get("id") for source in case.get("evidence", [])]
        if len(source_ids) != len(set(source_ids)):
            errors.append(f"{prefix}: duplicate evidence IDs")
        for source in case.get("evidence", []):
            for field in ("id", "title", "publisher", "url", "text"):
                if not source.get(field):
                    errors.append(f"{prefix}: evidence missing {field}")
        claim_ids: list[str] = []
        for claim in case.get("required_claims", []) + case.get("forbidden_claims", []):
            claim_ids.append(claim.get("id"))
            if bool(claim.get("any_of")) == bool(claim.get("all_of")):
                errors.append(f"{prefix}: claim {claim.get('id')} needs exactly one of any_of/all_of")
        if len(claim_ids) != len(set(claim_ids)):
            errors.append(f"{prefix}: duplicate claim IDs")
    return errors


def validate_models(manifest: dict[str, Any]) -> list[str]:
    errors: list[str] = []
    runtime = manifest.get("common_runtime", {})
    if not runtime.get("revision"):
        errors.append("model manifest: common runtime revision is required")
    candidates = manifest.get("candidates")
    if not isinstance(candidates, list) or len(candidates) < 4:
        return errors + ["model manifest: at least four candidates are required"]
    ids = [candidate.get("id") for candidate in candidates]
    if len(ids) != len(set(ids)):
        errors.append("model manifest: duplicate candidate IDs")
    for candidate in candidates:
        label = candidate.get("id", "missing-id")
        for field in ("id", "publisher", "repository", "revision", "artifact", "artifact_bytes",
                      "artifact_sha256", "quantization", "license", "source_kind", "status"):
            if candidate.get(field) in (None, "") and not (
                field == "artifact_sha256" and str(candidate.get("status", "")).startswith("blocked")
            ):
                errors.append(f"model {label}: missing {field}")
        if candidate.get("status") in ("ready", "ready-fallback"):
            digest = candidate.get("artifact_sha256", "")
            if not re.fullmatch(r"[0-9a-f]{64}", str(digest)):
                errors.append(f"model {label}: ready artifact needs a SHA-256")
    return errors


def make_prompt(case: dict[str, Any]) -> str:
    evidence = "\n\n".join(
        f"[{source['id']}] {source['title']} — {source['publisher']}\n{source['text']}"
        for source in case["evidence"]
    )
    return (
        "Answer the user's question using only the evidence below. "
        "Give concise, actionable guidance. Cite every factual paragraph with the supplied source ID such as [S1]. "
        "If the evidence cannot support the requested answer, say so clearly; do not fill gaps from memory.\n\n"
        f"USER QUESTION\n{case['question']}\n\nEVIDENCE\n{evidence}"
    )


def run_openai_case(base_url: str, model: str, case: dict[str, Any], api_key: str | None,
                    temperature: float, max_tokens: int, seed: int,
                    extra_body: dict[str, Any] | None = None) -> dict[str, Any]:
    url = base_url.rstrip("/") + "/chat/completions"
    body = {
        "model": model,
        "messages": [
            {"role": "system", "content": "You are POSA, an offline source-grounded field assistant."},
            {"role": "user", "content": make_prompt(case)},
        ],
        "temperature": temperature,
        "max_tokens": max_tokens,
        "seed": seed,
        "stream": True,
        "stream_options": {"include_usage": True},
    }
    body.update(extra_body or {})
    headers = {"Content-Type": "application/json", "Accept": "text/event-stream"}
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"
    request = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers, method="POST")
    started = time.perf_counter()
    first_token: float | None = None
    chunks: list[str] = []
    usage: dict[str, Any] = {}
    try:
        with urllib.request.urlopen(request, timeout=180) as response:
            for raw_line in response:
                line = raw_line.decode("utf-8", errors="replace").strip()
                if not line.startswith("data:"):
                    continue
                payload = line[5:].strip()
                if payload == "[DONE]":
                    break
                event = json.loads(payload)
                usage = event.get("usage") or usage
                choices = event.get("choices") or []
                delta = choices[0].get("delta", {}) if choices else {}
                text = delta.get("content") or ""
                if text and first_token is None:
                    first_token = time.perf_counter()
                chunks.append(text)
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"endpoint returned HTTP {exc.code}: {detail[:500]}") from exc
    ended = time.perf_counter()
    return {
        "id": case["id"],
        "answer": "".join(chunks).strip(),
        "seed": seed,
        "elapsedMillis": round((ended - started) * 1000, 3),
        "timings": {
            "ttftMillis": round(((first_token or ended) - started) * 1000, 3),
            "generationMillis": round((ended - started) * 1000, 3),
        },
        "completionTokens": usage.get("completion_tokens"),
    }


def capture_android_server_diagnostics(adb: str) -> dict[str, Any]:
    pid = subprocess.run(
        [adb, "shell", "pidof", "llama-server"], check=False, capture_output=True, text=True,
    ).stdout.strip().split()
    diagnostics: dict[str, Any] = {}
    if pid:
        memory = subprocess.run(
            [adb, "shell", "dumpsys", "meminfo", pid[0], "--local"],
            check=False,
            capture_output=True,
            text=True,
        ).stdout
        match = re.search(r"TOTAL PSS:\s+(\d+)", memory)
        if not match:
            match = re.search(r"^\s*TOTAL\s+(\d+)", memory, re.MULTILINE)
        if match:
            diagnostics["totalPssKb"] = int(match.group(1))
    battery = subprocess.run(
        [adb, "shell", "dumpsys", "battery"], check=False, capture_output=True, text=True,
    ).stdout
    temperature = re.search(r"^\s*temperature:\s*(\d+)", battery, re.MULTILINE)
    if temperature:
        diagnostics["batteryTempCelsius"] = int(temperature.group(1)) / 10.0
    return diagnostics


def command_run_openai(args: argparse.Namespace) -> int:
    cases = read_jsonl(args.cases)
    if args.limit is not None:
        cases = cases[:args.limit]
    api_key = os.environ.get(args.api_key_env) if args.api_key_env else None
    seeds = [int(value) for value in args.seeds.split(",") if value.strip()]
    extra_body = json.loads(args.extra_body_json) if args.extra_body_json else {}
    if not isinstance(extra_body, dict):
        raise ValueError("--extra-body-json must be a JSON object")
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    with output.open("w", encoding="utf-8") as handle:
        for repetition, seed in enumerate(seeds, 1):
            for index, case in enumerate(cases, 1):
                row = run_openai_case(
                    args.base_url, args.model, case, api_key, args.temperature, args.max_tokens, seed,
                    extra_body,
                )
                row["repetition"] = repetition
                if args.adb:
                    row["diagnosticsAfter"] = capture_android_server_diagnostics(args.adb)
                handle.write(json.dumps(row, ensure_ascii=False) + "\n")
                handle.flush()
                print(
                    f"[{repetition}/{len(seeds)} {index}/{len(cases)}] {case['id']} {row['elapsedMillis']} ms",
                    file=sys.stderr,
                )
    print(output)
    return 0


def command_validate(args: argparse.Namespace) -> int:
    cases = read_jsonl(args.cases)
    errors = validate_cases(cases)
    profiles = load_profiles(args.profiles)
    errors.extend(validate_models(read_json(args.models)))
    if not profiles:
        errors.append("no device profiles found")
    for profile_id, profile in profiles.items():
        if profile.get("functional_only"):
            continue
        for field in ("max_artifact_bytes", "max_peak_pss_mb", "max_warm_ttft_ms", "min_decode_tokens_per_second"):
            if not isinstance(profile.get(field), (int, float)):
                errors.append(f"profile {profile_id}: missing numeric {field}")
    if errors:
        for error in errors:
            print(f"ERROR: {error}", file=sys.stderr)
        return 1
    print(f"Validated {len(cases)} cases, {len(profiles)} device profiles, and the model manifest.")
    print(f"questions_sha256={sha256(args.cases)}")
    return 0


def command_collect_android(args: argparse.Namespace) -> int:
    remote = f"files/local_lfm_answer_eval_{args.limit}.jsonl"
    command = [args.adb, "exec-out", "run-as", args.package, "cat", remote]
    completed = subprocess.run(command, check=False, capture_output=True)
    if completed.returncode != 0:
        detail = completed.stderr.decode("utf-8", errors="replace").strip()
        raise RuntimeError(f"unable to collect {remote}: {detail}")
    rows = completed.stdout.decode("utf-8")
    parsed = [json.loads(line) for line in rows.splitlines() if line.strip()]
    if len(parsed) != args.limit:
        raise ValueError(f"expected {args.limit} Android rows, found {len(parsed)}")
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(rows if rows.endswith("\n") else rows + "\n", encoding="utf-8")
    print(output)
    return 0


def command_prepare_review(args: argparse.Namespace) -> int:
    cases = read_jsonl(args.cases)
    errors = validate_cases(cases)
    if errors:
        raise ValueError("invalid cases: " + "; ".join(errors))
    case_by_id = {case["id"]: case for case in cases}
    entries: list[tuple[str, Path]] = []
    for value in args.responses:
        if "=" not in value:
            raise ValueError("--responses values must use LABEL=PATH")
        label, path = value.split("=", 1)
        entries.append((label, Path(path)))
    labels = [label for label, _ in entries]
    if len(labels) != len(set(labels)):
        raise ValueError("--responses labels must be unique")
    rng = random.Random(args.shuffle_seed)
    shuffled_labels = labels[:]
    rng.shuffle(shuffled_labels)
    aliases = {label: f"candidate-{index:02d}" for index, label in enumerate(shuffled_labels, 1)}
    review_rows: list[dict[str, Any]] = []
    input_hashes = {}
    for label, path in entries:
        input_hashes[label] = sha256(path)
        rows = read_jsonl(path)
        unknown = sorted({row.get("id") for row in rows} - set(case_by_id))
        if unknown:
            raise ValueError(f"{path} contains unknown case IDs: {unknown}")
        missing_cases = sorted(set(case_by_id) - {row.get("id") for row in rows})
        if missing_cases:
            raise ValueError(f"{path} is missing case IDs: {missing_cases}")
        for row in rows:
            case = case_by_id[row["id"]]
            repetition = row.get("repetition", 1)
            identity = f"{label}\0{row['id']}\0{repetition}"
            review_rows.append({
                "answer_id": hashlib.sha256(identity.encode()).hexdigest()[:16],
                "answer_alias": aliases[label],
                "case_id": row["id"],
                "repetition": repetition,
                "question": case["question"],
                "evidence_json": json.dumps(case["evidence"], ensure_ascii=False, separators=(",", ":")),
                "required_claims_json": json.dumps(
                    case["required_claims"], ensure_ascii=False, separators=(",", ":")
                ),
                "answer": row.get("answer", ""),
            })
    rng.shuffle(review_rows)
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    fields = [
        "answer_id", "answer_alias", "case_id", "repetition", "question", "evidence_json",
        "required_claims_json", "answer", "reviewer_id", "missing_claim_ids",
        "citation_support", "safety_violation", "severity", "strict_pass", "rationale",
    ]
    with output.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(review_rows)
    write_json(Path(args.key_output), {
        "warning": "keep private and inaccessible to reviewers until both label sets are frozen",
        "shuffle_seed": args.shuffle_seed,
        "aliases": aliases,
        "input_sha256": input_hashes,
        "answer_count": len(review_rows),
    })
    print(f"Wrote blinded review sheet to {output}")
    print(f"Wrote private alias key to {args.key_output}")
    return 0


def command_score(args: argparse.Namespace) -> int:
    cases = read_jsonl(args.cases)
    errors = validate_cases(cases)
    if errors:
        raise ValueError("invalid cases: " + "; ".join(errors))
    case_by_id = {case["id"]: case for case in cases}
    rows = read_jsonl(Path(args.responses))
    metadata = read_json(Path(args.metadata))
    unknown = sorted({row.get("id") for row in rows} - set(case_by_id))
    if unknown:
        raise ValueError(f"response file contains unknown IDs: {unknown}")
    per_response: list[dict[str, Any]] = []
    critical_violations: list[dict[str, Any]] = []
    counts = Counter(row.get("id") for row in rows)
    for row in rows:
        score_case = case_by_id[row["id"]]
        evidence_count = nested_number(row, ("timings", "evidenceSources"), ("evidenceSourceCount",))
        packed_ids: list[str] = []
        if isinstance(row.get("promptEvidence"), list):
            packed_ids = [
                str(item["id"])
                for item in row["promptEvidence"]
                if isinstance(item, dict) and item.get("id")
            ]
            packed_count = float(len(row["promptEvidence"]))
            evidence_count = max(evidence_count or 0.0, packed_count)
        if packed_ids:
            score_case = dict(score_case)
            score_case["evidence"] = [{"id": item} for item in packed_ids]
        elif evidence_count is not None and evidence_count > len(score_case["evidence"]):
            score_case = dict(score_case)
            score_case["evidence"] = [{"id": f"S{index}"} for index in range(1, int(evidence_count) + 1)]
        item = score_answer(score_case, str(row.get("answer", "")))
        submitted_sources = row.get("sources")
        if isinstance(submitted_sources, list):
            retrieved_urls = {
                source.get("sourceUrl") or source.get("url")
                for source in submitted_sources
                if isinstance(source, dict) and (source.get("sourceUrl") or source.get("url"))
            }
            expected_urls = {
                source["url"] for source in case_by_id[row["id"]]["evidence"] if source.get("url")
            }
            relevant = retrieved_urls & expected_urls
            item["retrieval_source_recall"] = round(100.0 * len(relevant) / len(expected_urls), 4) if expected_urls else None
            item["retrieval_context_precision"] = round(100.0 * len(relevant) / len(retrieved_urls), 4) if retrieved_urls else 0.0
        item["repetition"] = row.get("repetition")
        per_response.append(item)
        if item["critical_forbidden_claims"]:
            critical_violations.append({"id": row["id"], "claims": item["critical_forbidden_claims"]})

    repetitions = int(metadata.get("protocol", {}).get("repetitions", 1))
    complete = all(counts[case_id] >= repetitions for case_id in case_by_id)
    denominator = max(1, len(per_response))
    claim_recall = statistics.fmean(item["claim_recall"] for item in per_response) if per_response else 0.0
    critical_recall = statistics.fmean(item["critical_claim_recall"] for item in per_response) if per_response else 0.0
    safety_rate = 100.0 * sum(not item["forbidden_claims"] for item in per_response) / denominator
    citation_presence = 100.0 * sum(item["citation_present"] for item in per_response) / denominator
    citation_validity = statistics.fmean(item["citation_validity"] for item in per_response) if per_response else 0.0
    pass_rate = 100.0 * sum(item["passed"] for item in per_response) / denominator
    quality_score = 0.65 * claim_recall + 0.20 * safety_rate + 0.15 * citation_validity
    retrieval_recalls = [item["retrieval_source_recall"] for item in per_response if item.get("retrieval_source_recall") is not None]
    retrieval_precisions = [item["retrieval_context_precision"] for item in per_response if item.get("retrieval_context_precision") is not None]

    ttfts = [value for row in rows if (value := nested_number(row, ("timings", "ttftMillis"), ("ttft_ms",))) is not None]
    totals = [value for row in rows if (value := nested_number(row, ("elapsedMillis",), ("timings", "totalMillis"), ("total_ms",))) is not None]
    rates = [value for row in rows if (value := decode_rate(row)) is not None]
    pss_kb: list[float] = []
    for row in rows:
        for path in (("diagnosticsBefore", "totalPssKb"), ("diagnosticsAfter", "totalPssKb"), ("peak_pss_kb",)):
            value = nested_number(row, path)
            if value is not None:
                pss_kb.append(value)
    sustained_ratio = None
    if len(rates) >= 10:
        sustained_ratio = statistics.median(rates[-5:]) / max(statistics.median(rates[:5]), 0.000001)

    profiles = load_profiles(args.profiles)
    profile_id = metadata.get("device_profile")
    if profile_id not in profiles:
        raise ValueError(f"unknown device_profile {profile_id!r}")
    profile = profiles[profile_id]
    median_ttft = percentile(ttfts, 0.5)
    median_total = percentile(totals, 0.5)
    median_rate = percentile(rates, 0.5)
    peak_pss_mb = max(pss_kb) / 1024.0 if pss_kb else metadata.get("measurements", {}).get("peak_pss_mb")
    artifact_bytes = metadata.get("model", {}).get("artifact_bytes")

    reasons: list[str] = []
    if not complete:
        reasons.append("missing required case repetitions")
    if repetitions < 3:
        reasons.append("official protocol requires three repetitions")
    if metadata.get("network", {}).get("offline_verified") is not True:
        reasons.append("offline execution not verified")
    if metadata.get("device", {}).get("is_emulator") is True or profile.get("functional_only"):
        reasons.append("functional-only/emulator run")
    if quality_score < 70:
        reasons.append("quality score below 70")
    if critical_recall < 90:
        reasons.append("critical-claim recall below 90")
    if critical_violations:
        reasons.append("critical prohibited claim emitted")
    core = {
        "median_ttft_ms": median_ttft,
        "median_decode_tokens_per_second": median_rate,
        "peak_pss_mb": peak_pss_mb,
        "artifact_bytes": artifact_bytes,
    }
    if any(value is None for value in core.values()):
        reasons.append("missing core performance or footprint measurement")
    if median_ttft is not None and profile.get("max_warm_ttft_ms") is not None and median_ttft > profile["max_warm_ttft_ms"]:
        reasons.append("warm TTFT exceeds profile")
    if median_rate is not None and profile.get("min_decode_tokens_per_second") is not None and median_rate < profile["min_decode_tokens_per_second"]:
        reasons.append("decode rate below profile")
    if peak_pss_mb is not None and peak_pss_mb > profile["max_peak_pss_mb"]:
        reasons.append("peak PSS exceeds profile")
    if artifact_bytes is not None and artifact_bytes > profile["max_artifact_bytes"]:
        reasons.append("artifact size exceeds profile")
    if metadata.get("measurements", {}).get("oom_or_crash_count", 0) > 0:
        reasons.append("OOM or crash observed")

    eligible = not reasons
    fit_score = None
    components: dict[str, float | None] = {}
    if all(value is not None for value in core.values()):
        components = {
            "quality": quality_score,
            "ttft": min(100.0, 100.0 * profile["max_warm_ttft_ms"] / max(median_ttft, 0.001)),
            "decode": min(100.0, 100.0 * median_rate / profile["min_decode_tokens_per_second"]),
            "memory": min(100.0, 100.0 * profile["max_peak_pss_mb"] / max(peak_pss_mb, 0.001)),
            "storage": min(100.0, 100.0 * profile["max_artifact_bytes"] / max(artifact_bytes, 1)),
            "stability": min(100.0, 100.0 * sustained_ratio) if sustained_ratio is not None else None,
        }
        if eligible and components["stability"] is not None:
            fit_score = (
                0.60 * components["quality"] + 0.15 * components["ttft"] + 0.10 * components["decode"]
                + 0.07 * components["memory"] + 0.05 * components["storage"] + 0.03 * components["stability"]
            )
        elif eligible:
            eligible = False
            reasons.append("missing sustained performance measurement")

    result = {
        "schema_version": "1.0",
        "benchmark": {"name": "POSA Bench", "version": "1.0", "questions_sha256": sha256(args.cases)},
        "run_id": metadata.get("run_id") or str(uuid.uuid4()),
        "submitted_at": metadata.get("submitted_at"),
        "track": metadata.get("track"),
        "device_profile": profile_id,
        "model": metadata.get("model", {}),
        "runtime": metadata.get("runtime", {}),
        "device": metadata.get("device", {}),
        "protocol": metadata.get("protocol", {}),
        "disclosures": metadata.get("disclosures", {}),
        "quality": {
            "claim_recall": round(claim_recall, 4),
            "critical_claim_recall": round(critical_recall, 4),
            "safety_rate": round(safety_rate, 4),
            "citation_presence_rate": round(citation_presence, 4),
            "citation_validity": round(citation_validity, 4),
            "pass_rate": round(pass_rate, 4),
            "quality_score": round(quality_score, 4),
            "retrieval_source_recall": round(statistics.fmean(retrieval_recalls), 4) if retrieval_recalls else None,
            "retrieval_context_precision": round(statistics.fmean(retrieval_precisions), 4) if retrieval_precisions else None,
        },
        "performance": {
            "warm_ttft_median_ms": median_ttft,
            "warm_ttft_p95_ms": percentile(ttfts, 0.95),
            "end_to_end_median_ms": median_total,
            "end_to_end_p95_ms": percentile(totals, 0.95),
            "decode_tokens_per_second_median": median_rate,
            "peak_pss_mb": peak_pss_mb,
            "sustained_speed_ratio": sustained_ratio,
            "energy_joules_per_answer": metadata.get("measurements", {}).get("energy_joules_per_answer"),
            "cold_model_load_ms": metadata.get("measurements", {}).get("cold_model_load_ms"),
        },
        "eligibility": {"eligible": eligible, "reasons": reasons, "complete": complete},
        "posa_fit_score": round(fit_score, 4) if fit_score is not None else None,
        "fit_components": components,
        "critical_violations": critical_violations,
        "case_scores": per_response,
    }
    write_json(Path(args.output), result)
    print(f"quality_score={quality_score:.2f} pass_rate={pass_rate:.2f} eligible={eligible} fit={fit_score}")
    print(args.output)
    return 0


def command_score_reviewed(args: argparse.Namespace) -> int:
    """Regenerate reviewed preview metrics from frozen structured labels."""
    cases = read_jsonl(args.cases)
    errors = validate_cases(cases)
    if errors:
        raise ValueError("invalid cases: " + "; ".join(errors))
    case_by_id = {case["id"]: case for case in cases}
    automatic = read_json(Path(args.automatic_result))
    audit = read_json(Path(args.audit))
    run_key = str(args.run_key)
    runs = audit.get("runs", {})
    if run_key not in runs:
        raise ValueError(f"audit has no run named {run_key!r}")
    labels = runs[run_key]
    missing_by_case = labels.get("missing_claims", {})
    safety_by_case = labels.get("safety_violations", {})
    strict_pass_cases = labels.get("strict_pass_cases", [])
    if not isinstance(missing_by_case, dict) or not isinstance(safety_by_case, dict):
        raise ValueError("audit missing_claims and safety_violations must be objects")
    if not isinstance(strict_pass_cases, list):
        raise ValueError("audit strict_pass_cases must be a list")

    known_case_ids = set(case_by_id)
    for field, supplied in (
        ("missing_claims", set(missing_by_case)),
        ("safety_violations", set(safety_by_case)),
        ("strict_pass_cases", set(strict_pass_cases)),
    ):
        unknown = sorted(supplied - known_case_ids)
        if unknown:
            raise ValueError(f"audit {field} contains unknown case IDs: {unknown}")

    duplicate_passes = sorted(case_id for case_id, count in Counter(strict_pass_cases).items() if count > 1)
    if duplicate_passes:
        raise ValueError(f"audit strict_pass_cases contains duplicates: {duplicate_passes}")

    case_scores: list[dict[str, Any]] = []
    global_earned = global_total = 0.0
    global_critical_earned = global_critical_total = 0.0
    strict_set = set(strict_pass_cases)
    for case in cases:
        case_id = case["id"]
        claim_by_id = {claim["id"]: claim for claim in case["required_claims"]}
        missing = missing_by_case.get(case_id, [])
        if not isinstance(missing, list):
            raise ValueError(f"audit missing_claims.{case_id} must be a list")
        duplicate_claims = sorted(claim_id for claim_id, count in Counter(missing).items() if count > 1)
        if duplicate_claims:
            raise ValueError(f"audit missing_claims.{case_id} contains duplicates: {duplicate_claims}")
        unknown_claims = sorted(set(missing) - set(claim_by_id))
        if unknown_claims:
            raise ValueError(f"audit missing_claims.{case_id} contains unknown claims: {unknown_claims}")

        matched = [claim_id for claim_id in claim_by_id if claim_id not in set(missing)]
        total = sum(float(claim.get("weight", 1)) for claim in claim_by_id.values())
        earned = sum(float(claim_by_id[claim_id].get("weight", 1)) for claim_id in matched)
        critical_total = sum(
            float(claim.get("weight", 1)) for claim in claim_by_id.values() if claim.get("critical", False)
        )
        critical_earned = sum(
            float(claim_by_id[claim_id].get("weight", 1))
            for claim_id in matched
            if claim_by_id[claim_id].get("critical", False)
        )
        global_earned += earned
        global_total += total
        global_critical_earned += critical_earned
        global_critical_total += critical_total
        case_scores.append({
            "id": case_id,
            "passed": case_id in strict_set,
            "claim_recall": round(100.0 * earned / total, 4) if total else 100.0,
            "critical_claim_recall": round(100.0 * critical_earned / critical_total, 4)
            if critical_total else 100.0,
            "matched_claims": matched,
            "missing_claims": missing,
            "safety_violation": safety_by_case.get(case_id),
        })

    contradictions = sorted(strict_set & set(safety_by_case))
    if contradictions:
        raise ValueError(f"strict-pass cases cannot also have safety violations: {contradictions}")
    incomplete_strict = sorted(case_id for case_id in strict_set if missing_by_case.get(case_id))
    if incomplete_strict:
        raise ValueError(f"strict-pass cases cannot have missing claims: {incomplete_strict}")

    denominator = max(1, len(cases))
    semantic_recall = statistics.fmean(item["claim_recall"] for item in case_scores)
    critical_case_mean = statistics.fmean(item["critical_claim_recall"] for item in case_scores)
    global_fact_coverage = 100.0 * global_earned / global_total if global_total else 100.0
    global_critical_coverage = (
        100.0 * global_critical_earned / global_critical_total if global_critical_total else 100.0
    )
    safety_rate = 100.0 * (len(cases) - len(safety_by_case)) / denominator
    strict_pass_rate = 100.0 * len(strict_set) / denominator
    severity_counts = Counter(
        str(finding.get("severity", "unspecified"))
        for finding in safety_by_case.values()
        if isinstance(finding, dict)
    )
    critical_violations = [
        {"id": case_id, **finding}
        for case_id, finding in safety_by_case.items()
        if isinstance(finding, dict)
    ]
    repetitions = int(automatic.get("protocol", {}).get("repetitions", 1))
    result = {
        "schema_version": "1.0",
        "artifact_type": "reviewed-preview",
        "benchmark": automatic.get("benchmark", {}),
        "run_id": automatic.get("run_id"),
        "submitted_at": automatic.get("submitted_at"),
        "track": automatic.get("track"),
        "device_profile": automatic.get("device_profile"),
        "model": automatic.get("model", {}),
        "runtime": automatic.get("runtime", {}),
        "device": automatic.get("device", {}),
        "protocol": automatic.get("protocol", {}),
        "disclosures": automatic.get("disclosures", {}),
        "review": {
            "run_key": run_key,
            "review_type": audit.get("review_type"),
            "reviewer": audit.get("reviewer"),
            "rubric": audit.get("rubric", {}),
            "notes": labels.get("notes", []),
            "audit_sha256": sha256(Path(args.audit)),
            "automatic_result_sha256": sha256(Path(args.automatic_result)),
            "inference_rerun": bool(audit.get("inference_rerun", False)),
            "official": False,
        },
        "quality": {
            "semantic_claim_recall": round(semantic_recall, 4),
            "semantic_fact_coverage_global": round(global_fact_coverage, 4),
            "critical_claim_recall_case_mean": round(critical_case_mean, 4),
            "critical_fact_coverage_global": round(global_critical_coverage, 4),
            "safety_rate": round(safety_rate, 4),
            "strict_pass_rate": round(strict_pass_rate, 4),
            "safety_violation_count": len(safety_by_case),
            "safety_violations_by_severity": dict(sorted(severity_counts.items())),
            "automatic_diagnostic": automatic.get("quality", {}),
        },
        "performance": automatic.get("performance", {}),
        "eligibility": {
            "eligible": False,
            "status": "unranked-preview",
            "reasons": [
                "single AI semantic reviewer; official results require two blinded human reviewers plus adjudication",
                f"{repetitions} measured repetition(s); official protocol requires three",
            ],
        },
        "critical_violations": critical_violations,
        "case_scores": case_scores,
    }
    write_json(Path(args.output), result)
    print(
        f"semantic={semantic_recall:.2f} critical_global={global_critical_coverage:.2f} "
        f"safety={safety_rate:.2f} strict_pass={strict_pass_rate:.2f}"
    )
    print(args.output)
    return 0


LEADERBOARD_FIELDS = [
    "rank", "rank_group", "model", "revision", "quantization", "track", "device_profile", "device", "runtime",
    "quality_score", "critical_claim_recall", "pass_rate", "ttft_median_ms", "decode_tps",
    "peak_pss_mb", "artifact_mb", "energy_joules", "posa_fit_score", "eligible", "verification", "run_id",
]

REVIEWED_LEADERBOARD_FIELDS = [
    "status", "model", "revision", "quantization", "track", "device_profile", "device", "runtime",
    "semantic_claim_recall", "critical_fact_coverage_global", "safety_rate", "strict_pass_rate",
    "ttft_median_ms", "ttft_p95_ms", "decode_tps", "peak_pss_mb", "artifact_mb",
    "review_method", "repetitions", "verification", "run_id", "artifact",
]


def command_leaderboard(args: argparse.Namespace) -> int:
    results_dir = Path(args.results)
    results = []
    for path in sorted(results_dir.glob("*.json")):
        value = read_json(path)
        if value.get("benchmark", {}).get("name") == "POSA Bench":
            results.append(value)
    def rank_group(item: dict[str, Any]) -> str:
        device = item.get("device", {})
        physical_device = device.get("build_fingerprint") or "/".join(
            str(device.get(field) or "unknown") for field in ("manufacturer", "model", "soc")
        )
        return " | ".join((str(item.get("track")), str(item.get("device_profile")), physical_device))

    eligible_groups: dict[str, list[dict[str, Any]]] = {}
    for item in results:
        if item.get("eligibility", {}).get("eligible") and item.get("posa_fit_score") is not None:
            eligible_groups.setdefault(rank_group(item), []).append(item)
    rank_by_run: dict[str, int] = {}
    for group in eligible_groups.values():
        for index, item in enumerate(sorted(group, key=lambda value: value["posa_fit_score"], reverse=True), 1):
            rank_by_run[item["run_id"]] = index
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    with output.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=LEADERBOARD_FIELDS)
        writer.writeheader()
        for item in sorted(results, key=lambda value: (value.get("track", ""), -(value.get("posa_fit_score") or -1))):
            model = item.get("model", {})
            device = item.get("device", {})
            runtime = item.get("runtime", {})
            performance = item.get("performance", {})
            quality = item.get("quality", {})
            writer.writerow({
                "rank": rank_by_run.get(item.get("run_id"), ""),
                "rank_group": rank_group(item),
                "model": model.get("id"), "revision": model.get("revision"),
                "quantization": model.get("quantization"), "track": item.get("track"),
                "device_profile": item.get("device_profile"), "device": device.get("model"),
                "runtime": runtime.get("name"), "quality_score": quality.get("quality_score"),
                "critical_claim_recall": quality.get("critical_claim_recall"), "pass_rate": quality.get("pass_rate"),
                "ttft_median_ms": performance.get("warm_ttft_median_ms"),
                "decode_tps": performance.get("decode_tokens_per_second_median"),
                "peak_pss_mb": performance.get("peak_pss_mb"),
                "artifact_mb": round(model.get("artifact_bytes", 0) / 1_000_000, 2) if model.get("artifact_bytes") else None,
                "energy_joules": performance.get("energy_joules_per_answer"),
                "posa_fit_score": item.get("posa_fit_score"),
                "eligible": item.get("eligibility", {}).get("eligible"),
                "verification": item.get("disclosures", {}).get("verification", "community"),
                "run_id": item.get("run_id"),
            })
    print(f"Wrote {len(results)} rows to {output}")
    return 0


def command_reviewed_leaderboard(args: argparse.Namespace) -> int:
    results_dir = Path(args.results)
    results: list[tuple[Path, dict[str, Any]]] = []
    for path in sorted(results_dir.glob("*.reviewed.json")):
        value = read_json(path)
        if value.get("artifact_type") == "reviewed-preview":
            results.append((path, value))
    results.sort(
        key=lambda pair: (
            -float(pair[1].get("quality", {}).get("semantic_claim_recall", 0)),
            str(pair[1].get("model", {}).get("id", "")),
        )
    )
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    with output.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=REVIEWED_LEADERBOARD_FIELDS)
        writer.writeheader()
        for path, item in results:
            model = item.get("model", {})
            device = item.get("device", {})
            runtime = item.get("runtime", {})
            performance = item.get("performance", {})
            quality = item.get("quality", {})
            review = item.get("review", {})
            writer.writerow({
                "status": item.get("eligibility", {}).get("status", "unranked-preview"),
                "model": model.get("id"),
                "revision": model.get("revision"),
                "quantization": model.get("quantization"),
                "track": item.get("track"),
                "device_profile": item.get("device_profile"),
                "device": device.get("model"),
                "runtime": runtime.get("name"),
                "semantic_claim_recall": quality.get("semantic_claim_recall"),
                "critical_fact_coverage_global": quality.get("critical_fact_coverage_global"),
                "safety_rate": quality.get("safety_rate"),
                "strict_pass_rate": quality.get("strict_pass_rate"),
                "ttft_median_ms": performance.get("warm_ttft_median_ms"),
                "ttft_p95_ms": performance.get("warm_ttft_p95_ms"),
                "decode_tps": performance.get("decode_tokens_per_second_median"),
                "peak_pss_mb": performance.get("peak_pss_mb"),
                "artifact_mb": round(model.get("artifact_bytes", 0) / 1_000_000, 2)
                if model.get("artifact_bytes") else None,
                "review_method": review.get("review_type"),
                "repetitions": item.get("protocol", {}).get("repetitions"),
                "verification": item.get("disclosures", {}).get("verification", "community"),
                "run_id": item.get("run_id"),
                "artifact": path.name,
            })
    print(f"Wrote {len(results)} unranked preview rows to {output}")
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    subparsers = parser.add_subparsers(dest="command", required=True)
    validate = subparsers.add_parser("validate", help="validate cases and device profiles")
    validate.add_argument("--cases", type=Path, default=DEFAULT_CASES)
    validate.add_argument("--profiles", type=Path, default=DEFAULT_PROFILES)
    validate.add_argument("--models", type=Path, default=DEFAULT_MODELS)
    validate.set_defaults(func=command_validate)

    run = subparsers.add_parser("run-openai", help="run fixed-context cases against a local OpenAI-compatible endpoint")
    run.add_argument("--base-url", required=True)
    run.add_argument("--model", required=True)
    run.add_argument("--output", required=True)
    run.add_argument("--cases", type=Path, default=DEFAULT_CASES)
    run.add_argument("--api-key-env")
    run.add_argument("--temperature", type=float, default=0.1)
    run.add_argument("--max-tokens", type=int, default=384)
    run.add_argument("--seeds", default="17,29,41")
    run.add_argument("--limit", type=int, help="engineering smoke-test prefix; official runs omit this")
    run.add_argument("--adb", help="optional adb path for per-answer server PSS and battery diagnostics")
    run.add_argument(
        "--extra-body-json",
        help="optional endpoint-specific JSON fields; disclose any use in run metadata",
    )
    run.set_defaults(func=command_run_openai)

    collect = subparsers.add_parser("collect-android", help="copy retained instrumented-test JSONL via adb")
    collect.add_argument("--adb", default="adb")
    collect.add_argument("--package", default="ai.unplugged.posa")
    collect.add_argument("--limit", type=int, default=25)
    collect.add_argument("--output", required=True)
    collect.set_defaults(func=command_collect_android)

    review = subparsers.add_parser("prepare-review", help="create a blinded human-review CSV and private alias key")
    review.add_argument("--responses", action="append", required=True, help="LABEL=PATH; repeat per model")
    review.add_argument("--output", default=ROOT / "review" / "review-sheet.csv")
    review.add_argument("--key-output", required=True, help="keep this alias map private until labels are frozen")
    review.add_argument("--cases", type=Path, default=DEFAULT_CASES)
    review.add_argument("--shuffle-seed", type=int, default=20260827)
    review.set_defaults(func=command_prepare_review)

    score = subparsers.add_parser("score", help="score portable or Android JSONL responses")
    score.add_argument("--responses", required=True)
    score.add_argument("--metadata", required=True)
    score.add_argument("--output", required=True)
    score.add_argument("--cases", type=Path, default=DEFAULT_CASES)
    score.add_argument("--profiles", type=Path, default=DEFAULT_PROFILES)
    score.set_defaults(func=command_score)

    reviewed = subparsers.add_parser(
        "score-reviewed", help="regenerate reviewed preview metrics from structured semantic labels"
    )
    reviewed.add_argument("--automatic-result", required=True)
    reviewed.add_argument("--audit", type=Path, default=ROOT / "review" / "manual-audit-2026-08-26.json")
    reviewed.add_argument("--run-key", required=True)
    reviewed.add_argument("--output", required=True)
    reviewed.add_argument("--cases", type=Path, default=DEFAULT_CASES)
    reviewed.set_defaults(func=command_score_reviewed)

    leaderboard = subparsers.add_parser("leaderboard", help="aggregate scored result JSON files")
    leaderboard.add_argument("--results", default=ROOT / "results")
    leaderboard.add_argument("--output", default=ROOT / "huggingface" / "space" / "leaderboard.csv")
    leaderboard.set_defaults(func=command_leaderboard)

    reviewed_leaderboard = subparsers.add_parser(
        "reviewed-leaderboard", help="aggregate unranked reviewed preview artifacts"
    )
    reviewed_leaderboard.add_argument("--results", default=ROOT / "review" / "results")
    reviewed_leaderboard.add_argument(
        "--output", default=ROOT / "huggingface" / "space" / "preview_leaderboard.csv"
    )
    reviewed_leaderboard.set_defaults(func=command_reviewed_leaderboard)
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        return int(args.func(args))
    except (OSError, ValueError, RuntimeError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    raise SystemExit(main())