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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
"""``explicit-train`` — CPU contracts, frozen plans, and gated GPU launch."""

from __future__ import annotations

import argparse
import importlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any, cast

from ..atomic_io import atomic_write_json, atomic_write_jsonl, read_jsonl
from ..hashing import canonical_config_hash, sha256_file
from ..paths import repo_root
from ..training.artifacts import (
    QWEN35_2B_REVISION,
    RunArtifactError,
    RunMode,
    RuntimeTrainingConfig,
    TrainerKind,
    build_run_manifest,
    write_frozen_run,
)
from ..training.backend import (
    BackendContractError,
    prepare_sft_records,
    sft_loss_token_count,
)
from ..training.data import (
    AdmissionError,
    AdmissionValidator,
    AdmittedGroup,
    certified_release_validator,
    load_groups,
)
from ..training.environment import write_environment_snapshot
from ..training.launcher import (
    LauncherUnavailable,
    build_launch_command,
    check_launcher_environment,
    execute,
)
from ..training.ledger import LedgerError
from ..training.offline import offline_contract_smoke
from ..training.rewards import (
    ABLATION_ARM_KNOBS,
    ABLATION_ARMS,
    CORE_ABLATION_ARMS,
    GPU_SMOKE_ARMS,
    arm_trainer_kind,
)
from ..training.sft_schedule import SFTScheduleError, match_sft_schedules
from ..training.slots import build_comparison_slots, comparison_slot_manifest_sha256
from ..training.smoke_gate import (
    SmokeGateError,
    certify_smoke_gate,
)
from ..training.targets import ours_target

_RL_TOKEN_CAP = 24_000_000
_TOTAL_RL_TOKEN_CAP = 216_000_000
_TOTAL_ABLATION_TOKEN_CAP = 48_000_000
_SFT_TOKEN_CAP = 6_000_000
_EXPECTED_RL_RUNS = {
    ("answer_grpo", 1),
    ("papo_controlled", 1),
    ("papo_controlled", 2),
    ("defacto_controlled", 1),
    ("defacto_controlled", 2),
    ("intervention_grpo", 1),
    ("intervention_grpo", 2),
    ("evi_po", 1),
    ("evi_po", 2),
}
_EXPECTED_SMOKE_RUNS = {(arm, 1) for arm in GPU_SMOKE_ARMS}
# Core ablations are limited to the two direct EVI objective removals.  Six
# exploratory target/mask/margin sweeps remain available as explicit one-off
# plans but are not part of the automatic full-budget queue.
_EXPECTED_ABLATION_RUNS = {(arm, 1) for arm in CORE_ABLATION_ARMS}
_EXPECTED_SFT_DATA = {"full_only", "full_plus_certified_intervention"}


def _resolve_validator(
    spec: str,
    *,
    asset_root: Path,
    replayed_view_dirs: frozenset[Path] | None = None,
    replay_certificates: bool = True,
) -> AdmissionValidator:
    if spec == "builtin-certified-release":
        return certified_release_validator(
            asset_root,
            replayed_view_dirs=replayed_view_dirs,
            replay_certificates=replay_certificates,
        )
    if ":" not in spec:
        raise AdmissionError("--validator must be module:function")
    module_name, function_name = spec.split(":", 1)
    try:
        function = getattr(importlib.import_module(module_name), function_name)
    except (ImportError, AttributeError) as exc:
        raise AdmissionError(f"cannot load validator {spec!r}: {exc}") from exc
    if not callable(function):
        raise AdmissionError(f"validator {spec!r} is not callable")
    return cast(AdmissionValidator, function)


def _load_yaml(path: Path) -> dict[str, Any]:
    try:
        import yaml
    except ImportError as exc:
        raise RunArtifactError("PyYAML is required to load a run matrix") from exc
    try:
        value = yaml.safe_load(path.read_text(encoding="utf-8"))
    except (OSError, yaml.YAMLError) as exc:
        raise RunArtifactError(f"cannot read matrix config {path}: {exc}") from exc
    if not isinstance(value, dict):
        raise RunArtifactError(f"{path} must contain a mapping")
    return value


def _validate_runtime_args_against_config(
    args: argparse.Namespace,
    config: Mapping[str, Any],
    *,
    sft: bool,
    run_mode: RunMode = "main",
) -> None:
    """Reject CLI values that drift from the authoritative experiment config."""

    try:
        io = config["input_output"]
        student = config["common_student"]
        server = student["server_runtime"]
        budget = config["training_budget"]
        expected = {
            "world_size": int(server["world_size"]),
            "per_device_batch_size": int(server["per_device_train_batch_size"]),
            "gradient_accumulation_steps": int(server["gradient_accumulation_steps"]),
            "checkpoint_interval": int(server["checkpoint_interval_steps"]),
            "max_prompt_tokens": int(io["max_prompt_tokens"]),
            "max_completion_tokens": int(io["max_completion_tokens"]),
            "learning_rate": float(student["optimizer"]["learning_rate"]),
            "token_cap": int(
                budget[
                    "max_assistant_tokens_per_sft_run"
                    if sft
                    else "max_sampled_completion_tokens_per_rl_run"
                ]
            ),
        }
        if not sft:
            expected["generations"] = int(student["generations_per_prompt"])
            expected["max_optimizer_steps"] = int(
                budget["smoke_steps_per_arm"]
                if run_mode == "smoke"
                else server["max_optimizer_steps"]
            )
            evi_po = config["rewards"]["evi_po"]
            expected["evi_direction_loss_weight"] = float(evi_po["lambda_direction"])
            expected["evi_evidence_loss_weight"] = float(evi_po["lambda_evidence"])
            expected["evi_direction_margin"] = float(evi_po["margin"])
    except (KeyError, TypeError, ValueError) as exc:
        raise RunArtifactError(f"experiment config lacks runtime authority: {exc}") from exc
    drift = {
        name: (getattr(args, name), value)
        for name, value in expected.items()
        if getattr(args, name) != value
    }
    if drift:
        formatted = ", ".join(
            f"{name}={actual!r} (config {wanted!r})"
            for name, (actual, wanted) in sorted(drift.items())
        )
        raise RunArtifactError(
            "runtime arguments drift from authoritative experiment config: " + formatted
        )
    target_modules = tuple(args.target_module or ["all-linear"])
    if target_modules != ("all-linear",):
        raise RunArtifactError(
            "controlled plans require the config-frozen LoRA target_modules=all-linear"
        )
    if args.backend_entrypoint != "explicit_learning.training.backend:run":
        raise RunArtifactError(
            "controlled plans require backend explicit_learning.training.backend:run"
        )


def cmd_dry_run(args: argparse.Namespace) -> int:
    try:
        summary = offline_contract_smoke(
            steps_per_arm=args.steps_per_arm,
            seed=args.seed,
            token_cap=args.token_cap,
        )
    except (ValueError, AdmissionError, LedgerError) as exc:
        print(f"OFFLINE DRY RUN FAILED: {exc}", file=sys.stderr)
        return 1
    print(json.dumps(summary, sort_keys=True))
    return 0


