doctrine 0.4.9

Project tooling CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
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
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
// SPDX-License-Identifier: GPL-3.0-only
//! SL-068 PHASE-02 — `doctrine dispatch candidate create` (core happy path)
//! end-to-end over the BUILT binary (design §5.3; EX-1..5 / VT-1..4).
//!
//! The fixture reuses the SL-064 `dispatch sync --prepare-review` projection to
//! mint REAL `review/<slice>` + `phase/<slice>-NN` refs AND a verified journal on
//! `dispatch/<slice>` — the genuine provenance substrate create gates on (EX-1).
//!
//! * VT-1: a clean 3-way create from `review/064` and from a `phase/064-NN`
//!   records source/base/merge OIDs (merge_oid has the two expected parents) and
//!   shows NO phantom `.doctrine` deletions vs live trunk (the SL-067 defect fix).
//! * VT-2: create refuses before/without a verified prepare-review row.
//! * VT-3: an existing target ref refuses (zero-oid CAS); a supersede creates a
//!   fresh row + ref linked by `supersedes`.
//! * VT-4 / EX-4: `review/*` and `phase/*` OIDs are unchanged after a create
//!   (invariant I1); a payload fixture proves review_surface vs close_target differ.

#![allow(
    clippy::expect_used,
    clippy::unwrap_used,
    clippy::tests_outside_test_module,
    reason = "integration test: fail-fast unwrap/expect are idiomatic, and test fns live at crate root by construction"
)]

use std::path::Path;
use std::process::{Command, Output};

const BIN: &str = env!("CARGO_BIN_EXE_doctrine");

fn git(dir: &Path, args: &[&str]) -> String {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .expect("spawn git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}

fn commit(dir: &Path, path: &str, content: &str, msg: &str) -> String {
    let full = dir.join(path);
    std::fs::create_dir_all(full.parent().unwrap()).unwrap();
    std::fs::write(&full, content).unwrap();
    git(dir, &["add", path]);
    git(dir, &["commit", "-q", "-m", msg]);
    git(dir, &["rev-parse", "HEAD"])
}

/// The built fixture's captured OIDs.
struct Fixture {
    base: String,
}

/// Build a repo with `main` at a trunk base and a `dispatch/064` branch carrying
/// two code phases, an authored `.doctrine/` entity, and the
/// `boundaries.toml` ledger. Leaves the working tree on `main`.
fn build_fixture(dir: &Path) -> Fixture {
    std::fs::create_dir_all(dir).unwrap();
    git(dir, &["init", "-q", "-b", "main"]);
    git(dir, &["config", "user.email", "t@example.com"]);
    git(dir, &["config", "user.name", "Test"]);
    let base = commit(dir, "trunk.txt", "trunk", "base");

    git(dir, &["checkout", "-q", "-b", "dispatch/064"]);
    let code_end_1 = commit(dir, "src1.txt", "a", "phase1 code");
    let code_end_2 = commit(dir, "src2.txt", "b", "phase2 code");
    commit(
        dir,
        ".doctrine/slice/064/slice-064.md",
        "scope",
        "authored entity",
    );

    let boundaries = format!(
        "[[boundary]]\nphase = \"PHASE-01\"\ncode_start_oid = \"{base}\"\ncode_end_oid = \"{code_end_1}\"\n\
         [[boundary]]\nphase = \"PHASE-02\"\ncode_start_oid = \"{code_end_1}\"\ncode_end_oid = \"{code_end_2}\"\n"
    );
    std::fs::create_dir_all(dir.join(".doctrine/dispatch/064")).unwrap();
    std::fs::write(
        dir.join(".doctrine/dispatch/064/boundaries.toml"),
        &boundaries,
    )
    .unwrap();
    git(dir, &["add", ".doctrine/dispatch/064"]);
    git(dir, &["commit", "-q", "-m", "ledger fixtures"]);

    git(dir, &["checkout", "-q", "main"]);
    Fixture { base }
}

fn run(cwd: &Path, worker: Option<bool>, args: &[&str]) -> Output {
    let mut cmd = Command::new(BIN);
    cmd.args(args).current_dir(cwd);
    match worker {
        Some(true) => {
            cmd.env("DOCTRINE_WORKER", "1");
        }
        Some(false) | None => {
            cmd.env_remove("DOCTRINE_WORKER");
        }
    }
    cmd.output().expect("spawn doctrine")
}

fn stderr(out: &Output) -> String {
    String::from_utf8_lossy(&out.stderr).into_owned()
}

fn ref_exists(dir: &Path, refname: &str) -> bool {
    Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["rev-parse", "--verify", "--quiet", refname])
        .output()
        .expect("spawn git")
        .status
        .success()
}

/// Run stage-1 prepare-review so the fixture carries verified provenance.
fn prepare_review(dir: &Path) {
    let out = run(
        dir,
        None,
        &[
            "dispatch",
            "sync",
            "--prepare-review",
            "--slice",
            "64",
            "-p",
            dir.to_str().unwrap(),
        ],
    );
    assert!(
        out.status.success(),
        "prepare-review ok; stderr: {}",
        stderr(&out)
    );
}

/// Run `dispatch candidate create` with the given extra flags.
fn create(cwd: &Path, worker: Option<bool>, extra: &[&str]) -> Output {
    let mut args = vec!["dispatch", "candidate", "create", "--slice", "64"];
    args.extend_from_slice(extra);
    args.push("-p");
    args.push(cwd.to_str().unwrap());
    run(cwd, worker, &args)
}

fn read_candidates(dir: &Path) -> String {
    std::fs::read_to_string(dir.join(".doctrine/dispatch/064/candidates.toml"))
        .expect("candidates.toml written")
}

fn stdout(out: &Output) -> String {
    String::from_utf8_lossy(&out.stdout).into_owned()
}

/// Run `dispatch candidate status --slice 64` over the built binary.
fn status(cwd: &Path, worker: Option<bool>) -> Output {
    run(
        cwd,
        worker,
        &[
            "dispatch",
            "candidate",
            "status",
            "--slice",
            "64",
            "-p",
            cwd.to_str().unwrap(),
        ],
    )
}

/// The parents of a commit, in order.
fn parents(dir: &Path, commitish: &str) -> Vec<String> {
    git(dir, &["rev-list", "--parents", "-n", "1", commitish])
        .split_whitespace()
        .skip(1)
        .map(str::to_owned)
        .collect()
}

/// Run `dispatch candidate admit --slice 64` with the given extra flags.
fn admit(cwd: &Path, worker: Option<bool>, extra: &[&str]) -> Output {
    let mut args = vec!["dispatch", "candidate", "admit", "--slice", "64"];
    args.extend_from_slice(extra);
    args.push("-p");
    args.push(cwd.to_str().unwrap());
    run(cwd, worker, &args)
}

/// Run `dispatch sync --integrate --slice 64` with the given extra flags
/// (DOCTRINE_WORKER unset). Mirrors e2e_dispatch_sync.rs's `integrate` helper.
fn integrate(cwd: &Path, extra: &[&str]) -> Output {
    let mut args = vec![
        "dispatch",
        "sync",
        "--integrate",
        "--slice",
        "64",
        "-p",
        cwd.to_str().unwrap(),
    ];
    args.extend_from_slice(extra);
    run(cwd, None, &args)
}

/// Create + return the candidate close_target built from `phase/064-02`.
fn create_close_target(dir: &Path, label: &str) {
    assert!(
        create(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--payload",
                "code",
                "--base",
                "refs/heads/main",
                "--label",
                label,
                "--source",
                "refs/heads/phase/064-02",
            ],
        )
        .status
        .success(),
        "create close_target {label}"
    );
}

