doctrine 0.5.1

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
// SPDX-License-Identifier: GPL-3.0-only
//! SL-064 PHASE-04 — `doctrine dispatch sync --prepare-review --slice <n>`
//! end-to-end over the BUILT binary (design §4.2 B / §4.3 C; ADR-012 D4/D5).
//!
//! * VT-1: default prepare-review creates `review/<slice>` and leaves trunk
//!   (`main`) byte-identical.
//! * VT-2: golden review composition — `review/064` carries the impl bundle
//!   (code + authored `.doctrine/` entity), excludes `.doctrine/dispatch/064/**`
//!   AND every journal-verified orthogonal path, retains a failed-mark path.
//! * VT-3: synthesized `phase/064-NN` refs contain exactly each phase's code
//!   delta, carry no `.doctrine/` path, and skip the empty-code phase.
//! * VT-4: impersonation — a marker-present linked worktree AND `DOCTRINE_WORKER=1`
//!   each refuse the verb, creating no external ref.
//! * EX-5: a stale pre-existing `review/064` is reported, never clobbered.
//!
//! PHASE-05 — stage-2 `--integrate` (appended below):
//! * EX-1/VT-3: integrate replays from a checkout with `dispatch/064` not checked
//!   out (plumbing-only, no coordination worktree).
//! * VT-1: the 3-way replay matrix — no-op on intact refs, idempotent re-run
//!   (crash-after-apply), refusal on a clobbered/diverged target. (The four CAS
//!   arms are exhaustively unit-pinned in `git::tests::replay_ref_no_op_apply_refuse`.)
//! * VT-2: trunk projection opt-in + fast-forward-only; refuses non-ff/moved trunk.
//! * EX-4: optional `edge` aggregate, default off.
//! * VT-5: `--integrate` refused under worker-mode (marker / `DOCTRINE_WORKER`).

#![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,
    code_end_1: String,
    code_end_2: String,
}

/// Build a repo with `main` at a trunk base and a `dispatch/064` branch carrying
/// two code phases, an authored entity, a verified-orthogonal file, a
/// failed-orthogonal file, and the `boundaries.toml`/`orthogonal.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",
    );
    commit(dir, "ahead.txt", "ahead", "orthogonal ahead-projected");
    commit(dir, "notahead.txt", "notahead", "orthogonal failed");

    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\
         [[boundary]]\nphase = \"PHASE-03\"\ncode_start_oid = \"{code_end_2}\"\ncode_end_oid = \"{code_end_2}\"\n"
    );
    let orthogonal = "[[mark]]\nentity = \"ahead\"\npath = \"ahead.txt\"\nstatus = \"verified\"\n\
         [[mark]]\nentity = \"notahead\"\npath = \"notahead.txt\"\nstatus = \"failed\"\n";
    std::fs::create_dir_all(dir.join(".doctrine/dispatch/064")).unwrap();
    std::fs::write(
        dir.join(".doctrine/dispatch/064/boundaries.toml"),
        &boundaries,
    )
    .unwrap();
    std::fs::write(
        dir.join(".doctrine/dispatch/064/orthogonal.toml"),
        orthogonal,
    )
    .unwrap();
    git(dir, &["add", ".doctrine/dispatch/064"]);
    git(dir, &["commit", "-q", "-m", "ledger fixtures"]);

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

/// Run `doctrine <args>` in `cwd`; `worker = Some(true)` sets DOCTRINE_WORKER=1.
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()
}

fn prepare_review(cwd: &Path) -> Output {
    run(
        cwd,
        None,
        &[
            "dispatch",
            "sync",
            "--prepare-review",
            "--slice",
            "64",
            "-p",
            cwd.to_str().unwrap(),
        ],
    )
}

// --- VT-1: review/<slice> created, trunk untouched ---------------------------

#[test]
fn prepare_review_creates_review_ref_and_leaves_trunk_unchanged() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    let main_before = git(dir, &["rev-parse", "main"]);

    let out = prepare_review(dir);
    assert!(
        out.status.success(),
        "prepare-review ok; stderr: {}",
        stderr(&out)
    );

    assert!(ref_exists(dir, "review/064"), "review/064 created");
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        main_before,
        "trunk untouched"
    );
    assert!(!ref_exists(dir, "edge"), "edge never written");
}