def cmd_snapshot_environment(args: argparse.Namespace) -> int:
    try:
        snapshot = write_environment_snapshot(args.output)
    except (FileExistsError, OSError, RuntimeError) as exc:
        print(f"ENVIRONMENT SNAPSHOT FAILED: {exc}", file=sys.stderr)
        return 1
    print(
        json.dumps(
            {
                "ok": True,
                "output": str(args.output),
                "distribution_count": len(snapshot["distributions"]),
                "cuda_available": bool(
                    snapshot.get("torch") and snapshot["torch"]["cuda_available"]
                ),
            },
            sort_keys=True,
        )
    )
    return 0


def _admitted(
    args: argparse.Namespace,
    *,
    replayed_view_dirs: frozenset[Path] | None = None,
    replay_certificates: bool = True,
    verify_assets: bool = True,
) -> tuple[AdmittedGroup, ...]:
    validator = _resolve_validator(
        args.validator,
        asset_root=args.asset_root,
        replayed_view_dirs=replayed_view_dirs,
        replay_certificates=replay_certificates,
    )
    return load_groups(
        args.dataset,
        dataset_root=args.asset_root,
        validator=validator,
        verify_assets=verify_assets,
    )


def _common_sft_rows(
    groups: tuple[AdmittedGroup, ...],
    *,
    mode: str,
) -> list[dict[str, Any]]:
    if mode not in {"full_only", "full_plus_certified_intervention"}:
        raise ValueError(f"unsupported SFT data mode: {mode!r}")
    rows: list[dict[str, Any]] = []
    for group in sorted(groups, key=lambda item: item.base_id):
        views = [
            view
            for view in group.row["views"]
            if mode == "full_plus_certified_intervention" or view["state"] == "FULL"
        ]
        for view in views:
            target = ours_target(view, group.row["full_answer_canonical"])
            rows.append(
                {
                    "schema_version": 2,
                    "record_kind": mode,
                    "group_id": group.group_id,
                    "base_id": group.base_id,
                    "split": group.row["split"],
                    "view_id": view["view_id"],
                    "state": view["state"],
                    "question": group.row["question"],
                    "choices": group.row["choices"],
                    "images": view["images"],
                    "target": target,
                    "assistant_response": f"<answer>{target}</answer>",
                    "answer_type": group.row["answer_type"],
                    "certificate_id": view["certificate_id"],
                    "trained": False,
                }
            )
    return rows


def cmd_build_common_sft_data(args: argparse.Namespace) -> int:
    """Build certificate-target SFT records with no teacher or pending trajectory."""

    try:
        groups = _admitted(args)
        rows = _common_sft_rows(groups, mode=args.mode)
        atomic_write_jsonl(args.output, rows)
    except (AdmissionError, OSError, StopIteration) as exc:
        print(f"SFT DATA BUILD FAILED: {exc}", file=sys.stderr)
        return 1
    print(
        json.dumps(
            {
                "ok": True,
                "trained": False,
                "mode": args.mode,
                "record_count": len(rows),
                "output": str(args.output),
            },
            sort_keys=True,
        )
    )
    return 0


def _json_object(path: Path, label: str) -> dict[str, Any]:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise ValueError(f"{label} is unreadable: {exc}") from exc
    if not isinstance(value, dict):
        raise ValueError(f"{label} must contain a JSON object")
    return value