// --- VT-1: clean 3-way from review/<slice> -----------------------------------

#[test]
fn e2e_dispatch_candidate_clean_merge_from_review() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    let fx = build_fixture(dir);
    prepare_review(dir);

    let base_oid = git(dir, &["rev-parse", "main"]);
    let source_oid = git(dir, &["rev-parse", "review/064"]);

    let out = create(
        dir,
        None,
        &[
            "--role",
            "review_surface",
            "--payload",
            "impl_bundle",
            "--base",
            "refs/heads/main",
            "--label",
            "review-001",
            "--worktree",
        ],
    );
    assert!(
        out.status.success(),
        "clean create ok; stderr: {}",
        stderr(&out)
    );
    assert!(
        ref_exists(dir, "candidate/064/review-001"),
        "branch created"
    );

    // merge_oid has BOTH base and source as parents (a true no-ff 3-way).
    let merge_oid = git(dir, &["rev-parse", "candidate/064/review-001"]);
    let ps = parents(dir, &merge_oid);
    assert_eq!(ps.len(), 2, "no-ff merge has two parents: {ps:?}");
    assert!(ps.contains(&base_oid), "base is a parent: {ps:?}");
    assert!(ps.contains(&source_oid), "source is a parent: {ps:?}");

    // The recorded row carries the OIDs.
    let toml = read_candidates(dir);
    assert!(toml.contains("status = \"created\""), "{toml}");
    assert!(toml.contains(&source_oid), "source_oid recorded: {toml}");
    assert!(toml.contains(&base_oid), "base_oid recorded: {toml}");
    assert!(toml.contains(&merge_oid), "merge_oid recorded: {toml}");

    // EX-3: a clean trunk-advanced case shows NO phantom .doctrine deletions vs
    // live trunk — the 3-way union carries the base's .doctrine corpus AND the
    // source's code. (The base here IS live trunk; the deletion-free property is
    // what the SL-067 squash defect violated.)
    let diff = git(dir, &["diff", "--name-status", "main", &merge_oid]);
    assert!(
        !diff.lines().any(|l| l.starts_with('D')),
        "no phantom deletions vs live trunk: {diff}"
    );
    // The candidate carries both the .doctrine entity and the source code.
    let listing = git(dir, &["ls-tree", "-r", "--name-only", &merge_oid]);
    assert!(
        listing.contains(".doctrine/slice/064/slice-064.md"),
        ".doctrine corpus carried: {listing}"
    );
    assert!(
        listing.contains("src1.txt"),
        "source code carried: {listing}"
    );
    let _ = &fx.base;
}

// --- VT-1: clean 3-way from a phase chain ------------------------------------

#[test]
fn e2e_dispatch_candidate_clean_merge_from_phase_chain() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    let base_oid = git(dir, &["rev-parse", "main"]);
    let source_oid = git(dir, &["rev-parse", "phase/064-02"]);

    let out = create(
        dir,
        None,
        &[
            "--role",
            "close_target",
            "--payload",
            "code",
            "--base",
            "refs/heads/main",
            "--label",
            "close-001",
            "--source",
            "refs/heads/phase/064-02",
        ],
    );
    assert!(
        out.status.success(),
        "phase-chain create ok; stderr: {}",
        stderr(&out)
    );

    let merge_oid = git(dir, &["rev-parse", "candidate/064/close-001"]);
    let ps = parents(dir, &merge_oid);
    assert_eq!(ps.len(), 2, "no-ff merge has two parents: {ps:?}");
    assert!(ps.contains(&base_oid) && ps.contains(&source_oid), "{ps:?}");

    let diff = git(dir, &["diff", "--name-status", "main", &merge_oid]);
    assert!(
        !diff.lines().any(|l| l.starts_with('D')),
        "no phantom deletions vs live trunk: {diff}"
    );
}

// --- VT-2: unverified / absent provenance refuses ----------------------------

#[test]
fn e2e_dispatch_candidate_unverified_source_refuses() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    // NOTE: prepare-review NOT run ⇒ no verified journal row for review/064.

    let out = create(
        dir,
        None,
        &[
            "--role",
            "review_surface",
            "--payload",
            "impl_bundle",
            "--base",
            "refs/heads/main",
            "--label",
            "review-001",
            "--worktree",
        ],
    );
    assert!(
        !out.status.success(),
        "refused without a verified prepare-review row"
    );
    assert!(
        stderr(&out).contains("prepare-review") || stderr(&out).contains("verified"),
        "refusal names the provenance gate: {}",
        stderr(&out)
    );
    assert!(
        !ref_exists(dir, "candidate/064/review-001"),
        "refused run creates no candidate ref"
    );
    assert!(
        !dir.join(".doctrine/dispatch/064/candidates.toml").exists(),
        "refused run records no row"
    );
}