// --- VT-2: review composition (golden) ---------------------------------------

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

    let out = prepare_review(dir);
    assert!(
        out.status.success(),
        "prepare-review ok; stderr: {}",
        stderr(&out)
    );

    let listing = git(dir, &["ls-tree", "-r", "--name-only", "review/064"]);
    let paths: Vec<&str> = listing.lines().collect();
    // impl bundle retained:
    for kept in [
        "trunk.txt",
        "src1.txt",
        "src2.txt",
        ".doctrine/slice/064/slice-064.md",
    ] {
        assert!(paths.contains(&kept), "review retains {kept}: {listing}");
    }
    // run ledger excluded:
    assert!(
        !paths
            .iter()
            .any(|p| p.starts_with(".doctrine/dispatch/064")),
        "review excludes the run-ledger dir: {listing}"
    );
    // verified-orthogonal path excluded; failed-mark path retained:
    assert!(
        !paths.contains(&"ahead.txt"),
        "verified-orthogonal path excluded: {listing}"
    );
    assert!(
        paths.contains(&"notahead.txt"),
        "failed-mark path falls back into the bundle: {listing}"
    );

    // parented to the trunk base ⇒ diff base...review is exactly the bundle.
    let parent = git(dir, &["rev-parse", "review/064^"]);
    assert_eq!(parent, fixture.base, "review parented to the trunk base");
}

// --- VT-3: per-phase synthesis -----------------------------------------------

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

    let out = prepare_review(dir);
    assert!(
        out.status.success(),
        "prepare-review ok; stderr: {}",
        stderr(&out)
    );

    assert!(ref_exists(dir, "phase/064-01"), "phase 01 cut");
    assert!(ref_exists(dir, "phase/064-02"), "phase 02 cut");
    assert!(
        !ref_exists(dir, "phase/064-03"),
        "empty-code phase 03 emits no ref"
    );

    // phase 01 = exactly src1.txt over the trunk base; no .doctrine.
    assert_eq!(
        git(dir, &["diff", "--name-only", &fixture.base, "phase/064-01"]),
        "src1.txt",
        "phase 01 diff is exactly its code delta"
    );
    // phase 02 chained off phase 01 = exactly src2.txt.
    assert_eq!(
        git(
            dir,
            &["diff", "--name-only", "phase/064-01", "phase/064-02"]
        ),
        "src2.txt",
        "phase 02 diff is exactly its code delta"
    );
    let p1_listing = git(dir, &["ls-tree", "-r", "--name-only", "phase/064-01"]);
    assert!(
        !p1_listing.lines().any(|p| p.starts_with(".doctrine")),
        "phase ref carries no .doctrine/ path: {p1_listing}"
    );
    // The empty phase used code_end_2 == code_start_2; phase 02 already covers it.
    let _ = &fixture.code_end_1;
    let _ = &fixture.code_end_2;
}

// --- VT-3 (cont): EX-2 journal committed onto the branch with verified rows ---

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

    let out = prepare_review(dir);
    assert!(
        out.status.success(),
        "prepare-review ok; stderr: {}",
        stderr(&out)
    );

    let journal = git(
        dir,
        &["show", "dispatch/064:.doctrine/dispatch/064/journal.toml"],
    );
    assert!(
        journal.contains("review/064"),
        "journal records the review ref: {journal}"
    );
    assert!(
        journal.contains("phase/064-01"),
        "journal records a phase ref: {journal}"
    );
    assert!(
        journal.contains("verified"),
        "applied rows are verified: {journal}"
    );
    assert!(
        !journal.contains("pending"),
        "no rows left pending after a clean run: {journal}"
    );
}

// --- VT-4: impersonation refusal ---------------------------------------------

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

    // (1) Marker-present linked worktree, env unset ⇒ refused, names verb.
    let holder = tempfile::tempdir().unwrap();
    let base = git(dir, &["rev-parse", "HEAD"]);
    let linked = holder.path().join("fork");
    git(
        dir,
        &[
            "worktree",
            "add",
            "-b",
            "wkr-guard",
            linked.to_str().unwrap(),
            &base,
        ],
    );
    let marker_dir = linked.join(".doctrine/state/dispatch");
    std::fs::create_dir_all(&marker_dir).unwrap();
    std::fs::write(marker_dir.join("worker"), b"").unwrap();

    let out = run(
        &linked,
        None,
        &[
            "dispatch",
            "sync",
            "--prepare-review",
            "--slice",
            "64",
            "-p",
            dir.to_str().unwrap(),
        ],
    );
    assert!(
        !out.status.success(),
        "refused from a marked linked worktree"
    );
    assert!(
        stderr(&out).contains("dispatch-sync"),
        "refusal names the verb: {}",
        stderr(&out)
    );
    assert!(
        !ref_exists(dir, "review/064"),
        "refused run creates no external ref"
    );

    // (2) DOCTRINE_WORKER set ⇒ dual-cause refusal.
    let out = run(
        dir,
        Some(true),
        &[
            "dispatch",
            "sync",
            "--prepare-review",
            "--slice",
            "64",
            "-p",
            dir.to_str().unwrap(),
        ],
    );
    assert!(!out.status.success(), "refused when DOCTRINE_WORKER set");
    assert!(
        stderr(&out).contains("DOCTRINE_WORKER"),
        "carries the dual-cause: {}",
        stderr(&out)
    );
    assert!(!ref_exists(dir, "review/064"), "still no external ref");
}

// --- EX-5: a stale pre-existing review ref is reported, never clobbered -------