def cmd_build_training_inputs(args: argparse.Namespace) -> int:
    """Admit once and atomically publish slots plus both raw SFT datasets."""

    output_dir = args.output_dir
    staging: Path | None = None
    try:
        if output_dir.exists():
            raise FileExistsError(f"output directory already exists: {output_dir}")
        if len(args.code_commit) != 40 or any(
            char not in "0123456789abcdef" for char in args.code_commit
        ):
            raise ValueError("--code-commit must be a full lowercase 40-hex revision")
        if args.workers < 1:
            raise ValueError("--workers must be at least 1")
        release = _json_object(args.release_manifest, "release manifest")
        if (
            release.get("reasoning_vlm_calls") != 0
            or release.get("per_example_human_decisions") != 0
        ):
            raise ValueError("release manifest violates zero-VLM/zero-human data policy")

        from ..datasets.evi_core_release import EVI_CORE_RELEASE_CONTRACT

        core_release = release.get("contract") == EVI_CORE_RELEASE_CONTRACT
        replay: dict[str, Any] | None = None
        if not core_release:
            if args.replay_report is None:
                raise ValueError("--replay-report is required for legacy release bundles")
            replay = _json_object(args.replay_report, "train replay report")
            if (
                not isinstance(replay.get("view_count"), int)
                or replay.get("passed") != replay["view_count"]
                or replay.get("failed") != 0
            ):
                raise ValueError("train replay report is not an exact all-pass result")
        replayed_view_dirs: frozenset[Path] | None = None
        admission_replay_count = 0
        if args.validator == "builtin-certified-release" and not core_release:
            from ..certificates.replay import replay_dataset

            admission_results = replay_dataset(args.asset_root, workers=args.workers)
            failures = [result for result in admission_results if not result.ok]
            if failures:
                raise AdmissionError(
                    "parallel admission replay failed: " + "; ".join(failures[0].errors[:3])
                )
            assert replay is not None
            if len(admission_results) != replay["view_count"]:
                raise ValueError("parallel admission replay count differs from replay report")
            replayed_view_dirs = frozenset(
                Path(result.view_dir).resolve() for result in admission_results
            )
            admission_replay_count = len(admission_results)

        groups = _admitted(
            args,
            replayed_view_dirs=replayed_view_dirs,
            replay_certificates=not core_release,
            verify_assets=not core_release,
        )
        expected_views = sum(len(group.row["views"]) for group in groups)
        if core_release:
            group_counts = release.get("group_counts")
            if not isinstance(group_counts, Mapping) or group_counts.get("train") != len(groups):
                raise ValueError("EVI core release/train group count differs from admitted groups")
            split_view_counts = release.get("split_view_counts")
            if (
                not isinstance(split_view_counts, Mapping)
                or split_view_counts.get("train") != expected_views
            ):
                raise ValueError("EVI core release/train view count differs from admitted views")
        else:
            assert replay is not None
            split_manifests = release.get("split_manifests")
            train_manifest = (
                split_manifests.get("train") if isinstance(split_manifests, Mapping) else None
            )
            if not isinstance(train_manifest, Mapping):
                raise ValueError("release manifest has no train split manifest")
            if train_manifest.get("group_count") != len(groups):
                raise ValueError("release/train group count differs from admitted groups")
            if train_manifest.get("view_count") != expected_views:
                raise ValueError("release/train view count differs from admitted views")
            if (
                replay.get("view_count") != expected_views
                or replay.get("passed") != expected_views
                or replay.get("failed") != 0
            ):
                raise ValueError("train replay report is not an exact all-pass result")

        slots = build_comparison_slots(groups, seed=args.seed, max_slots=args.max_slots)
        if len(slots) != expected_views:
            raise ValueError(
                f"comparison slots must cover all admitted views: {len(slots)} != {expected_views}"
            )
        full_rows = _common_sft_rows(groups, mode="full_only")
        pair_rows = _common_sft_rows(
            groups,
            mode="full_plus_certified_intervention",
        )
        if len(full_rows) != len(groups) or len(pair_rows) != expected_views:
            raise ValueError("raw SFT datasets do not exactly cover admitted groups/views")

        output_dir.parent.mkdir(parents=True, exist_ok=True)
        staging = Path(
            tempfile.mkdtemp(prefix=f".{output_dir.name}.staging.", dir=output_dir.parent)
        )
        slots_path = staging / "comparison-slots.jsonl"
        full_path = staging / "full-only.raw.jsonl"
        pair_path = staging / "full-plus-intervention.raw.jsonl"
        atomic_write_jsonl(slots_path, (slot.to_row() for slot in slots))
        atomic_write_jsonl(full_path, full_rows)
        atomic_write_jsonl(pair_path, pair_rows)
        state_counts: dict[str, int] = {}
        for row in pair_rows:
            state = str(row["state"])
            state_counts[state] = state_counts.get(state, 0) + 1
        manifest = {
            "schema_version": 1,
            "kind": "certified_model_independent_training_inputs",
            "trained": False,
            "builder_code_commit": args.code_commit,
            "group_count": len(groups),
            "view_count": expected_views,
            "comparison_slot_count": len(slots),
            "comparison_slot_manifest_sha256": comparison_slot_manifest_sha256(slots),
            "full_only_raw_rows": len(full_rows),
            "full_plus_intervention_raw_rows": len(pair_rows),
            "full_plus_intervention_state_counts": dict(sorted(state_counts.items())),
            "admission_replay_count": admission_replay_count,
            "admission_replay_workers": args.workers,
            "admission_mode": (
                "structural_no_content_hash_replay"
                if core_release
                else "legacy_full_certificate_replay"
            ),
            "reasoning_vlm_calls": 0,
            "per_example_human_decisions": 0,
            "row_duplication_allowed": False,
        }
        if not core_release:
            assert args.replay_report is not None
            manifest.update(
                {
                    "comparison_slots_sha256": sha256_file(slots_path),
                    "full_only_raw_sha256": sha256_file(full_path),
                    "full_plus_intervention_raw_sha256": sha256_file(pair_path),
                    "source_groups_sha256": sha256_file(args.dataset),
                    "release_manifest_sha256": sha256_file(args.release_manifest),
                    "train_replay_report_sha256": sha256_file(args.replay_report),
                }
            )
        atomic_write_json(staging / "manifest.json", manifest)
        os.replace(staging, output_dir)
        staging = None
    except (
        AdmissionError,
        FileExistsError,
        OSError,
        StopIteration,
        ValueError,
    ) as exc:
        if staging is not None:
            shutil.rmtree(staging, ignore_errors=True)
        print(f"TRAINING INPUT BUILD FAILED: {exc}", file=sys.stderr)
        return 1
    print(json.dumps({"ok": True, "output_dir": str(output_dir), **manifest}, sort_keys=True))
    return 0


def cmd_build_comparison_slots(args: argparse.Namespace) -> int:
    try:
        groups = _admitted(args)
        slots = build_comparison_slots(groups, seed=args.seed, max_slots=args.max_slots)
        atomic_write_jsonl(args.output, (slot.to_row() for slot in slots))
    except (AdmissionError, OSError, ValueError) as exc:
        print(f"COMPARISON SLOT BUILD FAILED: {exc}", file=sys.stderr)
        return 1
    print(
        json.dumps(
            {
                "ok": True,
                "slot_count": len(slots),
                "slot_manifest_sha256": comparison_slot_manifest_sha256(slots),
                "output": str(args.output),
            },
            sort_keys=True,
        )
    )
    return 0


def cmd_match_sft_schedules(args: argparse.Namespace) -> int:
    """Loss-token and row-count match the two one-epoch SFT ablations."""

    try:
        if not args.model_path.is_dir() or not (args.model_path / "config.json").is_file():
            raise SFTScheduleError("processor/model snapshot is missing config.json")
        from transformers import AutoProcessor

        processor = AutoProcessor.from_pretrained(
            str(args.model_path),
            revision=args.model_revision,
        )
        full_rows = list(read_jsonl(args.full_input))
        pair_rows = list(read_jsonl(args.pair_input))
        prepared_by_kind = {
            kind: prepare_sft_records(
                {
                    "dataset_path": str(path),
                    "dataset_asset_root": str(args.asset_root),
                    "arm": kind,
                }
            )
            for kind, path in (
                ("full_only", args.full_input),
                ("full_plus_certified_intervention", args.pair_input),
            )
        }
        loss_counts: dict[tuple[str, str, str], int] = {}
        for kind, prepared in prepared_by_kind.items():
            for row in prepared.rows:
                identity = (kind, str(row["group_id"]), str(row["view_id"]))
                loss_counts[identity] = sft_loss_token_count(processor, row)

        def loss_token_counter(row: Mapping[str, Any]) -> int:
            identity = (
                str(row.get("record_kind", "")),
                str(row.get("group_id", "")),
                str(row.get("view_id", "")),
            )
            try:
                return loss_counts[identity]
            except KeyError as exc:
                raise SFTScheduleError(f"prepared loss-token count missing for {identity}") from exc

        matched = match_sft_schedules(
            full_rows,
            pair_rows,
            loss_token_counter=loss_token_counter,
            intervention_per_state=args.intervention_per_state,
        )
        atomic_write_jsonl(args.full_output, matched.full_only)
        atomic_write_jsonl(args.pair_output, matched.full_plus_intervention)
        manifest = {
            "schema_version": 2,
            "kind": "loss_token_and_record_matched_sft_schedules",
            "model_revision": args.model_revision,
            "model_snapshot_sha256": args.model_snapshot_sha256,
            "full_source": str(args.full_input.resolve()),
            "pair_source": str(args.pair_input.resolve()),
            "full_output": str(args.full_output.resolve()),
            "pair_output": str(args.pair_output.resolve()),
            "loss_tokens_each": matched.loss_tokens,
            "records_each": matched.record_count,
            "full_record_count": len(matched.full_only),
            "pair_record_count": len(matched.full_plus_intervention),
            "pair_state_counts": matched.state_counts,
            "row_duplication_allowed": False,
            "counting_contract": (
                "trl_1.9.1_vlm_prompt_completion_attention_mask_non_padding_tokens"
            ),
        }
        atomic_write_json(args.manifest_output, manifest)
    except (
        BackendContractError,
        ImportError,
        OSError,
        SFTScheduleError,
        AttributeError,
        TypeError,
        ValueError,
    ) as exc:
        print(f"SFT SCHEDULE MATCH FAILED: {exc}", file=sys.stderr)
        return 1
    print(json.dumps({"ok": True, **manifest}, sort_keys=True))
    return 0