// --- VT-3: zero-oid CAS refuses an existing ref; supersede creates a fresh one -

#[test]
fn e2e_dispatch_candidate_create_zero_oid_cas_refuses_existing() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    let mk = |label: &str, supersedes: Option<&str>| -> Output {
        let mut extra = vec![
            "--role",
            "review_surface",
            "--payload",
            "impl_bundle",
            "--base",
            "refs/heads/main",
            "--label",
            label,
            "--worktree",
        ];
        if let Some(s) = supersedes {
            extra.push("--supersedes");
            extra.push(s);
        }
        create(dir, None, &extra)
    };

    assert!(mk("review-001", None).status.success(), "first create");
    let first_oid = git(dir, &["rev-parse", "candidate/064/review-001"]);

    // Re-creating the SAME label refuses under zero-oid CAS, leaving the ref.
    let dup = mk("review-001", None);
    assert!(!dup.status.success(), "existing target ref refuses");
    assert!(
        stderr(&dup).contains("already exists"),
        "refusal names the CAS cause: {}",
        stderr(&dup)
    );
    assert_eq!(
        git(dir, &["rev-parse", "candidate/064/review-001"]),
        first_oid,
        "the existing branch is left untouched"
    );

    // A supersede creates a FRESH row + ref linked by `supersedes`.
    let sup = mk("review-002", Some("cand-064-review-001"));
    assert!(
        sup.status.success(),
        "supersede create ok; stderr: {}",
        stderr(&sup)
    );
    assert!(ref_exists(dir, "candidate/064/review-002"), "fresh ref");
    let toml = read_candidates(dir);
    assert!(
        toml.contains("supersedes = \"cand-064-review-001\""),
        "fresh row links the prior id: {toml}"
    );
    // The old branch is NEVER rewritten.
    assert_eq!(
        git(dir, &["rev-parse", "candidate/064/review-001"]),
        first_oid,
        "supersession never rewrites the old branch"
    );
}

// --- VT-4 / EX-4: evidence refs unchanged; payload axes differ ----------------

#[test]
fn e2e_dispatch_candidate_create_leaves_evidence_refs_and_distinguishes_payload() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    let review_before = git(dir, &["rev-parse", "review/064"]);
    let phase1_before = git(dir, &["rev-parse", "phase/064-01"]);
    let phase2_before = git(dir, &["rev-parse", "phase/064-02"]);

    // review_surface (impl_bundle) candidate.
    assert!(
        create(
            dir,
            None,
            &[
                "--role",
                "review_surface",
                "--payload",
                "impl_bundle",
                "--base",
                "refs/heads/main",
                "--label",
                "review-001",
                "--worktree",
            ],
        )
        .status
        .success()
    );
    // close_target (code) candidate.
    assert!(
        create(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--payload",
                "code",
                "--base",
                "refs/heads/main",
                "--label",
                "close-001",
                "--source",
                "refs/heads/phase/064-02",
            ],
        )
        .status
        .success()
    );

    // I1: review/* and phase/* OIDs are unchanged after create.
    assert_eq!(git(dir, &["rev-parse", "review/064"]), review_before);
    assert_eq!(git(dir, &["rev-parse", "phase/064-01"]), phase1_before);
    assert_eq!(git(dir, &["rev-parse", "phase/064-02"]), phase2_before);

    // The two candidates differ on payload + role + source — a proof the axes
    // are recorded distinctly, and the bundle vs code payloads diverge in content.
    let toml = read_candidates(dir);
    assert!(toml.contains("payload = \"impl_bundle\""), "{toml}");
    assert!(toml.contains("payload = \"code\""), "{toml}");
    assert!(toml.contains("role = \"review_surface\""), "{toml}");
    assert!(toml.contains("role = \"close_target\""), "{toml}");

    let review_listing = git(
        dir,
        &["ls-tree", "-r", "--name-only", "candidate/064/review-001"],
    );
    let close_listing = git(
        dir,
        &["ls-tree", "-r", "--name-only", "candidate/064/close-001"],
    );
    assert!(
        review_listing.contains(".doctrine/slice/064/slice-064.md"),
        "impl_bundle candidate carries the .doctrine corpus: {review_listing}"
    );
    assert!(
        !close_listing.contains(".doctrine/slice/064/slice-064.md")
            || review_listing != close_listing,
        "code close_target differs from the impl_bundle review surface: \
         review={review_listing} close={close_listing}"
    );
}

// --- PHASE-03 fixtures: a genuinely 3-way-conflicting source/base ------------

/// Like [`build_fixture`] but engineer a real 3-way conflict: the dispatch
/// branch and `main` both modify the SAME merge-base file (`trunk.txt`) to
/// DIFFERENT values, so `merge-tree` of `review/064` onto `main` conflicts.
/// (The merge base is the original `base` commit; both sides diverge on it.)
fn build_conflict_fixture(dir: &Path) -> Fixture {
    std::fs::create_dir_all(dir).unwrap();
    git(dir, &["init", "-q", "-b", "main"]);
    git(dir, &["config", "user.email", "t@example.com"]);
    git(dir, &["config", "user.name", "Test"]);
    let base = commit(dir, "trunk.txt", "trunk\n", "base");

    git(dir, &["checkout", "-q", "-b", "dispatch/064"]);
    // Dispatch side rewrites trunk.txt to one value.
    let code_end_1 = commit(
        dir,
        "trunk.txt",
        "DISPATCH SIDE\n",
        "phase1 conflicting edit",
    );
    let code_end_2 = commit(dir, "src2.txt", "b", "phase2 code");
    commit(
        dir,
        ".doctrine/slice/064/slice-064.md",
        "scope",
        "authored entity",
    );

    let boundaries = format!(
        "[[boundary]]\nphase = \"PHASE-01\"\ncode_start_oid = \"{base}\"\ncode_end_oid = \"{code_end_1}\"\n\
         [[boundary]]\nphase = \"PHASE-02\"\ncode_start_oid = \"{code_end_1}\"\ncode_end_oid = \"{code_end_2}\"\n"
    );
    std::fs::create_dir_all(dir.join(".doctrine/dispatch/064")).unwrap();
    std::fs::write(
        dir.join(".doctrine/dispatch/064/boundaries.toml"),
        &boundaries,
    )
    .unwrap();
    git(dir, &["add", ".doctrine/dispatch/064"]);
    git(dir, &["commit", "-q", "-m", "ledger fixtures"]);

    git(dir, &["checkout", "-q", "main"]);
    // Main side rewrites trunk.txt to a DIFFERENT value ⇒ conflicts with review/064.
    commit(dir, "trunk.txt", "MAIN SIDE\n", "main conflicting edit");
    Fixture { base }
}