#[test]
fn stale_review_ref_is_reported_not_clobbered() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    // A crashed prior run left review/064 at the trunk base (bogus content).
    let bogus = git(dir, &["rev-parse", "main"]);
    git(dir, &["update-ref", "refs/heads/review/064", &bogus]);

    let out = prepare_review(dir);
    assert!(
        !out.status.success(),
        "stale ref makes the run report failure"
    );
    assert!(
        stderr(&out).contains("not clobbered"),
        "stale ref is reported, not clobbered: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "review/064"]),
        bogus,
        "the stale review/064 is left untouched"
    );
}

// --- VT-4 (IMP-075): apply-contract persistence. A semantic refusal returns
//     Ok(Refused) — NOT a `?`-Err — so the post-loop recovery commit_journal runs
//     and durably records `status=Failed`. Tree-read the COMMITTED journal to
//     prove the recovery commit ran rather than an early Err abort. ------------

#[test]
fn refused_row_persists_failed_status_in_committed_journal() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    // A crashed prior run left review/064 at the trunk base — its zero-oid CAS
    // creation will be refused (the row is a SEMANTIC refusal, not fatal).
    let bogus = git(dir, &["rev-parse", "main"]);
    git(dir, &["update-ref", "refs/heads/review/064", &bogus]);

    let out = prepare_review(dir);
    assert!(!out.status.success(), "stale ref makes the run bail");

    // The committed journal on dispatch/064 must carry the refused row as failed:
    // proves the recovery commit_journal ran AFTER the apply loop (Ok(Refused),
    // not an early Err abort that would skip the recovery commit).
    let journal = git(
        dir,
        &["show", "dispatch/064:.doctrine/dispatch/064/journal.toml"],
    );
    assert!(
        journal.contains("review/064"),
        "journal records the refused review row: {journal}"
    );
    assert!(
        journal.contains("failed"),
        "the refused row persisted status=failed (recovery commit ran): {journal}"
    );
}

// ====================================================================
// PHASE-05 — stage-2 `dispatch sync --integrate` (design §4 / ADR-012 D4/D5)
// ====================================================================

/// Run `dispatch sync --integrate --slice 64` in `cwd` with `extra` flags.
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)
}

/// EX-1 / VT-3 + VT-1(no-op): integrate runs from a checkout where `dispatch/064`
/// is NOT checked out (plumbing-only, no coordination worktree). Default
/// integration replays the prepared journal as verified no-ops and leaves trunk
/// untouched (EX-3).
#[test]
fn integrate_default_replays_prepared_refs_no_checkout_no_trunk_write() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());

    let trunk_before = git(dir, &["rev-parse", "main"]);
    let review_before = git(dir, &["rev-parse", "review/064"]);
    let phase_before = git(dir, &["rev-parse", "phase/064-02"]);
    // The working tree is on `main`; dispatch/064 is a branch with no worktree.
    assert_eq!(git(dir, &["rev-parse", "--abbrev-ref", "HEAD"]), "main");

    let out = integrate(dir, &[]);
    assert!(
        out.status.success(),
        "default integrate replays cleanly; stderr: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        trunk_before,
        "trunk untouched"
    );
    assert_eq!(git(dir, &["rev-parse", "review/064"]), review_before);
    assert_eq!(git(dir, &["rev-parse", "phase/064-02"]), phase_before);

    let journal = git(
        dir,
        &["show", "dispatch/064:.doctrine/dispatch/064/journal.toml"],
    );
    assert!(
        !journal.contains("pending"),
        "no pending rows after replay: {journal}"
    );
}

/// VT-2: trunk projection is opt-in, fast-forward-only. `--trunk` advances the
/// trunk ref to the cumulative code tip; a second run is an idempotent no-op
/// (VT-1: crash-after-apply recovery).
#[test]
fn integrate_trunk_fast_forwards_then_is_idempotent() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());
    let phase_tip = git(dir, &["rev-parse", "phase/064-02"]);

    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(
        out.status.success(),
        "ff trunk integrate; stderr: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        phase_tip,
        "trunk fast-forwarded to the cumulative code tip"
    );

    // Re-run: current == planned ⇒ verified no-op, trunk unchanged.
    let out2 = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(
        out2.status.success(),
        "idempotent re-run; stderr: {}",
        stderr(&out2)
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        phase_tip,
        "no second advance"
    );
}

/// VT-2: explicit trunk mode refuses a non-fast-forward / moved trunk and writes
/// nothing (IMP-043 re-anchor is reported, never auto-resolved).
#[test]
fn integrate_trunk_refuses_non_fast_forward() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());

    // Move trunk onto a divergent commit — not an ancestor of the phase chain.
    let moved = commit(dir, "trunk2.txt", "moved", "trunk advanced divergently");
    assert_eq!(git(dir, &["rev-parse", "main"]), moved);

    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(!out.status.success(), "non-ff trunk is refused");
    assert!(
        stderr(&out).contains("fast-forward") || stderr(&out).contains("trunk moved"),
        "refusal names the non-ff/moved-trunk cause: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        moved,
        "trunk left untouched"
    );
}