def _runtime_from_args(
    args: argparse.Namespace,
    *,
    run_id: str,
    trainer_kind: TrainerKind,
    arm: str,
    seed: int,
    output_dir: Path,
    run_mode: RunMode,
    dataset_path: Path | None = None,
) -> RuntimeTrainingConfig:
    # Ablation arms carry code-defined numeric knobs (ABLATION_ARM_KNOBS) that
    # override the free CLI --evi-* / papo defaults, so the frozen config is
    # pinned to the version-controlled source of truth rather than a YAML value.
    # Main-ladder arms are absent from that map and fall back to the CLI args
    # (which _validate_runtime_args_against_config has already bound to the
    # experiment config). C/D are pure target-function variants with no knob.
    ablation_knobs: Mapping[str, float] = ABLATION_ARM_KNOBS.get(arm, {}) if arm in ABLATION_ARMS else {}
    return RuntimeTrainingConfig(
        run_id=run_id,
        trainer_kind=trainer_kind,
        arm=arm,
        seed=seed,
        model_path=str(args.model_path.resolve()),
        model_revision=args.model_revision,
        model_snapshot_sha256=args.model_snapshot_sha256,
        dataset_path=str((dataset_path or args.dataset).resolve()),
        dataset_asset_root=str(args.dataset_asset_root.resolve()),
        output_dir=str(output_dir.resolve()),
        initial_checkpoint_path=str(args.initial_checkpoint.resolve()),
        environment_lock_path=str(args.environment_lock.resolve()),
        environment_lock_sha256=args.environment_lock_sha256,
        evaluation_manifest_path=str(args.evaluation_manifest.resolve()),
        evaluation_manifest_sha256=args.evaluation_manifest_sha256,
        system_prompt_sha256=sha256_file(repo_root() / "prompts" / "common_system.txt"),
        precision="bf16",
        attention_implementation="flash_attention_2",
        max_prompt_tokens=args.max_prompt_tokens,
        max_completion_tokens=args.max_completion_tokens,
        total_context_tokens=args.max_prompt_tokens + args.max_completion_tokens,
        per_device_train_batch_size=args.per_device_batch_size,
        gradient_accumulation_steps=args.gradient_accumulation_steps,
        world_size=args.world_size,
        generations_per_prompt=1 if trainer_kind == "sft" else args.generations,
        checkpoint_interval=args.checkpoint_interval,
        max_optimizer_steps=-1 if trainer_kind == "sft" else args.max_optimizer_steps,
        max_completion_tokens_per_run=args.token_cap,
        learning_rate=args.learning_rate,
        lora_rank=64,
        lora_alpha=128,
        lora_dropout=0.0,
        lora_target_modules=tuple(args.target_module or ["all-linear"]),
        comparison_slot_manifest_sha256=args.comparison_slot_manifest_sha256,
        backend_entrypoint=args.backend_entrypoint,
        use_vllm=trainer_kind != "sft",
        run_mode=run_mode,
        compatibility_gate_path=(
            str(args.compatibility_gate.resolve())
            if run_mode == "main" and args.compatibility_gate is not None
            else None
        ),
        evi_direction_loss_weight=(
            ablation_knobs.get("lambda_direction", args.evi_direction_loss_weight)
            if trainer_kind == "evi_po"
            else 0.0
        ),
        evi_evidence_loss_weight=(
            ablation_knobs.get("lambda_evidence", args.evi_evidence_loss_weight)
            if trainer_kind == "evi_po"
            else 0.0
        ),
        evi_direction_margin=(
            ablation_knobs.get("margin", args.evi_direction_margin)
            if trainer_kind == "evi_po"
            else 0.0
        ),
        papo_mask_ratio=(
            ablation_knobs.get("mask_ratio", 0.6) if trainer_kind == "papo" else 0.6
        ),
        papo_perception_loss_weight=(
            ablation_knobs.get("perception_loss_weight", 0.02)
            if trainer_kind == "papo"
            else 0.02
        ),
    )


def _write_plan(
    args: argparse.Namespace,
    *,
    runtime: RuntimeTrainingConfig,
    run_dir: Path,
    source_config_sha256: str,
    dataset_manifest_sha256: str | None = None,
) -> tuple[Path, Path, tuple[str, ...]]:
    config_path = run_dir / "frozen-config.json"
    command = build_launch_command(
        config_path,
        world_size=runtime.world_size,
        python_executable=args.python_executable,
    )
    frozen, manifest = build_run_manifest(
        runtime,
        source_config_sha256=source_config_sha256,
        dataset_manifest_sha256=dataset_manifest_sha256 or args.dataset_manifest_sha256,
        initial_checkpoint_sha256=args.initial_checkpoint_sha256,
        code_commit=args.code_commit,
        created_at=args.created_at,
        launcher_command=command,
    )
    written_config, written_manifest = write_frozen_run(
        run_dir,
        frozen_config=frozen,
        run_manifest=manifest,
    )
    return written_config, written_manifest, command


def cmd_sft(args: argparse.Namespace) -> int:
    try:
        experiment = _load_yaml(args.experiment_config)
        _validate_runtime_args_against_config(args, experiment, sft=True)
        runtime = _runtime_from_args(
            args,
            run_id=args.run_id,
            trainer_kind="sft",
            arm=args.arm,
            seed=args.seed,
            output_dir=args.run_dir,
            run_mode="sft",
        )
        config_path, manifest_path, command = _write_plan(
            args,
            runtime=runtime,
            run_dir=args.run_dir,
            source_config_sha256=canonical_config_hash(experiment),
        )
    except (RunArtifactError, OSError, ValueError) as exc:
        print(f"SFT PLAN FAILED: {exc}", file=sys.stderr)
        return 1
    if args.execute:
        try:
            return execute(config_path)
        except LauncherUnavailable as exc:
            print(f"TRAINING BLOCKED: {exc}", file=sys.stderr)
            return 2
    check = check_launcher_environment(config_path) if args.check_launcher else None
    print(
        json.dumps(
            {
                "status": "planned",
                "trained": False,
                "config": str(config_path),
                "manifest": str(manifest_path),
                "launcher_command": command,
                "launcher_ready": check.ok if check else None,
                "launcher_errors": check.errors if check else (),
            },
            sort_keys=True,
        )
    )
    return 0 if check is None or check.ok else 2