// --- VT-1: conflict lifecycle — abort without --worktree, record with it ------

#[test]
fn e2e_dispatch_candidate_conflict_records_or_aborts() {
    // No --worktree ⇒ conflict aborts cleanly: no row, no ref, no worktree.
    {
        let repo = tempfile::tempdir().unwrap();
        let dir = repo.path();
        build_conflict_fixture(dir);
        prepare_review(dir);

        let out = create(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--payload",
                "code",
                "--base",
                "refs/heads/main",
                "--label",
                "conflict-001",
                "--source",
                "refs/heads/review/064",
            ],
        );
        assert!(
            !out.status.success(),
            "conflict without --worktree aborts; stderr: {}",
            stderr(&out)
        );
        assert!(
            stderr(&out).contains("conflict"),
            "refusal names the conflict: {}",
            stderr(&out)
        );
        assert!(
            !ref_exists(dir, "candidate/064/conflict-001"),
            "aborted conflict creates no candidate ref"
        );
        assert!(
            !dir.join(".doctrine/dispatch/064/candidates.toml").exists(),
            "aborted conflict records no row"
        );
        assert!(
            !dir.join(".doctrine/state/dispatch/candidate").exists(),
            "aborted conflict leaves no worktree dir"
        );
    }

    // With --worktree ⇒ row status=conflicted, branch at base, worktree created.
    {
        let repo = tempfile::tempdir().unwrap();
        let dir = repo.path();
        build_conflict_fixture(dir);
        prepare_review(dir);
        let base_oid = git(dir, &["rev-parse", "main"]);

        let out = create(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--payload",
                "code",
                "--base",
                "refs/heads/main",
                "--label",
                "conflict-001",
                "--source",
                "refs/heads/review/064",
                "--worktree",
            ],
        );
        assert!(
            out.status.success(),
            "conflict with --worktree records the conflicted lifecycle; stderr: {}",
            stderr(&out)
        );
        assert!(
            ref_exists(dir, "candidate/064/conflict-001"),
            "conflicted candidate branch created so the user can resolve"
        );
        // The branch is parked at the base (the merge attempt) for resolution.
        assert_eq!(
            git(dir, &["rev-parse", "candidate/064/conflict-001"]),
            base_oid,
            "conflicted branch parked at base for resolve+commit"
        );
        let toml = read_candidates(dir);
        assert!(
            toml.contains("status = \"conflicted\""),
            "row recorded conflicted: {toml}"
        );
        // The worktree path is displayed AND created.
        let wt = dir.join(".doctrine/state/dispatch/candidate/cand-064-conflict-001");
        assert!(wt.exists(), "conflicted candidate worktree created: {wt:?}");
        assert!(
            String::from_utf8_lossy(&out.stdout).contains("cand-064-conflict-001")
                || stderr(&out).contains("cand-064-conflict-001"),
            "worktree path displayed; stdout={} stderr={}",
            String::from_utf8_lossy(&out.stdout),
            stderr(&out)
        );
    }
}

// --- VT-2: review_surface requires --worktree --------------------------------

#[test]
fn e2e_dispatch_candidate_review_surface_requires_worktree() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    let out = create(
        dir,
        None,
        &[
            "--role",
            "review_surface",
            "--payload",
            "impl_bundle",
            "--base",
            "refs/heads/main",
            "--label",
            "review-001",
        ],
    );
    assert!(
        !out.status.success(),
        "review_surface without --worktree refuses"
    );
    assert!(
        stderr(&out).contains("--worktree"),
        "refusal names the missing flag: {}",
        stderr(&out)
    );
    assert!(
        !ref_exists(dir, "candidate/064/review-001"),
        "refused review_surface creates no candidate ref"
    );
    assert!(
        !dir.join(".doctrine/dispatch/064/candidates.toml").exists(),
        "refused review_surface records no row"
    );
}

// --- VT-2: Orchestrator-classed (worker-mode refusal) ------------------------

#[test]
fn dispatch_candidate_is_orchestrator_classed() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    // DOCTRINE_WORKER set ONLY on this subprocess (via create's worker arg).
    let out = create(
        dir,
        Some(true),
        &[
            "--role",
            "close_target",
            "--payload",
            "code",
            "--base",
            "refs/heads/main",
            "--label",
            "close-001",
            "--source",
            "refs/heads/phase/064-02",
        ],
    );
    assert!(!out.status.success(), "refused when DOCTRINE_WORKER set");
    assert!(
        stderr(&out).contains("DOCTRINE_WORKER"),
        "carries the dual-cause token: {}",
        stderr(&out)
    );
    assert!(
        !ref_exists(dir, "candidate/064/close-001"),
        "refused run creates no candidate ref"
    );
    assert!(
        !dir.join(".doctrine/dispatch/064/candidates.toml").exists(),
        "refused run records no row"
    );
}

// --- VT-2: create refuses on a raw evidence ref (invariant I9) ----------------