/// RV-030 F-1: a foreign commit landing on trunk BETWEEN coordinate and
/// prepare-review must NOT reparent the projection. Stage-1 projects off the
/// pinned fork-point `merge-base(dispatch/064, trunk)`, not the live trunk tip —
/// the coordination worktree isolates the working tree, not the trunk ref. So the
/// per-phase cut stays an exact code delta (no foreign leak), and the §3/IMP-043
/// moved-trunk net fires: a subsequent `integrate --trunk` refuses the non-ff
/// instead of silently absorbing the pre-stage-1 movement.
#[test]
fn prepare_review_projects_off_pinned_fork_point_not_moved_trunk() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    let fixture = build_fixture(dir);

    // A foreign writer advances trunk after dispatch/064 forked from `base`.
    let foreign = commit(dir, "foreign.txt", "foreign", "foreign trunk advance");
    assert_eq!(git(dir, &["rev-parse", "main"]), foreign);
    assert_ne!(
        foreign, fixture.base,
        "trunk genuinely moved off the fork-point"
    );

    let out = prepare_review(dir);
    assert!(
        out.status.success(),
        "prepare-review ok despite moved trunk; stderr: {}",
        stderr(&out)
    );

    // The phase cut is parented on the FORK-POINT, not the moved trunk tip — so
    // its diff is exactly the phase code, with no foreign trunk delta leaking in.
    assert_eq!(
        git(dir, &["rev-parse", "phase/064-01^"]),
        fixture.base,
        "phase parented on the pinned fork-point, not the moved trunk tip"
    );
    assert_eq!(
        git(dir, &["diff", "--name-only", &fixture.base, "phase/064-01"]),
        "src1.txt",
        "phase diff is the exact code delta — foreign trunk file excluded"
    );
    assert!(
        !git(dir, &["ls-tree", "-r", "--name-only", "phase/064-02"]).contains("foreign.txt"),
        "the foreign trunk file never leaks into the phase bundle"
    );

    // The moved-trunk net now fires: the phase chain descends from the fork-point,
    // not the moved tip, so integrate --trunk refuses the non-ff (was silently
    // absorbed when stage-1 parented on the live trunk tip).
    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(
        !out.status.success(),
        "integrate --trunk refuses the moved trunk; stderr: {}",
        stderr(&out)
    );
    assert!(
        stderr(&out).contains("fast-forward") || stderr(&out).contains("trunk moved"),
        "refusal names the non-ff cause: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        foreign,
        "trunk left untouched on refusal"
    );
}

/// VT-1 (replay refusal on divergence): a prepared ref clobbered after
/// prepare-review diverges from both its journaled `expected_old` and `planned`
/// ⇒ integrate refuses and leaves it untouched.
#[test]
fn integrate_refuses_clobbered_prepared_ref() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());

    // A foreign writer moved review/064 to the trunk base (≠ ZERO, ≠ planned).
    let bogus = git(dir, &["rev-parse", "main"]);
    git(dir, &["update-ref", "refs/heads/review/064", &bogus]);

    let out = integrate(dir, &[]);
    assert!(
        !out.status.success(),
        "diverged prepared ref refuses replay"
    );
    assert!(
        stderr(&out).contains("moved target") || stderr(&out).contains("not clobbered"),
        "divergence is reported: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "review/064"]),
        bogus,
        "the clobbered ref is left untouched, never force-resolved"
    );
}

/// EX-4: the optional `edge` aggregate advances to the `review/<slice>` bundle,
/// isolated to this sync point; default integration writes no edge ref.
#[test]
fn integrate_edge_is_opt_in_and_aggregates_the_review_bundle() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());
    let review_tip = git(dir, &["rev-parse", "review/064"]);

    // Default integrate writes no edge ref.
    assert!(integrate(dir, &[]).status.success());
    assert!(
        !ref_exists(dir, "refs/heads/edge"),
        "edge is opt-in, default off"
    );

    // Opt-in: edge is created at the review bundle.
    let out = integrate(dir, &["--edge", "refs/heads/edge"]);
    assert!(
        out.status.success(),
        "edge projection; stderr: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "edge"]),
        review_tip,
        "edge aggregates the review/<slice> bundle"
    );
}

// === SL-121 PHASE-02 — worktree-aware integrate advance + report ============