def _plan_matrix(
    args: argparse.Namespace,
    *,
    rows: list[Mapping[str, Any]],
    source_config_sha256: str,
    sft: bool,
    run_mode: RunMode,
    dataset_by_identity: Mapping[str, Path] | None = None,
    dataset_sha_by_identity: Mapping[str, str] | None = None,
) -> list[dict[str, Any]]:
    planned: list[dict[str, Any]] = []
    for row in rows:
        if not isinstance(row, Mapping):
            raise RunArtifactError("matrix rows must be mappings")
        run_id = str(row.get("run_id", ""))
        if not run_id:
            raise RunArtifactError("matrix row has no run_id")
        arm = str(row.get("arm") or row.get("data") or "")
        seed = int(row.get("seed", args.seed))
        trainer_kind: TrainerKind = "sft" if sft else arm_trainer_kind(arm)
        run_dir = args.run_root / run_id
        runtime = _runtime_from_args(
            args,
            run_id=run_id,
            trainer_kind=trainer_kind,
            arm=arm,
            seed=seed,
            output_dir=run_dir,
            run_mode=run_mode,
            dataset_path=dataset_by_identity.get(arm) if dataset_by_identity else None,
        )
        config_path, manifest_path, command = _write_plan(
            args,
            runtime=runtime,
            run_dir=run_dir,
            source_config_sha256=source_config_sha256,
            dataset_manifest_sha256=(
                dataset_sha_by_identity.get(arm) if dataset_sha_by_identity else None
            ),
        )
        planned.append(
            {
                "run_id": run_id,
                "arm": arm,
                "seed": seed,
                "trainer_kind": trainer_kind,
                "config": str(config_path),
                "manifest": str(manifest_path),
                "launcher_command": command,
            }
        )
    return planned


def _validate_rl_matrix(rows: Any, *, token_cap: int) -> list[Mapping[str, Any]]:
    if not isinstance(rows, list):
        raise RunArtifactError("main_rl_runs must be a list")
    if len(rows) != len(_EXPECTED_RL_RUNS):
        raise RunArtifactError(
            f"main_rl_runs must contain exactly {len(_EXPECTED_RL_RUNS)} rows, found {len(rows)}"
        )
    validated: list[Mapping[str, Any]] = []
    identities: set[tuple[str, int]] = set()
    run_ids: set[str] = set()
    for index, row in enumerate(rows):
        if not isinstance(row, Mapping):
            raise RunArtifactError(f"main_rl_runs[{index}] must be a mapping")
        run_id = str(row.get("run_id", ""))
        if not run_id or run_id in run_ids:
            raise RunArtifactError(f"main_rl_runs[{index}] has missing or duplicate run_id")
        run_ids.add(run_id)
        if row.get("model") != "qwen35_2b":
            raise RunArtifactError(f"main_rl_runs[{index}] must use model qwen35_2b")
        arm = str(row.get("arm", ""))
        raw_seed = row.get("seed")
        if isinstance(raw_seed, bool) or not isinstance(raw_seed, int):
            raise RunArtifactError(f"main_rl_runs[{index}] has invalid seed")
        seed = raw_seed
        identity = (arm, seed)
        if identity in identities:
            raise RunArtifactError(f"duplicate main RL arm/seed identity: {identity}")
        identities.add(identity)
        validated.append(row)
    if identities != _EXPECTED_RL_RUNS:
        missing = sorted(_EXPECTED_RL_RUNS - identities)
        extra = sorted(identities - _EXPECTED_RL_RUNS)
        raise RunArtifactError(
            f"{len(_EXPECTED_RL_RUNS)}-run matrix identity drift; missing={missing}, extra={extra}"
        )
    if token_cap > _RL_TOKEN_CAP:
        raise RunArtifactError(f"per-run completion-token cap exceeds {_RL_TOKEN_CAP}")
    if token_cap * len(validated) > _TOTAL_RL_TOKEN_CAP:
        raise RunArtifactError(f"matrix completion-token cap exceeds {_TOTAL_RL_TOKEN_CAP}")
    return validated


def _validate_ablation_matrix(rows: Any, *, token_cap: int) -> list[Mapping[str, Any]]:
    """Validate the two-run core ingredient-isolation ablation matrix."""

    if not isinstance(rows, list):
        raise RunArtifactError("ablation_rl_runs must be a list")
    if len(rows) != len(_EXPECTED_ABLATION_RUNS):
        raise RunArtifactError(
            f"ablation_rl_runs must contain exactly {len(_EXPECTED_ABLATION_RUNS)} rows, "
            f"found {len(rows)}"
        )
    validated: list[Mapping[str, Any]] = []
    identities: set[tuple[str, int]] = set()
    run_ids: set[str] = set()
    for index, row in enumerate(rows):
        if not isinstance(row, Mapping):
            raise RunArtifactError(f"ablation_rl_runs[{index}] must be a mapping")
        run_id = str(row.get("run_id", ""))
        if not run_id or run_id in run_ids:
            raise RunArtifactError(f"ablation_rl_runs[{index}] has missing or duplicate run_id")
        run_ids.add(run_id)
        if row.get("model") != "qwen35_2b":
            raise RunArtifactError(f"ablation_rl_runs[{index}] must use model qwen35_2b")
        arm = str(row.get("arm", ""))
        if arm not in CORE_ABLATION_ARMS:
            raise RunArtifactError(f"ablation_rl_runs[{index}] has non-core ablation arm {arm!r}")
        raw_seed = row.get("seed")
        if isinstance(raw_seed, bool) or not isinstance(raw_seed, int):
            raise RunArtifactError(f"ablation_rl_runs[{index}] has invalid seed")
        identity = (arm, int(raw_seed))
        if identity in identities:
            raise RunArtifactError(f"duplicate ablation arm/seed identity: {identity}")
        identities.add(identity)
        validated.append(row)
    if identities != _EXPECTED_ABLATION_RUNS:
        missing = sorted(_EXPECTED_ABLATION_RUNS - identities)
        extra = sorted(identities - _EXPECTED_ABLATION_RUNS)
        raise RunArtifactError(
            f"{len(_EXPECTED_ABLATION_RUNS)}-run ablation identity drift; "
            f"missing={missing}, extra={extra}"
        )
    if token_cap > _RL_TOKEN_CAP:
        raise RunArtifactError(f"per-run completion-token cap exceeds {_RL_TOKEN_CAP}")
    if token_cap * len(validated) > _TOTAL_ABLATION_TOKEN_CAP:
        raise RunArtifactError(
            f"ablation completion-token cap exceeds {_TOTAL_ABLATION_TOKEN_CAP}"
        )
    return validated