#[test]
fn e2e_dispatch_raw_evidence_worktree_write_refuses() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    // Check the current worktree out onto a raw evidence ref (review/064).
    git(dir, &["checkout", "-q", "review/064"]);

    let out = create(
        dir,
        None,
        &[
            "--role",
            "close_target",
            "--payload",
            "code",
            "--base",
            "refs/heads/main",
            "--label",
            "close-001",
            "--source",
            "refs/heads/phase/064-02",
        ],
    );
    assert!(
        !out.status.success(),
        "create refuses from a worktree on a raw evidence ref"
    );
    assert!(
        stderr(&out).contains("review/064") || stderr(&out).contains("evidence"),
        "refusal names the raw evidence ref: {}",
        stderr(&out)
    );
    assert!(
        stderr(&out).contains("candidate"),
        "refusal points at the candidate workflow: {}",
        stderr(&out)
    );
    assert!(
        !ref_exists(dir, "candidate/064/close-001"),
        "refused-on-evidence-ref run creates no candidate ref"
    );
    assert!(
        !dir.join(".doctrine/dispatch/064/candidates.toml").exists(),
        "refused-on-evidence-ref run records no row"
    );

    // A phase/* ref refuses the same way.
    git(dir, &["checkout", "-q", "phase/064-01"]);
    let out2 = create(
        dir,
        None,
        &[
            "--role",
            "close_target",
            "--payload",
            "code",
            "--base",
            "refs/heads/main",
            "--label",
            "close-002",
            "--source",
            "refs/heads/phase/064-02",
        ],
    );
    assert!(
        !out2.status.success(),
        "create refuses from a worktree on a raw phase ref"
    );
    assert!(
        stderr(&out2).contains("phase/064-01") || stderr(&out2).contains("evidence"),
        "refusal names the raw phase ref: {}",
        stderr(&out2)
    );
}

// --- EX-5: Orchestrator-classed — refused under worker-mode -------------------

#[test]
fn e2e_dispatch_candidate_create_refused_under_worker_mode() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    let out = create(
        dir,
        Some(true),
        &[
            "--role",
            "review_surface",
            "--payload",
            "impl_bundle",
            "--base",
            "refs/heads/main",
            "--label",
            "review-001",
        ],
    );
    assert!(!out.status.success(), "refused when DOCTRINE_WORKER set");
    assert!(
        stderr(&out).contains("DOCTRINE_WORKER"),
        "carries the dual-cause token: {}",
        stderr(&out)
    );
    assert!(
        !ref_exists(dir, "candidate/064/review-001"),
        "refused run creates no candidate ref"
    );
}

// =============================================================================
// SL-068 PHASE-04 — `dispatch candidate status` (read-only surface; EX-1..3)
// =============================================================================

/// Splice an admission into `candidates.toml` for `id` at `admitted_oid` (admit
/// is PHASE-05 — the fixture writes the record directly, per VT-1's note). Appends
/// a `[current_admission.close_target]` table to the existing ledger file.
fn seed_close_target_admission(
    dir: &Path,
    candidate_id: &str,
    candidate_ref: &str,
    admitted_oid: &str,
) {
    let path = dir.join(".doctrine/dispatch/064/candidates.toml");
    let mut body = std::fs::read_to_string(&path).expect("candidates.toml exists");
    body.push_str(&format!(
        "\n[current_admission.close_target]\n\
         candidate_id = \"{candidate_id}\"\n\
         candidate_ref = \"{candidate_ref}\"\n\
         expected_ref_oid = \"{admitted_oid}\"\n\
         admitted_oid = \"{admitted_oid}\"\n\
         review = \"RV-007\"\n\
         admitted_at = \"2026-06-15\"\n"
    ));
    std::fs::write(&path, body).unwrap();
}

// --- VT-1: grouped evidence vs candidate surface (created + admitted) ---------

#[test]
fn e2e_dispatch_candidate_status_groups_evidence_and_candidates() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    // A created review_surface candidate AND a close_target we then admit.
    assert!(
        create(
            dir,
            None,
            &[
                "--role",
                "review_surface",
                "--payload",
                "impl_bundle",
                "--base",
                "refs/heads/main",
                "--label",
                "review-001",
                "--worktree",
            ],
        )
        .status
        .success()
    );
    assert!(
        create(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--payload",
                "code",
                "--base",
                "refs/heads/main",
                "--label",
                "close-001",
                "--source",
                "refs/heads/phase/064-02",
            ],
        )
        .status
        .success()
    );
    let close_tip = git(dir, &["rev-parse", "candidate/064/close-001"]);
    seed_close_target_admission(
        dir,
        "cand-064-close-001",
        "refs/heads/candidate/064/close-001",
        &close_tip,
    );

    let out = status(dir, None);
    assert!(out.status.success(), "status ok; stderr: {}", stderr(&out));
    let text = stdout(&out);

    // EX-1: the two groups are VISIBLY separate, evidence never conflated with
    // an interaction branch.
    let ev = text.find("evidence refs:").expect("evidence group header");
    let cd = text
        .find("candidates (interaction branches):")
        .expect("candidate group header");
    assert!(
        ev < cd,
        "evidence group precedes the candidate group: {text}"
    );

    // The evidence group names the exact evidence refs (coordination / impl
    // bundle / phase cuts), each labelled — NOT a candidate/* ref.
    let evidence = &text[ev..cd];
    assert!(
        evidence.contains("refs/heads/dispatch/064") && evidence.contains("coordination"),
        "evidence names the coordination branch: {evidence}"
    );
    assert!(
        evidence.contains("refs/heads/review/064") && evidence.contains("impl-bundle"),
        "evidence names the impl bundle: {evidence}"
    );
    assert!(
        evidence.contains("refs/heads/phase/064-01")
            && evidence.contains("refs/heads/phase/064-02")
            && evidence.contains("phase-cut"),
        "evidence names the phase cuts: {evidence}"
    );
    assert!(
        !evidence.contains("candidate/064/"),
        "the evidence group never lists a candidate interaction branch: {evidence}"
    );

    // EX-2: the candidate group reports id/status/base/source/tip/admission for
    // BOTH a created and an admitted candidate.
    let candidates = &text[cd..];
    assert!(
        candidates.contains("cand-064-review-001") && candidates.contains("created"),
        "the created review candidate is reported: {candidates}"
    );
    assert!(
        candidates.contains("cand-064-close-001"),
        "the admitted close candidate is reported: {candidates}"
    );
    assert!(
        candidates.contains("admitted (RV-007)"),
        "the admitted candidate names its admitting review: {candidates}"
    );
    // base/source/tip oid cells are present (12-char abbrev of the real oids).
    let base = git(dir, &["rev-parse", "main"]);
    assert!(
        candidates.contains(&base[..12]),
        "the base oid is reported: {candidates}"
    );
}

// --- VT-2: ref drift is reported, admitted oid unchanged ----------------------