/// VT-2 (the ISS-022/030 regression): a checked-out trunk target fast-forwards via
/// `merge --ff-only`, so ref + index + worktree all land on the planned tip and
/// `git status` is empty — no phantom reverse-diff. (Pre-SL-121 pure
/// `update_ref_cas` advanced the ref but left the live tree stale.)
#[test]
fn integrate_trunk_checked_out_ff_leaves_clean_tree() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());
    let phase_tip = git(dir, &["rev-parse", "phase/064-02"]);
    // build_fixture leaves the working tree on main → the trunk target is checked out.
    assert_eq!(git(dir, &["rev-parse", "--abbrev-ref", "HEAD"]), "main");

    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(
        out.status.success(),
        "ff integrate on a checked-out trunk; stderr: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        phase_tip,
        "trunk ref advanced to the cumulative code tip"
    );
    assert_eq!(
        git(dir, &["rev-parse", "HEAD"]),
        phase_tip,
        "HEAD advanced with the live checkout"
    );
    assert!(
        git(dir, &["status", "--porcelain"]).is_empty(),
        "index + worktree resynced — no phantom reverse-diff (ISS-022/030)",
    );
    assert!(
        dir.join("src1.txt").exists() && dir.join("src2.txt").exists(),
        "the advanced code is materialised in the live worktree",
    );
}

/// VT-1: a NOT-checked-out target advances by pure ref-CAS; the live (main)
/// checkout is left untouched — a pure-ref advance introduces no phantom diff.
#[test]
fn integrate_trunk_not_checked_out_advances_ref_leaves_live_checkout_clean() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    let fixture = build_fixture(dir);
    assert!(prepare_review(dir).status.success());
    let phase_tip = git(dir, &["rev-parse", "phase/064-02"]);
    // A trunk-like ref parked at the fork base, checked out nowhere.
    git(dir, &["update-ref", "refs/heads/release", &fixture.base]);

    let out = integrate(dir, &["--trunk", "refs/heads/release"]);
    assert!(
        out.status.success(),
        "ff integrate on a not-checked-out ref; stderr: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "release"]),
        phase_tip,
        "the unchecked-out ref advanced by CAS"
    );
    assert!(
        git(dir, &["status", "--porcelain"]).is_empty(),
        "the live main checkout is untouched by a pure-ref advance",
    );
}

/// VT-3 (EX-1, M4): a DIRTY checked-out target refuses the whole integrate with
/// `integrate-dirty-worktree` and moves ZERO refs — including the coordination ref
/// `dispatch/064` (the gate runs before the first `commit_journal`).
#[test]
fn integrate_dirty_checked_out_target_refuses_zero_refs_moved() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());

    // Snapshot every ref the integrate would touch + the coordination ref.
    let main_before = git(dir, &["rev-parse", "main"]);
    let dispatch_before = git(dir, &["rev-parse", "dispatch/064"]);
    let review_before = git(dir, &["rev-parse", "review/064"]);
    let phase_before = git(dir, &["rev-parse", "phase/064-02"]);

    // Dirty the checked-out trunk (tracked modification).
    std::fs::write(dir.join("trunk.txt"), "locally dirtied").unwrap();

    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(!out.status.success(), "a dirty checked-out target refuses");
    assert!(
        stderr(&out).contains("integrate-dirty-worktree"),
        "refusal names the dirty-worktree token: {}",
        stderr(&out),
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        main_before,
        "trunk unmoved"
    );
    assert_eq!(
        git(dir, &["rev-parse", "dispatch/064"]),
        dispatch_before,
        "coordination ref unmoved (gate precedes the first commit_journal, M4)"
    );
    assert_eq!(
        git(dir, &["rev-parse", "review/064"]),
        review_before,
        "review unmoved"
    );
    assert_eq!(
        git(dir, &["rev-parse", "phase/064-02"]),
        phase_before,
        "phase unmoved"
    );
}

/// VT-4 (B2): a checked-out target needing a NON-ff advance refuses
/// `integrate-nonff-checkout` (never `reset --hard` a live ref); the ref is left
/// unmoved and the row persists `Failed` in the committed journal. Exercised via
/// the edge row (not ff-gated at plan time) checked out in a linked worktree on a
/// commit divergent from `review/064`.
#[test]
fn integrate_nonff_checked_out_edge_refuses_and_persists_failed() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    let fixture = build_fixture(dir);
    assert!(prepare_review(dir).status.success());

    // An `edge` branch checked out in a linked worktree, advanced divergently so a
    // fast-forward to review/064 is impossible.
    git(dir, &["update-ref", "refs/heads/edge", &fixture.base]);
    let holder = tempfile::tempdir().unwrap();
    let linked = holder.path().join("edgewt");
    git(dir, &["worktree", "add", linked.to_str().unwrap(), "edge"]);
    std::fs::write(linked.join("divergent.txt"), "x").unwrap();
    git(&linked, &["add", "divergent.txt"]);
    git(&linked, &["commit", "-q", "-m", "edge divergent"]);
    let edge_before = git(dir, &["rev-parse", "edge"]);

    let out = integrate(dir, &["--edge", "refs/heads/edge"]);
    assert!(!out.status.success(), "a non-ff checked-out edge refuses");
    assert!(
        stderr(&out).contains("integrate-nonff-checkout"),
        "refusal names the non-ff-checkout token: {}",
        stderr(&out),
    );
    assert_eq!(
        git(dir, &["rev-parse", "edge"]),
        edge_before,
        "edge ref left untouched (never reset --hard a live ref)"
    );
    let journal = git(
        dir,
        &["show", "dispatch/064:.doctrine/dispatch/064/journal.toml"],
    );
    assert!(
        journal.contains("failed"),
        "the refused edge row persisted status=failed: {journal}"
    );
}