def _validate_smoke_matrix(rows: Any, *, token_cap: int) -> list[Mapping[str, Any]]:
    if not isinstance(rows, list) or len(rows) != len(_EXPECTED_SMOKE_RUNS):
        raise RunArtifactError(
            f"smoke_rl_runs must contain exactly {len(_EXPECTED_SMOKE_RUNS)} rows"
        )
    validated: list[Mapping[str, Any]] = []
    identities: set[tuple[str, int]] = set()
    run_ids: set[str] = set()
    for index, row in enumerate(rows):
        if not isinstance(row, Mapping):
            raise RunArtifactError(f"smoke_rl_runs[{index}] must be a mapping")
        run_id = str(row.get("run_id", ""))
        arm = str(row.get("arm", ""))
        seed = row.get("seed")
        if not run_id or run_id in run_ids or isinstance(seed, bool) or not isinstance(seed, int):
            raise RunArtifactError(f"smoke_rl_runs[{index}] has an invalid run_id or seed")
        if row.get("model") != "qwen35_2b":
            raise RunArtifactError(f"smoke_rl_runs[{index}] must use model qwen35_2b")
        run_ids.add(run_id)
        identities.add((arm, seed))
        validated.append(row)
    if identities != _EXPECTED_SMOKE_RUNS:
        raise RunArtifactError(
            "controlled-arm smoke identity drift; expected "
            f"{sorted(_EXPECTED_SMOKE_RUNS)}, found {sorted(identities)}"
        )
    if token_cap > _RL_TOKEN_CAP:
        raise RunArtifactError(f"smoke completion-token cap exceeds {_RL_TOKEN_CAP}")
    return validated


def _validate_sft_matrix(rows: Any) -> list[Mapping[str, Any]]:
    if not isinstance(rows, list):
        raise RunArtifactError("sft_ablation_runs must be a list")
    if len(rows) != 2:
        raise RunArtifactError(
            f"sft_ablation_runs must contain exactly two rows, found {len(rows)}"
        )
    validated: list[Mapping[str, Any]] = []
    run_ids: set[str] = set()
    data_identities: set[str] = set()
    for index, row in enumerate(rows):
        if not isinstance(row, Mapping):
            raise RunArtifactError(f"sft_ablation_runs[{index}] must be a mapping")
        run_id = str(row.get("run_id", ""))
        data = str(row.get("data", ""))
        if not run_id or run_id in run_ids:
            raise RunArtifactError(f"sft_ablation_runs[{index}] has missing or duplicate run_id")
        if data in data_identities:
            raise RunArtifactError(f"duplicate SFT data identity: {data!r}")
        if row.get("model") not in {None, "qwen35_2b"}:
            raise RunArtifactError(f"sft_ablation_runs[{index}] must use model qwen35_2b")
        run_ids.add(run_id)
        data_identities.add(data)
        validated.append(row)
    if data_identities != _EXPECTED_SFT_DATA:
        raise RunArtifactError(
            "SFT ablation identity drift; expected "
            f"{sorted(_EXPECTED_SFT_DATA)}, found {sorted(data_identities)}"
        )
    return validated


def cmd_run_matrix(args: argparse.Namespace) -> int:
    try:
        config = _load_yaml(args.matrix_config)
        _validate_runtime_args_against_config(args, config, sft=False)
        rows = _validate_rl_matrix(config.get("main_rl_runs"), token_cap=args.token_cap)
        planned = _plan_matrix(
            args,
            rows=rows,
            source_config_sha256=canonical_config_hash(config),
            sft=False,
            run_mode="main",
        )
    except (RunArtifactError, OSError, ValueError) as exc:
        print(f"RUN MATRIX PLAN FAILED: {exc}", file=sys.stderr)
        return 1
    print(json.dumps({"status": "planned", "trained": False, "runs": planned}, sort_keys=True))
    return 0


def cmd_run_rl_ablation(args: argparse.Namespace) -> int:
    try:
        config = _load_yaml(args.matrix_config)
        _validate_runtime_args_against_config(args, config, sft=False, run_mode="main")
        rows = _validate_ablation_matrix(config.get("ablation_rl_runs"), token_cap=args.token_cap)
        planned = _plan_matrix(
            args,
            rows=rows,
            source_config_sha256=canonical_config_hash(config),
            sft=False,
            run_mode="main",
        )
    except (RunArtifactError, OSError, ValueError) as exc:
        print(f"RL ABLATION PLAN FAILED: {exc}", file=sys.stderr)
        return 1
    print(json.dumps({"status": "planned", "trained": False, "runs": planned}, sort_keys=True))
    return 0


def _execute_smoke_plan(plan: Mapping[str, Any]) -> dict[str, Any]:
    import time

    config = Path(str(plan["config"]))
    command = tuple(str(part) for part in plan["launcher_command"])
    output = config.parent
    completion = output / "training-complete.json"
    resume_boundary = output / "smoke-resume-boundary.json"
    phase_seconds: dict[int, float] = {}
    started = time.monotonic()
    for phase in (1, 2):
        phase_start = time.monotonic()
        completed = subprocess.run(command, check=False).returncode
        phase_seconds[phase] = time.monotonic() - phase_start
        if completed == 0 and completion.is_file():
            return {
                "run_id": plan["run_id"],
                "completed": True,
                "process_phases": phase,
                "completion": str(completion),
                "wall_clock_seconds": time.monotonic() - started,
                "phase_seconds": phase_seconds,
            }
        if phase == 1 and resume_boundary.is_file() and not completion.exists():
            continue
        raise RunArtifactError(
            f"smoke subprocess failed for {plan['run_id']} in phase {phase} "
            f"(exit={completed}, boundary={resume_boundary.exists()})"
        )
    raise AssertionError("smoke process loop exhausted")


def _print_smoke_timing(
    planned: Sequence[Mapping[str, Any]], completed: Sequence[Mapping[str, Any]]
) -> None:
    """Print a per-arm wall-clock timing table (markdown) to stdout.

    Columns: run_id | arm | seed | phases | wall-clock | phase-1 | phase-2.
    ``phase-1`` is the step-0..5 run ending at the forced resume boundary;
    ``phase-2`` is the resume-to-20 run. Times are seconds.
    """
    plan_by_id = {plan["run_id"]: plan for plan in planned}

    def _s(v: Any) -> str:
        return f"{v:.1f}" if isinstance(v, float) else "?"

    print("\n## smoke matrix timing (per run, seconds)\n")
    print("| run_id | arm | seed | phases | wall-clock | phase-1 | phase-2 |")
    print("|--------|-----|------|--------|-----------|---------|---------|")
    for done in completed:
        plan = plan_by_id.get(done.get("run_id", ""), {})
        rid = done.get("run_id", "?")
        arm = plan.get("arm", "?")
        seed = plan.get("seed", "?")
        phases = done.get("process_phases", "?")
        wall = done.get("wall_clock_seconds")
        secs = done.get("phase_seconds") or {}
        print(
            f"| {rid} | {arm} | {seed} | {phases} | "
            f"{_s(wall)} | {_s(secs.get(1))} | {_s(secs.get(2))} |"
        )
    total = sum(d.get("wall_clock_seconds") or 0.0 for d in completed)
    print(f"\n**total wall-clock: {total:.1f}s** across {len(completed)} runs\n")


