File size: 29,326 Bytes
10979b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Generate and fail-closed validate the single-seed ImageNet follow-up batch."""

from __future__ import annotations

import argparse
import copy
import hashlib
import json
import math
import sys
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

import yaml

SCRIPT_PATH = Path(__file__).resolve()
JOURNAL_ROOT = SCRIPT_PATH.parents[1]
GMNET_ROOT = JOURNAL_ROOT.parent
PROTOCOL_PATH = JOURNAL_ROOT / "configs/single_seed_followup_protocol.yaml"
BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
BATCH_ROOT = GMNET_ROOT / "depoly/single_seed_followup_20260715"
RUN_ROOT = GMNET_ROOT / "runs/single_seed_followup"
CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"
GENERATED_HEADER = (
    "# Generated by journal_exp/scripts/generate_single_seed_followup.py; "
    "do not edit.\n"
)
APPROVAL_ROOT = BATCH_ROOT / "approvals"
TASK_IDS = (
    "ssfu_e3_s3_no_gate_seed0",
    "ssfu_e3_s3_relu6_only_seed0",
    "ssfu_e3_s3_smooth_fixed_c6_seed0",
    "ssfu_e0_s3_release_paperbn_seed0",
)
RESOURCE_KEYS = (
    "gpu_type",
    "gpu_num",
    "gpu_memory",
    "cpu_num",
    "memory",
    "efa",
    "priority",
    "pytorchjob",
    "custom_node_labels",
    "volcano_queue",
)
PROJECT_KEYS = (
    "project_name",
    "project_support_alias",
    "team",
    "cost_team",
    "cost_feature",
    "cost_sub_feature",
    "docker_image",
    "mount",
)


class ApprovalError(RuntimeError):
    """Raised when a launch is intentionally denied by the batch protocol."""


@dataclass(frozen=True)
class FollowupTask:
    task_id: str
    experiment: str
    model: str
    gate: str
    seed: int
    config_path: str
    role: str
    status: str
    submission_allowed: bool
    evidence: tuple[str, ...]
    contrast: str
    question: str
    trigger: dict[str, Any] | None = None

    @property
    def output_dir(self) -> Path:
        return RUN_ROOT / self.task_id

    @property
    def deploy_path(self) -> Path:
        return BATCH_ROOT / f"{self.task_id}.yaml"

    @property
    def approval_path(self) -> Path:
        return APPROVAL_ROOT / f"{self.task_id}.json"

    @property
    def job_name(self) -> str:
        return "gmnet-" + self.task_id.replace("_", "-")


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


def stable_sha256(value: Any) -> str:
    payload = json.dumps(
        value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def load_yaml(path: Path) -> dict[str, Any]:
    loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
    if not isinstance(loaded, dict):
        raise ValueError(f"expected a YAML mapping: {path}")
    return loaded


def load_protocol() -> dict[str, Any]:
    return load_yaml(PROTOCOL_PATH)


def build_tasks(protocol: dict[str, Any] | None = None) -> list[FollowupTask]:
    protocol = load_protocol() if protocol is None else protocol
    records = protocol.get("tasks")
    if not isinstance(records, list):
        raise ValueError("follow-up protocol tasks must be a list")
    tasks = [
        FollowupTask(
            task_id=str(record["task_id"]),
            experiment=str(record["experiment"]),
            model=str(record["model"]),
            gate=str(record["gate"]),
            seed=int(record["seed"]),
            config_path=str(record["config_path"]),
            role=str(record["role"]),
            status=str(record["status"]),
            submission_allowed=bool(record["submission_allowed"]),
            evidence=tuple(record.get("evidence", [])),
            contrast=str(record["contrast"]),
            question=str(record["question"]),
            trigger=copy.deepcopy(record.get("trigger")),
        )
        for record in records
    ]
    validate_protocol(protocol, tasks)
    return tasks


def load_resolved_config(path: Path) -> dict[str, Any]:
    if str(JOURNAL_ROOT) not in sys.path:
        sys.path.insert(0, str(JOURNAL_ROOT))
    from gmnet.config import load_config

    return load_config(path)


def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None:
    value: Any = config
    for part in dotted_key.split("."):
        if not isinstance(value, dict) or part not in value:
            raise ValueError(f"missing config value {dotted_key}")
        value = value[part]
    if value != expected:
        raise ValueError(
            f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}"
        )


def validate_task_config(
    protocol: dict[str, Any], task: FollowupTask, config: dict[str, Any]
) -> None:
    release_audit = task.role == "conditional_recipe_audit"
    expected_gate = (
        "smooth_clipped_self"
        if task.gate == "smooth_clipped_self_fixed_c6"
        else task.gate
    )
    common = {
        "model.variant": task.model,
        "model.gate_type": expected_gate,
        "model.num_classes": 1000,
        "model.f12_bn": False,
        "model.projection_bn": True,
        "model.second_dw_bn": False,
        "data.dataset": "imagenet",
        "data.expected_train_samples": protocol["data"]["expected_train_samples"],
        "data.expected_val_samples": protocol["data"]["expected_val_samples"],
        "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"],
        "train.fail_on_nonfinite": True,
        "train.strict_resume": True,
        "train.official_validation_policy": "final_epoch_only",
        "train.save_best_checkpoint": False,
    }
    for key, expected in common.items():
        require_value(config, key, expected)

    patterns = config.get("optimizer", {}).get("no_weight_decay_patterns")
    if not isinstance(patterns, list) or "raw_clip" not in patterns:
        raise ValueError(f"{task.task_id} must exclude raw_clip from weight decay")

    if release_audit:
        require_value(config, "recipe_id", "release-readme-legacy-audit-only")
        require_value(config, "model.drop_path_rate", 0.0)
        require_value(config, "train.epochs", 310)
        require_value(config, "train.eval_interval", 310)
    else:
        require_value(config, "recipe_id", "paper-supplementary-table8-v1")
        require_value(config, "model.drop_path_rate", 0.02)
        require_value(config, "train.epochs", 300)
        require_value(config, "train.eval_interval", 300)

    if task.gate == "smooth_clipped_self_fixed_c6":
        require_value(config, "model.smooth_clip_init", 6.0)
        require_value(config, "model.smooth_clip_beta", 10.0)
        require_value(config, "model.smooth_clip_per_channel", False)
        require_value(config, "model.smooth_clip_trainable", False)


def validate_protocol(protocol: dict[str, Any], tasks: list[FollowupTask]) -> None:
    if protocol.get("schema_version") != 1:
        raise ValueError("follow-up protocol schema_version must be 1")
    if protocol.get("protocol_id") != "imagenet-single-seed-followup-20260715":
        raise ValueError("unexpected follow-up protocol_id")
    if Path(str(protocol.get("run_root"))) != RUN_ROOT:
        raise ValueError(f"follow-up run_root must be {RUN_ROOT}")
    if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT:
        raise ValueError(f"follow-up deploy_root must be {BATCH_ROOT}")
    if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH:
        raise ValueError("unexpected follow-up code manifest path")
    if tuple(task.task_id for task in tasks) != TASK_IDS:
        raise ValueError("follow-up task matrix or ordering drifted")
    if len(set(TASK_IDS)) != len(TASK_IDS):
        raise ValueError("duplicate follow-up task IDs")

    parent = protocol["parent_protocol"]
    parent_path = JOURNAL_ROOT / str(parent["path"])
    if file_sha256(parent_path) != parent["sha256"]:
        raise ValueError("parent ImageNet-v2 protocol hash drifted")
    resume = protocol["historical_resume_manifest"]
    if file_sha256(Path(str(resume["path"]))) != resume["sha256"]:
        raise ValueError("historical resume manifest hash drifted")

    evidence_ids = set(protocol.get("legacy_evidence", {}))
    ready = []
    for task in tasks:
        if task.seed != 0:
            raise ValueError(f"non-seed0 task is outside this batch: {task.task_id}")
        if task.status not in {"ready", "conditional"}:
            raise ValueError(f"invalid task status: {task.task_id}")
        if task.submission_allowed != (task.status == "ready"):
            raise ValueError(f"task status/permission mismatch: {task.task_id}")
        if not task.evidence or not set(task.evidence).issubset(evidence_ids):
            raise ValueError(f"missing or unknown evidence for {task.task_id}")
        if task.status == "conditional" and task.trigger is None:
            raise ValueError(f"conditional task lacks trigger: {task.task_id}")
        if task.status == "ready":
            ready.append(task.task_id)
        config_path = JOURNAL_ROOT / task.config_path
        if not config_path.is_file():
            raise FileNotFoundError(config_path)
        validate_task_config(protocol, task, load_resolved_config(config_path))
    if ready != list(TASK_IDS[:3]):
        raise ValueError("only the three mechanism tasks may be initially ready")


def normalized_training_semantics(config: dict[str, Any]) -> dict[str, Any]:
    normalized = copy.deepcopy(config)
    normalized.pop("runtime", None)
    normalized.pop("experiment_id", None)
    protocol = normalized.get("protocol")
    if isinstance(protocol, dict):
        protocol.pop("code_sha256", None)
        if not protocol:
            normalized.pop("protocol")
    return normalized


def _assert_finite(value: Any, location: str) -> None:
    if isinstance(value, float) and not math.isfinite(value):
        raise ValueError(f"non-finite value at {location}")
    if isinstance(value, dict):
        for key, child in value.items():
            _assert_finite(child, f"{location}.{key}")
    elif isinstance(value, list):
        for index, child in enumerate(value):
            _assert_finite(child, f"{location}[{index}]")


def verify_evidence(protocol: dict[str, Any], evidence_id: str) -> None:
    record = protocol["legacy_evidence"][evidence_id]
    if record.get("acceptance") != "accepted_historical_seed0_alias":
        raise ValueError(f"invalid evidence acceptance: {evidence_id}")
    if record.get("code_provenance") != "retrospective_unverified":
        raise ValueError(f"legacy provenance must remain unverified: {evidence_id}")
    run_dir = Path(str(record["run_dir"]))
    for relative, expected_sha in record["expected"].items():
        path = run_dir / relative
        if not path.is_file():
            raise FileNotFoundError(f"missing evidence file: {path}")
        actual_sha = file_sha256(path)
        if actual_sha != expected_sha:
            raise ValueError(
                f"evidence hash mismatch for {evidence_id}/{relative}: {actual_sha}"
            )

    expected = record["expected"]
    official = record["official"]
    checks = json.loads(
        (run_dir / "official_eval/checks.json").read_text(encoding="utf-8")
    )
    results = json.loads(
        (run_dir / "official_eval/results.json").read_text(encoding="utf-8")
    )
    manifest = json.loads((run_dir / "data_manifest.json").read_text(encoding="utf-8"))
    if checks.get("status") != "passed":
        raise ValueError(f"official check did not pass: {evidence_id}")
    if checks.get("checkpoint_sha256") != expected["checkpoint_last.pt"]:
        raise ValueError(f"official checkpoint identity mismatch: {evidence_id}")
    if checks.get("artifacts_sha256") != official["artifacts_sha256"]:
        raise ValueError(f"official artifact identity mismatch: {evidence_id}")
    if results.get("status") != "complete" or results.get("partial_evaluation"):
        raise ValueError(f"official evaluation is not complete: {evidence_id}")
    if results.get("run_name") != official["run_name"]:
        raise ValueError(f"official run identity mismatch: {evidence_id}")
    if results.get("seed") != 0 or results.get("gate_type") != official["gate_type"]:
        raise ValueError(f"official seed/gate mismatch: {evidence_id}")
    if not math.isclose(
        float(results["metrics"]["top1"]),
        float(official["top1"]),
        rel_tol=0.0,
        abs_tol=1e-9,
    ):
        raise ValueError(f"official Top-1 mismatch: {evidence_id}")
    if results["metrics"].get("samples") != protocol["data"]["expected_val_samples"]:
        raise ValueError(f"official sample count mismatch: {evidence_id}")
    if results["hashes"].get("config_sha256") != official["checkpoint_config_sha256"]:
        raise ValueError(f"checkpoint config identity mismatch: {evidence_id}")
    if (
        results["hashes"].get("checkpoint_data_manifest_sha256")
        != protocol["data"]["canonical_manifest_sha256"]
    ):
        raise ValueError(f"checkpoint data identity mismatch: {evidence_id}")
    topology = results["topology"]
    if (
        topology.get("parameter_count") != official["parameter_count"]
        or topology.get("state_tensor_count") != official["state_tensor_count"]
    ):
        raise ValueError(f"topology mismatch: {evidence_id}")
    completion = results["training_completion"]
    expected_completion = {
        "epoch_complete": True,
        "expected_global_step": 187500,
        "expected_steps_per_epoch": 625,
        "global_step": 187500,
        "steps_in_epoch": 625,
        "training_complete": True,
        "world_size": 8,
    }
    for key, value in expected_completion.items():
        if completion.get(key) != value:
            raise ValueError(f"training completion mismatch: {evidence_id}/{key}")
    if results.get("checkpoint_epoch") != 299 or results.get("training_epochs") != 300:
        raise ValueError(f"training epoch mismatch: {evidence_id}")

    data = protocol["data"]
    manifest_expected = {
        "manifest_sha256": data["canonical_manifest_sha256"],
        "num_classes": 1000,
        "samples": {
            "train": data["expected_train_samples"],
            "val": data["expected_val_samples"],
        },
        "sample_index_sha256": {
            "train": data["train_sample_index_sha256"],
            "val": data["val_sample_index_sha256"],
        },
        "sampled_content_sha256": {
            "train": data["train_sampled_content_sha256"],
            "val": data["val_sampled_content_sha256"],
        },
    }
    for key, value in manifest_expected.items():
        if manifest.get(key) != value:
            raise ValueError(f"data manifest mismatch: {evidence_id}/{key}")

    resolved = load_yaml(run_dir / "config_resolved.yaml")
    runtime = resolved.get("runtime", {})
    runtime_expected = {
        "run_name": official["run_name"],
        "seed": 0,
        "world_size": 8,
        "data_manifest_sha256": data["canonical_manifest_sha256"],
        "config_fingerprint": official["checkpoint_config_sha256"],
    }
    for key, value in runtime_expected.items():
        if runtime.get(key) != value:
            raise ValueError(f"resolved runtime mismatch: {evidence_id}/{key}")
    target = load_resolved_config(JOURNAL_ROOT / record["target_config"])
    legacy_semantics = normalized_training_semantics(resolved)
    target_semantics = normalized_training_semantics(target)
    if legacy_semantics != target_semantics:
        raise ValueError(f"legacy/current config semantics differ: {evidence_id}")
    semantic_sha = stable_sha256(legacy_semantics)
    if semantic_sha != record["semantic_projection_sha256"]:
        raise ValueError(f"semantic projection hash mismatch: {evidence_id}")

    final_epochs = []
    for line_number, line in enumerate(
        (run_dir / "metrics.jsonl").read_text(encoding="utf-8").splitlines(), 1
    ):
        metric = json.loads(line)
        _assert_finite(metric, f"{evidence_id}.metrics[{line_number}]")
        if metric.get("kind") == "epoch" and metric.get("epoch") == 299:
            final_epochs.append(metric)
    if not any(
        item.get("epoch_complete")
        and item.get("training_complete")
        and item.get("global_step") == 187500
        for item in final_epochs
    ):
        raise ValueError(f"missing complete final epoch metric: {evidence_id}")

    if evidence_id == "legacy_learned_smooth_s3_seed0":
        model = resolved["model"]
        if (
            model.get("smooth_clip_trainable") is not True
            or model.get("smooth_clip_init") != 6.0
            or model.get("smooth_clip_beta") != 10.0
            or model.get("smooth_clip_per_channel") is not False
            or "raw_clip"
            not in resolved["optimizer"].get("no_weight_decay_patterns", [])
        ):
            raise ValueError("historical smooth controller semantics drifted")


def read_code_manifest() -> dict[str, Any]:
    path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH
    manifest = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(manifest.get("code_sha256"), str):
        raise ValueError("invalid code manifest")
    return manifest


def verify_code_manifest() -> str:
    if str(JOURNAL_ROOT) not in sys.path:
        sys.path.insert(0, str(JOURNAL_ROOT))
    from scripts.code_fingerprint import build_manifest

    expected = read_code_manifest()
    actual = build_manifest(JOURNAL_ROOT)
    if actual != expected:
        raise ValueError(
            "code manifest mismatch: "
            f"expected {expected.get('code_sha256')}, "
            f"computed {actual.get('code_sha256')}"
        )
    return str(expected["code_sha256"])


def trigger_is_met(protocol: dict[str, Any], task: FollowupTask) -> bool:
    if task.trigger is None:
        return True
    trigger = task.trigger
    evidence = protocol["legacy_evidence"][trigger["evidence"]]
    observed = float(evidence["official"][trigger["metric"]])
    if not math.isclose(
        observed, float(trigger["observed"]), rel_tol=0.0, abs_tol=1e-9
    ):
        raise ValueError(f"conditional trigger observation drifted: {task.task_id}")
    if trigger["operator"] != "less_than":
        raise ValueError(f"unsupported trigger operator: {task.task_id}")
    met = observed < float(trigger["threshold"])
    if (trigger.get("state") == "met") != met:
        raise ValueError(f"conditional trigger state drifted: {task.task_id}")
    return met


def approval_payload(
    protocol: dict[str, Any],
    task: FollowupTask,
    *,
    conditional: bool = False,
) -> dict[str, Any]:
    return {
        "schema_version": 1,
        "protocol_id": protocol["protocol_id"],
        "task_id": task.task_id,
        "status": "approved",
        "approval_basis": (
            "manual_conditional_trigger_acknowledgement"
            if conditional
            else "registered_ready_task"
        ),
        "approved_at_utc": (
            datetime.now(timezone.utc).isoformat()
            if conditional
            else protocol["registered_at_utc"]
        ),
        "config_path": task.config_path,
        "output_dir": str(task.output_dir),
        "code_sha256": read_code_manifest()["code_sha256"],
    }


def verify_approval(
    protocol: dict[str, Any], task: FollowupTask, code_sha256: str
) -> None:
    if not task.approval_path.is_file():
        raise ApprovalError(
            f"Follow-up guard denied {task.task_id}: missing " f"{task.approval_path}"
        )
    marker = json.loads(task.approval_path.read_text(encoding="utf-8"))
    required = {
        "schema_version": 1,
        "protocol_id": protocol["protocol_id"],
        "task_id": task.task_id,
        "status": "approved",
        "config_path": task.config_path,
        "output_dir": str(task.output_dir),
        "code_sha256": code_sha256,
    }
    for key, expected in required.items():
        if marker.get(key) != expected:
            raise ApprovalError(
                f"Follow-up guard denied {task.task_id}: marker field {key} drifted"
            )
    expected_basis = (
        "registered_ready_task"
        if task.status == "ready"
        else "manual_conditional_trigger_acknowledgement"
    )
    if marker.get("approval_basis") != expected_basis:
        raise ApprovalError(
            f"Follow-up guard denied {task.task_id}: approval basis drifted"
        )
    if task.status == "conditional" and not trigger_is_met(protocol, task):
        raise ApprovalError(
            f"Follow-up guard denied {task.task_id}: trigger is not met"
        )


def verify_task(task_id: str, require_approval: bool) -> None:
    protocol = load_protocol()
    tasks = build_tasks(protocol)
    try:
        task = next(task for task in tasks if task.task_id == task_id)
    except StopIteration as error:
        raise ValueError(f"unknown follow-up task: {task_id}") from error
    code_sha256 = verify_code_manifest()
    for evidence_id in task.evidence:
        verify_evidence(protocol, evidence_id)
    if require_approval:
        verify_approval(protocol, task, code_sha256)
    print(
        f"Verified follow-up task {task.task_id}: code={code_sha256}, "
        f"evidence={','.join(task.evidence)}"
    )


def load_base_invariants() -> dict[str, Any]:
    source = load_yaml(BASE_TEMPLATE)
    required = (*RESOURCE_KEYS, *PROJECT_KEYS)
    missing = [key for key in required if key not in source]
    if missing:
        raise ValueError(f"base launch template missing: {', '.join(missing)}")
    return {key: copy.deepcopy(source[key]) for key in required}


def build_launch_document(
    protocol: dict[str, Any],
    task: FollowupTask,
    invariants: dict[str, Any],
) -> dict[str, Any]:
    verify = (
        "/tmp/gmnet_venv/bin/python "
        "scripts/generate_single_seed_followup.py "
        f"--verify-task {task.task_id} --require-approval"
    )
    pre_run = (
        f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && "
        "INSTALL_DEV=0 bash ./scripts/setup_env.sh && "
        f"{verify} && KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full"
    )
    assignments = " ".join(
        (
            f"RUN_NAME={task.task_id}",
            f"CONFIG_PATH={task.config_path}",
            f"DATA_ROOT={protocol['data']['runtime_root']}",
            f"OUTPUT_DIR={task.output_dir}",
            f"SEED={task.seed}",
            "NPROC_PER_NODE=8",
            "RESUME=auto",
            "POST_EVAL=1",
            f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
        )
    )
    command = (
        f"cd {JOURNAL_ROOT} && {verify} && {assignments} "
        "bash scripts/run_single_seed_followup.sh"
    )
    document: dict[str, Any] = {
        key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS
    }
    document["script"] = {
        "pre_run_event": pre_run,
        "command": command,
        "jobs": [{"name": task.job_name}],
    }
    document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS})
    return document


def dump_yaml(value: Any) -> str:
    return GENERATED_HEADER + yaml.safe_dump(
        value,
        sort_keys=False,
        default_flow_style=False,
        width=1_000_000,
    )


def build_batch_manifest(
    protocol: dict[str, Any], tasks: list[FollowupTask]
) -> dict[str, Any]:
    records = []
    for task in tasks:
        record = asdict(task)
        record["evidence"] = list(task.evidence)
        record["deploy_path"] = str(task.deploy_path)
        record["approval_path"] = str(task.approval_path)
        record["output_dir"] = str(task.output_dir)
        record["job_name"] = task.job_name
        record["eta_class"] = ">12h"
        records.append(record)
    return {
        "schema_version": 1,
        "protocol_id": protocol["protocol_id"],
        "protocol_source": str(PROTOCOL_PATH),
        "generated_by": str(SCRIPT_PATH),
        "source_template": str(BASE_TEMPLATE),
        "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH),
        "code_sha256": read_code_manifest()["code_sha256"],
        "relationship_to_parent": protocol["relationship_to_parent"],
        "post_hoc_registration": copy.deepcopy(protocol["post_hoc_registration"]),
        "policy": copy.deepcopy(protocol["policy"]),
        "data": copy.deepcopy(protocol["data"]),
        "run_root": str(RUN_ROOT),
        "summary": {
            "task_count": len(tasks),
            "initially_approved_count": sum(task.submission_allowed for task in tasks),
            "conditional_count": sum(task.status == "conditional" for task in tasks),
        },
        "tasks": records,
    }


def expected_files() -> dict[Path, str]:
    protocol = load_protocol()
    tasks = build_tasks(protocol)
    invariants = load_base_invariants()
    files = {
        task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants))
        for task in tasks
    }
    files[BATCH_ROOT / "batch_manifest.yaml"] = dump_yaml(
        build_batch_manifest(protocol, tasks)
    )
    for task in tasks:
        if task.submission_allowed:
            payload = approval_payload(protocol, task)
            files[task.approval_path] = (
                json.dumps(payload, indent=2, sort_keys=True) + "\n"
            )
    return files


def write_files(files: dict[Path, str]) -> None:
    for path, content in files.items():
        path.parent.mkdir(parents=True, exist_ok=True)
        if path.is_file() and path.read_text(encoding="utf-8") == content:
            continue
        path.write_text(content, encoding="utf-8")
    expected = set(files)
    for path in BATCH_ROOT.glob("*.yaml"):
        if path in expected:
            continue
        if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
            path.unlink()


def check_files(files: dict[Path, str]) -> list[str]:
    errors = []
    for path, expected in files.items():
        if not path.is_file():
            errors.append(f"missing: {path}")
        elif path.read_text(encoding="utf-8") != expected:
            errors.append(f"stale: {path}")
    for path in BATCH_ROOT.glob("*.yaml"):
        if path in files:
            continue
        if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
            errors.append(f"stale generated file: {path}")
    return errors


def approve_conditional(task_id: str, acknowledged: bool) -> None:
    if not acknowledged:
        raise ApprovalError("conditional approval requires --acknowledge-conditional")
    protocol = load_protocol()
    tasks = build_tasks(protocol)
    task = next((item for item in tasks if item.task_id == task_id), None)
    if task is None or task.status != "conditional":
        raise ApprovalError(f"task is not conditional: {task_id}")
    verify_code_manifest()
    for evidence_id in task.evidence:
        verify_evidence(protocol, evidence_id)
    if not trigger_is_met(protocol, task):
        raise ApprovalError(f"conditional trigger is not met: {task_id}")
    task.approval_path.parent.mkdir(parents=True, exist_ok=True)
    task.approval_path.write_text(
        json.dumps(
            approval_payload(protocol, task, conditional=True),
            indent=2,
            sort_keys=True,
        )
        + "\n",
        encoding="utf-8",
    )
    print(f"Approved conditional follow-up task: {task_id}")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    action = parser.add_mutually_exclusive_group()
    action.add_argument("--check", action="store_true")
    action.add_argument("--verify-task")
    action.add_argument("--approve-conditional")
    parser.add_argument("--require-approval", action="store_true")
    parser.add_argument("--acknowledge-conditional", action="store_true")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    try:
        if args.verify_task:
            verify_task(args.verify_task, args.require_approval)
            return 0
        if args.approve_conditional:
            approve_conditional(args.approve_conditional, args.acknowledge_conditional)
            return 0
        protocol = load_protocol()
        tasks = build_tasks(protocol)
        verify_code_manifest()
        for evidence_id in protocol["legacy_evidence"]:
            verify_evidence(protocol, evidence_id)
        files = expected_files()
        if args.check:
            errors = check_files(files)
            if errors:
                print("\n".join(errors), file=sys.stderr)
                return 1
            print(
                f"Validated {len(tasks)} follow-up launch YAMLs, "
                "batch manifest, approvals, code, and legacy evidence"
            )
            return 0
        write_files(files)
        print(
            f"Generated {len(tasks)} follow-up launch YAMLs under {BATCH_ROOT}; "
            "no launchjob was submitted"
        )
        return 0
    except ApprovalError as error:
        print(str(error), file=sys.stderr)
        return 64


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