/// VT-6 (§4 / IMP-078): integrate emits per-row disposition detail on stderr with
/// the EXACT tokens AND preserves the machine-readable stdout ref-list contract.
#[test]
fn integrate_report_emits_disposition_and_preserves_stdout_reflist() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());

    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let so = String::from_utf8_lossy(&out.stdout);
    let se = stderr(&out);

    // stdout: the changed-ref list (advanced rows) — contract preserved.
    assert!(
        so.lines().any(|l| l == "refs/heads/main"),
        "stdout carries the advanced trunk ref verbatim: {so:?}",
    );
    // stderr: per-row disposition line for the trunk (main was checked out → the
    // ff-merge resync disposition) plus the trailing replayed count.
    assert!(
        se.contains("(advanced+resynced)"),
        "stderr names the exact advanced+resynced disposition: {se}",
    );
    assert!(
        se.contains("integrate: refs/heads/main "),
        "stderr carries the per-row trunk detail line: {se}",
    );
    assert!(
        se.contains("ref(s) replayed"),
        "the trailing summary line is preserved: {se}",
    );
    // The already-at-tip prepared rows report the no-op token.
    assert!(
        se.contains("(no-op)"),
        "no-op rows are reported with the exact token: {se}",
    );
}

/// VT-5: `--integrate` is the same Orchestrator verb class — a marker-present
/// linked worktree AND `DOCTRINE_WORKER=1` each refuse it, writing no trunk.
#[test]
fn integrate_refused_under_worker_mode() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());
    let trunk_before = git(dir, &["rev-parse", "main"]);

    // (1) Marker-present linked worktree, env unset ⇒ refused, names the verb.
    let holder = tempfile::tempdir().unwrap();
    let base = git(dir, &["rev-parse", "HEAD"]);
    let linked = holder.path().join("fork");
    git(
        dir,
        &[
            "worktree",
            "add",
            "-b",
            "wkr-int",
            linked.to_str().unwrap(),
            &base,
        ],
    );
    let marker_dir = linked.join(".doctrine/state/dispatch");
    std::fs::create_dir_all(&marker_dir).unwrap();
    std::fs::write(marker_dir.join("worker"), b"").unwrap();

    let out = run(
        &linked,
        None,
        &[
            "dispatch",
            "sync",
            "--integrate",
            "--trunk",
            "refs/heads/main",
            "--slice",
            "64",
            "-p",
            dir.to_str().unwrap(),
        ],
    );
    assert!(
        !out.status.success(),
        "refused from a marked linked worktree"
    );
    assert!(
        stderr(&out).contains("dispatch-sync"),
        "refusal names the verb: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        trunk_before,
        "no trunk write"
    );

    // (2) DOCTRINE_WORKER set ⇒ dual-cause refusal, still no trunk write.
    let out = run(
        dir,
        Some(true),
        &[
            "dispatch",
            "sync",
            "--integrate",
            "--trunk",
            "refs/heads/main",
            "--slice",
            "64",
            "-p",
            dir.to_str().unwrap(),
        ],
    );
    assert!(!out.status.success(), "refused when DOCTRINE_WORKER set");
    assert!(
        stderr(&out).contains("DOCTRINE_WORKER"),
        "carries the dual-cause: {}",
        stderr(&out)
    );
    assert_eq!(
        git(dir, &["rev-parse", "main"]),
        trunk_before,
        "still no trunk write"
    );
}

// --- PHASE-06 VT-2: the funnel-time `record-boundary` recording verb ----------
//
// The claude-arm phase cut (§4.3) consumes `boundaries.toml`; the orchestrator
// populates it during the funnel via this verb (the surface the skills cite).
// Pins: (a) it appends a `[[boundary]]` row at the CANONICAL padded ledger path
// `.doctrine/dispatch/064/` (the path `dispatch sync` tree-reads — writer↔reader
// agreement), and (b) it is Orchestrator-classed (refused under worker-mode).

fn record_boundary(cwd: &Path, root: &Path, phase: &str, start: &str, end: &str) -> Output {
    run(
        cwd,
        None,
        &[
            "dispatch",
            "record-boundary",
            "--slice",
            "64",
            "--phase",
            phase,
            "--code-start",
            start,
            "--code-end",
            end,
            "-p",
            root.to_str().unwrap(),
        ],
    )
}