def cmd_run_smoke_matrix(args: argparse.Namespace) -> int:
    """Freeze or execute one 20-step, forced-resume smoke per GPU trainer."""

    try:
        config = _load_yaml(args.matrix_config)
        _validate_runtime_args_against_config(
            args,
            config,
            sft=False,
            run_mode="smoke",
        )
        rows = _validate_smoke_matrix(
            config.get("smoke_rl_runs"),
            token_cap=args.token_cap,
        )
        planned = _plan_matrix(
            args,
            rows=rows,
            source_config_sha256=canonical_config_hash(config),
            sft=False,
            run_mode="smoke",
        )
        completed = [_execute_smoke_plan(plan) for plan in planned] if args.execute else []
    except (RunArtifactError, OSError, ValueError) as exc:
        print(f"SMOKE MATRIX FAILED: {exc}", file=sys.stderr)
        return 1
    if args.execute and completed:
        _print_smoke_timing(planned, completed)
    print(
        json.dumps(
            {
                "status": "completed" if args.execute else "planned",
                "trained": bool(args.execute),
                "forced_process_resume_step": 5,
                "runs": planned,
                "completed_runs": completed,
            },
            sort_keys=True,
        )
    )
    return 0


def cmd_certify_smoke_gate(args: argparse.Namespace) -> int:
    try:
        gate = certify_smoke_gate(args.config, args.output)
    except (OSError, SmokeGateError, TypeError, ValueError) as exc:
        print(f"SMOKE GATE CERTIFICATION FAILED: {exc}", file=sys.stderr)
        return 1
    print(
        json.dumps(
            {
                "status": gate["status"],
                "output": str(args.output),
                "common_contract_sha256": gate["common_contract_sha256"],
            },
            sort_keys=True,
        )
    )
    return 0


def cmd_run_sft_ablation(args: argparse.Namespace) -> int:
    try:
        config = _load_yaml(args.matrix_config)
        _validate_runtime_args_against_config(args, config, sft=True)
        rows = _validate_sft_matrix(config.get("sft_ablation_runs"))
        planned = _plan_matrix(
            args,
            rows=rows,
            source_config_sha256=canonical_config_hash(config),
            sft=True,
            run_mode="sft",
            dataset_by_identity={
                "full_only": args.full_only_dataset,
                "full_plus_certified_intervention": args.full_intervention_dataset,
            },
            dataset_sha_by_identity={
                "full_only": args.full_only_dataset_sha256,
                "full_plus_certified_intervention": args.full_intervention_dataset_sha256,
            },
        )
    except (RunArtifactError, OSError, ValueError) as exc:
        print(f"SFT ABLATION PLAN FAILED: {exc}", file=sys.stderr)
        return 1
    print(json.dumps({"status": "planned", "trained": False, "runs": planned}, sort_keys=True))
    return 0


def cmd_rl_smoke(args: argparse.Namespace) -> int:
    if args.offline:
        try:
            summary = offline_contract_smoke(
                steps_per_arm=args.steps,
                seed=args.seed,
                token_cap=args.token_cap,
            )
        except (ValueError, AdmissionError, LedgerError) as exc:
            print(f"RL OFFLINE SMOKE FAILED: {exc}", file=sys.stderr)
            return 1
        summary["requested_arm"] = args.arm
        print(json.dumps(summary, sort_keys=True))
        return 0
    if args.frozen_config is None:
        print("RL SMOKE BLOCKED: provide --offline or --frozen-config", file=sys.stderr)
        return 2
    check = check_launcher_environment(args.frozen_config)
    print(json.dumps({"ok": check.ok, "trained": False, "errors": check.errors}, sort_keys=True))
    return 0 if check.ok else 2


def _add_dataset_admission(parser: argparse.ArgumentParser) -> None:
    parser.add_argument("--dataset", type=Path, required=True, help="intervention groups JSONL.")
    parser.add_argument("--asset-root", type=Path, required=True)
    parser.add_argument(
        "--validator",
        default="builtin-certified-release",
        help="module:function callback invoked for group, image, and certificate admission.",
    )
    parser.add_argument("--output", type=Path, required=True)