#[test]
fn e2e_dispatch_candidate_status_reports_drift_when_ref_moves_past_admitted_oid() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    assert!(
        create(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--payload",
                "code",
                "--base",
                "refs/heads/main",
                "--label",
                "close-001",
                "--source",
                "refs/heads/phase/064-02",
            ],
        )
        .status
        .success()
    );
    let admitted_oid = git(dir, &["rev-parse", "candidate/064/close-001"]);
    seed_close_target_admission(
        dir,
        "cand-064-close-001",
        "refs/heads/candidate/064/close-001",
        &admitted_oid,
    );

    // Before the move: no drift.
    let before = stdout(&status(dir, None));
    assert!(
        before.contains("ok") && !before.contains("DRIFT"),
        "no drift before the ref moves: {before}"
    );

    // Move the candidate ref PAST its recorded/admitted oid (a fresh commit on
    // top — a hand-edit the candidate workflow forbids, which status must surface).
    git(dir, &["checkout", "-q", "candidate/064/close-001"]);
    let moved = commit(dir, "drifted.txt", "drift", "manual edit past admitted oid");
    git(dir, &["checkout", "-q", "main"]);
    assert_ne!(moved, admitted_oid, "the ref genuinely moved");

    let after = stdout(&status(dir, None));
    // I4: drift is REPORTED, not hidden.
    assert!(
        after.contains("DRIFT"),
        "the moved candidate ref is reported as drift: {after}"
    );
    // The admitted oid in the ledger is UNCHANGED (status mutated nothing).
    let ledger = read_candidates(dir);
    assert!(
        ledger.contains(&admitted_oid),
        "the admitted oid is unchanged after status: {ledger}"
    );
    assert!(
        !ledger.contains(&moved),
        "the moved tip was NOT written into the ledger (read-only): {ledger}"
    );
}

// --- VA-1: names evidence vs interaction branch + points at the next action ---

#[test]
fn e2e_dispatch_candidate_status_names_evidence_interaction_and_next_action() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);
    assert!(
        create(
            dir,
            None,
            &[
                "--role",
                "review_surface",
                "--payload",
                "impl_bundle",
                "--base",
                "refs/heads/main",
                "--label",
                "review-001",
                "--worktree",
            ],
        )
        .status
        .success()
    );

    let text = stdout(&status(dir, None));
    // Names the exact evidence ref AS evidence and the candidate AS the
    // interaction branch (the two labels are not interchangeable).
    assert!(
        text.contains("evidence refs:") && text.contains("refs/heads/review/064"),
        "names the impl bundle as an evidence ref: {text}"
    );
    assert!(
        text.contains("candidates (interaction branches):")
            && text.contains("candidate/064/review-001"),
        "names the candidate as the interaction branch: {text}"
    );
    // EX-3: points at the next safe ACTION (a concrete verb), not "inspect refs".
    let next = text.split("next:").nth(1).expect("a next-action block");
    assert!(
        next.contains("dispatch candidate admit") || next.contains("dispatch candidate create"),
        "the next block names a safe verb: {next}"
    );
    assert!(
        !text.contains("git rev-parse") && !text.contains("git update-ref"),
        "status guides via verbs, not raw ref plumbing: {text}"
    );
}

// --- VA-1: empty ledger guides toward create ---------------------------------

#[test]
fn e2e_dispatch_candidate_status_empty_ledger_guides_to_create() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    let out = status(dir, None);
    assert!(out.status.success(), "status ok; stderr: {}", stderr(&out));
    let text = stdout(&out);
    assert!(
        text.contains("(none recorded)"),
        "an empty ledger reports no candidates: {text}"
    );
    assert!(
        text.contains("dispatch candidate create --slice 64"),
        "the next action is to create the first candidate: {text}"
    );
}

// --- EX-3: status is Read-classed — works UNDER worker-mode -------------------

#[test]
fn e2e_dispatch_candidate_status_runs_under_worker_mode() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    // DOCTRINE_WORKER set: create is refused, but the read-only status surface
    // must SUCCEED (Read-classed, EX-3).
    let out = status(dir, Some(true));
    assert!(
        out.status.success(),
        "status is read-only and runs under worker-mode; stderr: {}",
        stderr(&out)
    );
    assert!(
        stdout(&out).contains("evidence refs:"),
        "status renders its surface under worker-mode"
    );
}

// =============================================================================
// SL-068 PHASE-05 — `dispatch candidate admit` (OID binding + provenance; VT-1..4)
// =============================================================================

// --- VT-1: an unproven tip (not descending from merge_oid) refuses (I3) -------

#[test]
fn e2e_dispatch_candidate_admit_rejects_unproven_tip() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);
    create_close_target(dir, "close-001");

    let merge_oid = git(dir, &["rev-parse", "candidate/064/close-001"]);
    let main_oid = git(dir, &["rev-parse", "main"]);

    // Move the candidate ref to `main` — a tip that does NOT descend from the
    // recorded merge_oid (merge_oid is a child of main, so main is its ancestor,
    // not the other way around). Verify the ancestry genuinely fails first.
    let is_anc = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["merge-base", "--is-ancestor", &merge_oid, &main_oid])
        .output()
        .expect("spawn git")
        .status
        .success();
    assert!(
        !is_anc,
        "the moved tip (main) genuinely does NOT descend from merge_oid"
    );
    git(dir, &["checkout", "-q", "candidate/064/close-001"]);
    git(dir, &["reset", "--hard", "main"]);
    git(dir, &["checkout", "-q", "main"]);

    let out = admit(
        dir,
        None,
        &[
            "--role",
            "close_target",
            "--candidate",
            "refs/heads/candidate/064/close-001",
            "--review",
            "RV-007",
        ],
    );
    assert!(!out.status.success(), "admit refuses an unproven tip");
    assert!(
        stderr(&out).contains("descend") || stderr(&out).contains("I3"),
        "refusal names the descent/I3 failure: {}",
        stderr(&out)
    );
    let toml = read_candidates(dir);
    assert!(
        !toml.contains("[current_admission.close_target]"),
        "no admission recorded on refusal: {toml}"
    );
}

// --- VT-2: happy path records an immutable admitted_oid -----------------------