#[test]
fn record_boundary_appends_row_at_canonical_padded_ledger_path() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    let fx = build_fixture(dir);
    let ledger = dir.join(".doctrine/dispatch/064/boundaries.toml");

    let out = record_boundary(dir, dir, "PHASE-09", &fx.base, &fx.code_end_1);
    assert!(
        out.status.success(),
        "record-boundary ok; stderr: {}",
        stderr(&out)
    );
    let body = std::fs::read_to_string(&ledger).expect("ledger written at padded path");
    assert!(body.contains("[[boundary]]"), "row header: {body}");
    assert!(body.contains("phase = \"PHASE-09\""), "phase row: {body}");
    // Stores the resolved code tip (full oid) the phase cut snapshots.
    assert!(body.contains(&fx.code_end_1), "code_end oid: {body}");

    // Append-only: a second record adds a second row, keeps the first.
    let out = record_boundary(dir, dir, "PHASE-10", &fx.code_end_1, &fx.code_end_2);
    assert!(out.status.success(), "second record ok: {}", stderr(&out));
    let body = std::fs::read_to_string(&ledger).unwrap();
    assert!(
        body.contains("PHASE-09") && body.contains("PHASE-10"),
        "both rows present: {body}"
    );
}

#[test]
fn record_boundary_refused_under_worker_mode() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    let fx = build_fixture(dir);
    let ledger = dir.join(".doctrine/dispatch/064/boundaries.toml");

    // (1) Marker-present linked worktree, env unset ⇒ refused, names the verb.
    let holder = tempfile::tempdir().unwrap();
    let base = git(dir, &["rev-parse", "HEAD"]);
    let linked = holder.path().join("fork");
    git(
        dir,
        &[
            "worktree",
            "add",
            "-b",
            "wkr-guard-rb",
            linked.to_str().unwrap(),
            &base,
        ],
    );
    let marker_dir = linked.join(".doctrine/state/dispatch");
    std::fs::create_dir_all(&marker_dir).unwrap();
    std::fs::write(marker_dir.join("worker"), b"").unwrap();

    let out = record_boundary(&linked, dir, "PHASE-09", &fx.base, &fx.code_end_1);
    assert!(
        !out.status.success(),
        "refused from a marked linked worktree"
    );
    assert!(
        stderr(&out).contains("dispatch-record-boundary"),
        "refusal names the verb: {}",
        stderr(&out)
    );
    assert!(!ledger.exists(), "refused run records nothing");

    // (2) DOCTRINE_WORKER set ⇒ refused, dual-cause token.
    let out = run(
        dir,
        Some(true),
        &[
            "dispatch",
            "record-boundary",
            "--slice",
            "64",
            "--phase",
            "PHASE-09",
            "--code-start",
            &fx.base,
            "--code-end",
            &fx.code_end_1,
            "-p",
            dir.to_str().unwrap(),
        ],
    );
    assert!(!out.status.success(), "refused when DOCTRINE_WORKER set");
    assert!(
        stderr(&out).contains("DOCTRINE_WORKER"),
        "carries the dual-cause: {}",
        stderr(&out)
    );
    assert!(!ledger.exists(), "still records nothing");
}

// ====================================================================
// PHASE-03 (SL-121) — close-verify read surface (EX-1 / VT-1, design §3(b))
// ====================================================================

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

/// Read the committed `dispatch/064` journal's trunk-row `planned_new_oid` via the
/// new read flag, naming the row with `--trunk <ref>`. Runs in `cwd`.
fn show_journal_trunk_oid(cwd: &Path, trunk: &str) -> Output {
    run(
        cwd,
        None,
        &[
            "dispatch",
            "sync",
            "--show-journal-trunk-oid",
            "--slice",
            "64",
            "--trunk",
            trunk,
            "-p",
            cwd.to_str().unwrap(),
        ],
    )
}

/// VT-1 / EX-1: after a trunk integrate journals the trunk row, the read surface
/// returns that row's full `planned_new_oid` from a checkout where `dispatch/064`
/// is NOT checked out (the working tree is on `main`) — a tree-read of the
/// committed journal (the `sync-tree-reads-ledger-not-worktree` invariant), not a
/// transient `candidate admit` stdout. The value equals the cumulative code tip
/// that `main` was advanced to.
#[test]
fn show_journal_trunk_oid_returns_committed_planned_oid_from_any_checkout() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());
    let phase_tip = git(dir, &["rev-parse", "phase/064-02"]);

    assert!(
        integrate(dir, &["--trunk", "refs/heads/main"])
            .status
            .success(),
        "trunk integrate journals the trunk row"
    );
    // The working tree is on `main`; dispatch/064 has no live worktree.
    assert_eq!(git(dir, &["rev-parse", "--abbrev-ref", "HEAD"]), "main");

    let out = show_journal_trunk_oid(dir, "refs/heads/main");
    assert!(
        out.status.success(),
        "read surface succeeds; stderr: {}",
        stderr(&out)
    );
    assert_eq!(
        stdout(&out),
        phase_tip,
        "prints the trunk row's full planned_new_oid (== the projected tip)"
    );
}