def _add_runtime_args(
    parser: argparse.ArgumentParser,
    *,
    include_run_id: bool,
    default_token_cap: int,
    include_dataset: bool = True,
    default_optimizer_steps: int = 5750,
) -> None:
    if include_run_id:
        parser.add_argument("--run-id", required=True)
        parser.add_argument("--run-dir", type=Path, required=True)
        parser.add_argument(
            "--experiment-config",
            type=Path,
            default=Path("configs/experiment.yaml"),
        )
    else:
        parser.add_argument("--run-root", type=Path, required=True)
        parser.add_argument("--matrix-config", type=Path, required=True)
    parser.add_argument("--model-path", type=Path, required=True)
    parser.add_argument("--model-revision", default=QWEN35_2B_REVISION)
    parser.add_argument("--model-snapshot-sha256", required=True)
    parser.add_argument("--dataset-asset-root", type=Path, required=True)
    if include_dataset:
        parser.add_argument("--dataset", type=Path, required=True)
        parser.add_argument("--dataset-manifest-sha256", required=True)
    parser.add_argument(
        "--comparison-slot-manifest-sha256",
        help="Required for RL plans; binds every arm to one ordered slot schedule.",
    )
    parser.add_argument("--initial-checkpoint", type=Path, required=True)
    parser.add_argument("--initial-checkpoint-sha256", required=True)
    parser.add_argument("--environment-lock", type=Path, required=True)
    parser.add_argument("--environment-lock-sha256", required=True)
    parser.add_argument("--evaluation-manifest", type=Path, required=True)
    parser.add_argument("--evaluation-manifest-sha256", required=True)
    parser.add_argument("--compatibility-gate", type=Path)
    parser.add_argument("--code-commit", required=True)
    parser.add_argument("--created-at", required=True)
    parser.add_argument("--seed", type=int, default=1)
    parser.add_argument("--per-device-batch-size", type=int, default=1)
    parser.add_argument("--gradient-accumulation-steps", type=int, default=16)
    parser.add_argument("--world-size", type=int, default=2)
    parser.add_argument("--generations", type=int, default=4)
    parser.add_argument("--checkpoint-interval", type=int, default=100)
    parser.add_argument(
        "--max-optimizer-steps",
        type=int,
        default=default_optimizer_steps,
    )
    parser.add_argument("--token-cap", type=int, default=default_token_cap)
    parser.add_argument("--learning-rate", type=float, default=1e-6)
    parser.add_argument("--max-prompt-tokens", type=int, default=4096)
    parser.add_argument("--max-completion-tokens", type=int, default=256)
    parser.add_argument("--evi-direction-loss-weight", type=float, default=0.1)
    parser.add_argument("--evi-evidence-loss-weight", type=float, default=0.1)
    parser.add_argument("--evi-direction-margin", type=float, default=0.5)
    parser.add_argument("--target-module", action="append")
    parser.add_argument(
        "--backend-entrypoint",
        default="explicit_learning.training.backend:run",
    )
    parser.add_argument("--python-executable", default=sys.executable)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="explicit-train")
    sub = parser.add_subparsers(dest="command", required=True)

    dry = sub.add_parser("dry-run", help="CPU-only all-arm contract exercise; never trains.")
    dry.add_argument("--steps-per-arm", type=int, default=2)
    dry.add_argument("--seed", type=int, default=20260728)
    dry.add_argument("--token-cap", type=int, default=1024)
    dry.set_defaults(func=cmd_dry_run)

    environment = sub.add_parser(
        "snapshot-environment",
        help="Write the immutable installed Python/CUDA/wheel environment lock.",
    )
    environment.add_argument("--output", type=Path, required=True)
    environment.set_defaults(func=cmd_snapshot_environment)

    sft_data = sub.add_parser("build-common-sft-data")
    _add_dataset_admission(sft_data)
    sft_data.add_argument(
        "--mode",
        choices=["full_only", "full_plus_certified_intervention"],
        default="full_only",
    )
    sft_data.set_defaults(func=cmd_build_common_sft_data)

    slots = sub.add_parser("build-comparison-slots")
    _add_dataset_admission(slots)
    slots.add_argument("--seed", type=int, default=20260728)
    slots.add_argument("--max-slots", type=int, default=46000)
    slots.set_defaults(func=cmd_build_comparison_slots)

    training_inputs = sub.add_parser(
        "build-training-inputs",
        help="Admit once and atomically publish slots plus both raw SFT datasets.",
    )
    training_inputs.add_argument("--dataset", type=Path, required=True)
    training_inputs.add_argument("--asset-root", type=Path, required=True)
    training_inputs.add_argument(
        "--validator",
        default="builtin-certified-release",
        help="module:function callback invoked for group, image, and certificate admission.",
    )
    training_inputs.add_argument("--release-manifest", type=Path, required=True)
    training_inputs.add_argument(
        "--replay-report",
        type=Path,
        default=None,
        help="Required only for legacy bundles that use full certificate replay.",
    )
    training_inputs.add_argument("--output-dir", type=Path, required=True)
    training_inputs.add_argument("--code-commit", required=True)
    training_inputs.add_argument("--seed", type=int, default=20260728)
    training_inputs.add_argument("--max-slots", type=int, default=46000)
    training_inputs.add_argument("--workers", type=int, default=8)
    training_inputs.set_defaults(func=cmd_build_training_inputs)

    schedules = sub.add_parser(
        "match-sft-schedules",
        help="Build token-matched, non-duplicated one-epoch SFT schedules.",
    )
    schedules.add_argument("--full-input", type=Path, required=True)
    schedules.add_argument("--pair-input", type=Path, required=True)
    schedules.add_argument("--full-output", type=Path, required=True)
    schedules.add_argument("--pair-output", type=Path, required=True)
    schedules.add_argument("--manifest-output", type=Path, required=True)
    schedules.add_argument("--model-path", type=Path, required=True)
    schedules.add_argument("--model-revision", default=QWEN35_2B_REVISION)
    schedules.add_argument("--model-snapshot-sha256", required=True)
    schedules.add_argument("--asset-root", type=Path, required=True)
    schedules.add_argument("--intervention-per-state", type=int, default=300)
    schedules.set_defaults(func=cmd_match_sft_schedules)

    sft = sub.add_parser("sft", help="Freeze an SFT launch plan; --execute is explicit.")
    _add_runtime_args(sft, include_run_id=True, default_token_cap=_SFT_TOKEN_CAP)
    sft.add_argument(
        "--arm",
        choices=["full_only", "full_plus_certified_intervention"],
        default="full_only",
    )
    sft.add_argument("--check-launcher", action="store_true")
    sft.add_argument("--execute", action="store_true")
    sft.set_defaults(func=cmd_sft)

    smoke = sub.add_parser("rl-smoke")
    smoke.add_argument("--offline", action="store_true")
    smoke.add_argument(
        "--arm",
        choices=[
            "answer_grpo",
            "papo_controlled",
            "defacto_controlled",
            "intervention_grpo",
            "evi_po",
        ],
    )
    smoke.add_argument("--steps", type=int, default=2)
    smoke.add_argument("--seed", type=int, default=1)
    smoke.add_argument("--token-cap", type=int, default=1024)
    smoke.add_argument("--frozen-config", type=Path)
    smoke.set_defaults(func=cmd_rl_smoke)

    smoke_matrix = sub.add_parser(
        "run-smoke-matrix",
        help="Freeze or execute one 20-step smoke per GPU trainer with forced resume.",
    )
    _add_runtime_args(
        smoke_matrix,
        include_run_id=False,
        default_token_cap=_RL_TOKEN_CAP,
        default_optimizer_steps=20,
    )
    smoke_matrix.add_argument("--execute", action="store_true")
    smoke_matrix.set_defaults(func=cmd_run_smoke_matrix)

    smoke_gate = sub.add_parser(
        "certify-smoke-gate",
        help="Certify the three completed 20-step GPU trainer smokes once.",
    )
    smoke_gate.add_argument("--config", type=Path, action="append", required=True)
    smoke_gate.add_argument("--output", type=Path, required=True)
    smoke_gate.set_defaults(func=cmd_certify_smoke_gate)

    matrix = sub.add_parser(
        "run-matrix",
        help="Freeze the controlled launch matrix; does not submit jobs.",
    )
    _add_runtime_args(matrix, include_run_id=False, default_token_cap=_RL_TOKEN_CAP)
    matrix.set_defaults(func=cmd_run_matrix)

    rl_ablation = sub.add_parser(
        "run-rl-ablation",
        help="Freeze the two direct EVI ingredient ablations; does not submit jobs.",
    )
    _add_runtime_args(
        rl_ablation, include_run_id=False, default_token_cap=_RL_TOKEN_CAP
    )
    rl_ablation.set_defaults(func=cmd_run_rl_ablation)

    ablation = sub.add_parser(
        "run-sft-ablation", help="Freeze SFT ablation plans; does not submit jobs."
    )
    _add_runtime_args(
        ablation,
        include_run_id=False,
        default_token_cap=_SFT_TOKEN_CAP,
        include_dataset=False,
    )
    ablation.add_argument("--full-only-dataset", type=Path, required=True)
    ablation.add_argument("--full-only-dataset-sha256", required=True)
    ablation.add_argument("--full-intervention-dataset", type=Path, required=True)
    ablation.add_argument("--full-intervention-dataset-sha256", required=True)
    ablation.set_defaults(func=cmd_run_sft_ablation)
    return parser


def main(argv: list[str] | None = None) -> int:
    if argv == []:
        build_parser().print_usage(sys.stderr)
        return 2
    args = build_parser().parse_args(argv)
    return int(args.func(args))


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