#[test]
fn e2e_dispatch_candidate_admit_records_immutable_oid_and_moved_ref_refuses() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);
    create_close_target(dir, "close-001");

    let tip = git(dir, &["rev-parse", "candidate/064/close-001"]);

    let out = admit(
        dir,
        None,
        &[
            "--role",
            "close_target",
            "--candidate",
            "refs/heads/candidate/064/close-001",
            "--review",
            "RV-007",
        ],
    );
    assert!(
        out.status.success(),
        "happy admit ok; stderr: {}",
        stderr(&out)
    );

    let toml = read_candidates(dir);
    assert!(
        toml.contains("[current_admission.close_target]"),
        "the close_target admission is recorded: {toml}"
    );
    assert!(
        toml.contains(&format!("admitted_oid = \"{tip}\"")),
        "admitted_oid pins the candidate tip: {toml}"
    );
    assert!(
        toml.contains("candidate_id = \"cand-064-close-001\""),
        "the admission names the candidate: {toml}"
    );
    assert!(
        toml.contains("review = \"RV-007\""),
        "the admission names its review: {toml}"
    );

    // Immutability: after the candidate ref later moves PAST the admitted oid,
    // the recorded admitted_oid is unchanged (re-running status mutates nothing).
    git(dir, &["checkout", "-q", "candidate/064/close-001"]);
    let moved = commit(dir, "drifted.txt", "drift", "manual edit past admitted oid");
    git(dir, &["checkout", "-q", "main"]);
    assert_ne!(moved, tip, "the ref genuinely moved");
    let after = read_candidates(dir);
    assert!(
        after.contains(&format!("admitted_oid = \"{tip}\"")),
        "admitted_oid stays immutable after the ref moves: {after}"
    );
    assert!(
        !after.contains(&moved),
        "the moved tip is NOT written into the admission: {after}"
    );
    // NOTE (VT-2 moved-ref): the read-reread refusal cannot be raced
    // deterministically from a single in-process CLI invocation (no hook between
    // the two resolves), so the moved-ref REFUSAL path is exercised by the admit
    // core's logic, not a black-box test; the immutability half is asserted here.
}

// --- VT-3: supersede re-admission records history, exactly one current --------

#[test]
fn e2e_dispatch_candidate_supersede_records_history() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);

    create_close_target(dir, "close-001");
    assert!(
        admit(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--candidate",
                "refs/heads/candidate/064/close-001",
                "--review",
                "RV-007",
            ],
        )
        .status
        .success(),
        "admit close-001"
    );

    // A superseding candidate from the same source (create requires a fresh
    // label + supersedes link).
    assert!(
        create(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--payload",
                "code",
                "--base",
                "refs/heads/main",
                "--label",
                "close-002",
                "--source",
                "refs/heads/phase/064-02",
                "--supersedes",
                "cand-064-close-001",
            ],
        )
        .status
        .success(),
        "create close-002 superseding close-001"
    );
    let tip2 = git(dir, &["rev-parse", "candidate/064/close-002"]);
    assert!(
        admit(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--candidate",
                "refs/heads/candidate/064/close-002",
                "--review",
                "RV-008",
            ],
        )
        .status
        .success(),
        "admit close-002"
    );

    let toml = read_candidates(dir);
    // Exactly ONE current close_target admission table.
    assert_eq!(
        toml.matches("[current_admission.close_target]").count(),
        1,
        "exactly one current close admission: {toml}"
    );
    // It points at close-002 with admitted_oid == its tip.
    assert!(
        toml.contains("candidate_id = \"cand-064-close-002\""),
        "the current admission is close-002: {toml}"
    );
    assert!(
        toml.contains(&format!("admitted_oid = \"{tip2}\"")),
        "admitted_oid is close-002's tip: {toml}"
    );
    // It supersedes the prior admitted candidate id.
    assert!(
        toml.contains("supersedes = \"cand-064-close-001\""),
        "the admission supersedes the prior admitted candidate: {toml}"
    );
}

// --- VT-4: admit leaves evidence/candidate refs untouched + worker refusal ----

#[test]
fn e2e_dispatch_candidate_admit_leaves_evidence_and_refused_under_worker() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);
    create_close_target(dir, "close-001");

    let review_before = git(dir, &["rev-parse", "review/064"]);
    let phase1_before = git(dir, &["rev-parse", "phase/064-01"]);
    let phase2_before = git(dir, &["rev-parse", "phase/064-02"]);
    let candidate_before = git(dir, &["rev-parse", "candidate/064/close-001"]);

    assert!(
        admit(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--candidate",
                "refs/heads/candidate/064/close-001",
                "--review",
                "RV-007",
            ],
        )
        .status
        .success(),
        "admit ok"
    );

    // EX-4: admit writes ONLY candidates.toml — every evidence/candidate ref is
    // byte-for-byte unchanged.
    assert_eq!(git(dir, &["rev-parse", "review/064"]), review_before);
    assert_eq!(git(dir, &["rev-parse", "phase/064-01"]), phase1_before);
    assert_eq!(git(dir, &["rev-parse", "phase/064-02"]), phase2_before);
    assert_eq!(
        git(dir, &["rev-parse", "candidate/064/close-001"]),
        candidate_before,
        "the candidate ref itself is untouched"
    );

    // Orchestrator-classed: refused under worker-mode, records no admission.
    let repo2 = tempfile::tempdir().unwrap();
    let dir2 = repo2.path();
    build_fixture(dir2);
    prepare_review(dir2);
    create_close_target(dir2, "close-001");

    let out = admit(
        dir2,
        Some(true),
        &[
            "--role",
            "close_target",
            "--candidate",
            "refs/heads/candidate/064/close-001",
            "--review",
            "RV-007",
        ],
    );
    assert!(!out.status.success(), "refused when DOCTRINE_WORKER set");
    assert!(
        stderr(&out).contains("DOCTRINE_WORKER"),
        "carries the dual-cause token: {}",
        stderr(&out)
    );
    let toml = read_candidates(dir2);
    assert!(
        !toml.contains("[current_admission.close_target]"),
        "no admission recorded under worker-mode refusal: {toml}"
    );
}