/// EX-1 (error path): a journal with no row for the named trunk ref (only
/// `--prepare-review` ran — no trunk row journaled) refuses with a named token and
/// prints no oid to stdout, so the close skill never diffs against an empty value.
#[test]
fn show_journal_trunk_oid_errors_when_no_trunk_row() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());

    let out = show_journal_trunk_oid(dir, "refs/heads/main");
    assert!(
        !out.status.success(),
        "no trunk row in the journal ⇒ refused"
    );
    assert!(
        stderr(&out).contains("show-journal-trunk-oid"),
        "refusal names the read surface: {}",
        stderr(&out)
    );
    assert!(
        stdout(&out).is_empty(),
        "no oid emitted on the error path: {:?}",
        stdout(&out)
    );
}

/// EX-1 (clap wiring, R1): `--show-journal-trunk-oid` without `--trunk` is refused
/// at parse — the read mode always names the row it reads.
#[test]
fn show_journal_trunk_oid_requires_trunk() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);

    let out = run(
        dir,
        None,
        &[
            "dispatch",
            "sync",
            "--show-journal-trunk-oid",
            "--slice",
            "64",
            "-p",
            dir.to_str().unwrap(),
        ],
    );
    assert!(!out.status.success(), "missing --trunk is a parse error");
    assert!(
        stderr(&out).contains("--trunk"),
        "clap names the required --trunk: {}",
        stderr(&out)
    );
}

// ====================================================================
// PHASE-02 (SL-126) — close-integration gate, end-to-end against a REAL
// journal. The keystone: PHASE-01's unit fixtures encode the row shape, but
// only a real `prepare_review` + `integrate --trunk` proves git produces a
// trunk row the gate reads as Integrated. Both arms drive a slice fixture at
// `reconcile` to `done` via the BUILT binary's `slice status`.
// ====================================================================

/// Materialise slice 064's authored `slice-064.toml` at `status = "reconcile"` in
/// the fixture's working tree (the legal source for `→ done`). The gate reads the
/// working filesystem for the authored status; no reqs/coverage ⇒ the blocker and
/// drift gates pass, leaving the integration gate as the sole arbiter.
fn write_reconcile_slice_64(dir: &Path) {
    let body = "id = 64\n\
         slug = \"dispatched-slice\"\n\
         title = \"Dispatched slice\"\n\
         status = \"reconcile\"\n\
         created = \"2026-06-20\"\n\
         updated = \"2026-06-20\"\n\
         \n[relationships]\nneeds = []\nafter = []\n";
    let path = dir.join(".doctrine/slice/064/slice-064.toml");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, body).unwrap();
}

/// Drive `slice status 64 done -p <dir>` over the built binary.
fn slice_status_done(dir: &Path) -> Output {
    run(
        dir,
        None,
        &["slice", "status", "64", "done", "-p", dir.to_str().unwrap()],
    )
}

/// VT-7(a): after a real `prepare_review` + `integrate --trunk refs/heads/main`,
/// the trunk row's planned oid is an ancestor of `main` — the gate reads the
/// git-produced journal as Integrated and `reconcile → done` SUCCEEDS.
#[test]
fn vt7_close_integration_succeeds_after_real_trunk_integrate() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());
    let out = integrate(dir, &["--trunk", "refs/heads/main"]);
    assert!(
        out.status.success(),
        "trunk integrate; stderr: {}",
        stderr(&out)
    );

    write_reconcile_slice_64(dir);
    let out = slice_status_done(dir);
    assert!(
        out.status.success(),
        "integrated slice closes; stderr: {}",
        stderr(&out)
    );
    // The authored status advanced to done.
    let toml = std::fs::read_to_string(dir.join(".doctrine/slice/064/slice-064.toml")).unwrap();
    assert!(
        toml.contains("status = \"done\""),
        "close wrote the terminal status: {toml}"
    );
}

/// VT-7(b): `prepare_review` ran but `--trunk` was NOT integrated, so the journal
/// carries no `refs/heads/main` row — the gate fails closed and `reconcile → done`
/// is REFUSED, naming the missing-trunk-row anomaly.
#[test]
fn vt7_close_integration_refused_without_trunk_integrate() {
    let repo = tempfile::tempdir().unwrap();
    let dir = repo.path();
    build_fixture(dir);
    assert!(prepare_review(dir).status.success());
    // Default integrate (no `--trunk`) — replays review/phase refs, no trunk row.
    assert!(integrate(dir, &[]).status.success());

    write_reconcile_slice_64(dir);
    let out = slice_status_done(dir);
    assert!(
        !out.status.success(),
        "an unintegrated dispatched slice is refused close"
    );
    assert!(
        stderr(&out).contains("not integrated to trunk")
            && stderr(&out).contains("integrate --trunk never completed"),
        "refusal names the no-trunk-row anomaly: {}",
        stderr(&out)
    );
    // Refused before the write — the authored status stays at reconcile.
    let toml = std::fs::read_to_string(dir.join(".doctrine/slice/064/slice-064.toml")).unwrap();
    assert!(
        toml.contains("status = \"reconcile\""),
        "no write on refusal: {toml}"
    );
}