// =============================================================================
// SL-068 PHASE-06 — candidate-aware `dispatch sync --integrate` (VT-1..4)
//
// NOTE: when a candidate workflow is active (≥1 recorded candidate row),
// --trunk sources the admitted close_target OID and --edge the admitted
// review_surface OID — never a raw phase/review ref, never a close-time merge.
// The PRESERVED legacy path (no ledger ⇒ phase-chain tip / raw review) is
// exercised by the SIBLING tests/e2e_dispatch_sync.rs (which records no
// candidate) and MUST remain unedited and green.
// =============================================================================

/// The full journal.toml committed on `dispatch/064` (object db, not the
/// filesystem — integrate tree-reads it). Used to assert the CAS targeted the
/// admitted OID.
fn dispatch_journal(dir: &Path) -> String {
    git(
        dir,
        &["show", "dispatch/064:.doctrine/dispatch/064/journal.toml"],
    )
}

// --- VT-1: admit a close_target, then integrate --trunk fast-forwards to the
//           admitted OID with NO close-time merge --------------------------------

#[test]
fn e2e_dispatch_candidate_admit_then_integrate_ff() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);
    create_close_target(dir, "close-001");

    let admitted_oid = git(dir, &["rev-parse", "candidate/064/close-001"]);
    assert!(
        admit(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--candidate",
                "refs/heads/candidate/064/close-001",
                "--review",
                "RV-007",
            ],
        )
        .status
        .success(),
        "admit close-001"
    );

    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(
        out.status.success(),
        "candidate-aware integrate --trunk ff; stderr: {}",
        stderr(&out)
    );

    // main now == the admitted OID exactly (fast-forward) — NOT a fresh
    // close-time merge commit (I6).
    let main_after = git(dir, &["rev-parse", "main"]);
    assert_eq!(
        main_after, admitted_oid,
        "trunk advanced to the admitted close_target OID, no close-time merge"
    );

    // The committed journal/CAS targeted planned_new_oid == admitted_oid for the
    // trunk row (source_oid == planned_new_oid for a direct projection).
    let journal = dispatch_journal(dir);
    assert!(
        journal.contains("target_ref = \"refs/heads/main\""),
        "the trunk row targets main: {journal}"
    );
    assert!(
        journal.contains(&format!("planned_new_oid = \"{admitted_oid}\"")),
        "the trunk row's planned_new_oid is the admitted OID: {journal}"
    );
    assert!(
        journal.contains(&format!("source_oid = \"{admitted_oid}\"")),
        "the trunk row's source is the admitted OID (no merge synthesised): {journal}"
    );
}

// --- VT-2: the candidate ref moves AFTER admit; integrate still targets the
//           ADMITTED oid (I4 — targeting is by oid, not the live ref) ------------

#[test]
fn e2e_dispatch_candidate_ref_moves_after_admit_close_uses_oid() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);
    create_close_target(dir, "close-001");

    let admitted_oid = git(dir, &["rev-parse", "candidate/064/close-001"]);
    assert!(
        admit(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--candidate",
                "refs/heads/candidate/064/close-001",
                "--review",
                "RV-007",
            ],
        )
        .status
        .success(),
        "admit close-001"
    );

    // Move the candidate ref forward PAST the admitted oid (a fresh commit on
    // top) so its live tip != admitted_oid.
    git(dir, &["checkout", "-q", "candidate/064/close-001"]);
    let moved_tip = commit(dir, "after.txt", "after admit", "move candidate past admit");
    git(dir, &["checkout", "-q", "main"]);
    assert_ne!(moved_tip, admitted_oid, "the candidate ref genuinely moved");

    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(
        out.status.success(),
        "integrate targets the admitted oid despite the moved ref; stderr: {}",
        stderr(&out)
    );

    let main_after = git(dir, &["rev-parse", "main"]);
    assert_eq!(
        main_after, admitted_oid,
        "trunk advanced to the ADMITTED oid (I4), not the moved candidate tip"
    );
    assert_ne!(
        main_after, moved_tip,
        "the moved candidate tip is NOT what integrate targeted"
    );
}

// --- VT-3: trunk moved past the admitted oid after admit ⇒ integrate REFUSES
//           (no ff), names the moved target + a superseding close-target ---------

#[test]
fn e2e_dispatch_candidate_trunk_moved_after_admit_refuses() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);
    create_close_target(dir, "close-001");

    assert!(
        admit(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--candidate",
                "refs/heads/candidate/064/close-001",
                "--review",
                "RV-007",
            ],
        )
        .status
        .success(),
        "admit close-001"
    );

    // Advance main past the admitted oid (a fresh commit on main) so the admitted
    // close_target no longer fast-forwards main.
    let main_advanced = commit(dir, "trunk-moved.txt", "moved", "trunk moves past admit");

    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(
        !out.status.success(),
        "integrate --trunk refuses a non-ff admitted oid"
    );
    let err = stderr(&out);
    assert!(
        err.contains("fast-forward") || err.contains("trunk moved"),
        "refusal names the moved trunk: {err}"
    );
    assert!(
        err.contains("superseding close-target") || err.contains("re-admit"),
        "refusal instructs to create a superseding close-target candidate: {err}"
    );

    // main is UNCHANGED at the post-advance tip — no merge, no clobber.
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        main_advanced,
        "trunk left at the post-advance tip — never clobbered"
    );
}

// --- VT-4: workflow active (close_target admitted) but NO review_surface
//           admission ⇒ integrate --edge REFUSES (no raw-ref fallback) ----------

#[test]
fn e2e_dispatch_candidate_integrate_edge_without_admission_refuses() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    prepare_review(dir);
    create_close_target(dir, "close-001");

    // Admit ONLY the close_target — the workflow is active, but there is no
    // review_surface admission.
    assert!(
        admit(
            dir,
            None,
            &[
                "--role",
                "close_target",
                "--candidate",
                "refs/heads/candidate/064/close-001",
                "--review",
                "RV-007",
            ],
        )
        .status
        .success(),
        "admit close-001"
    );

    let out = integrate(dir, &["--edge", "refs/heads/edge"]);
    assert!(
        !out.status.success(),
        "integrate --edge refuses with no review_surface admission"
    );
    let err = stderr(&out);
    assert!(
        err.contains("review_surface"),
        "refusal names the missing review_surface admission: {err}"
    );
    assert!(
        !ref_exists(dir, "refs/heads/edge"),
        "no silent raw-ref fallback — the edge ref was not created"
    );
}