loopflow 0.12.7

Run steps and flows with coding agents
Documentation
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
mod support;

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::process::{Command, Stdio};

use loopflow::engine::worktrees::create_named_worktree;
use loopflow::ops::{
    create_or_update_pr, land, submit, LandOptions, NullProgress, OpsError, PrOptions,
};
use loopflow::task::{AfterMerge, PrMergeMode, PrPhase};
use loopflow_test_support::TestRepo;
use support::{counting_open_script, presentation_attempts, register_task, EnvGuard};

fn push_branch(repo: &TestRepo, name: &str) {
    let _ = Command::new("git")
        .args(["push", "-u", "origin", name])
        .current_dir(repo.path())
        .status();
}

fn local_branch_exists(repo: &TestRepo, name: &str) -> bool {
    Command::new("git")
        .args(["show-ref", "--verify", &format!("refs/heads/{name}")])
        .current_dir(repo.path())
        .stderr(Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

fn remote_branch_exists(repo: &TestRepo, name: &str) -> bool {
    Command::new("git")
        .arg("--git-dir")
        .arg(repo.bare_path())
        .args(["show-ref", "--verify", &format!("refs/heads/{name}")])
        .stderr(Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

fn gh_no_pr_script() -> &'static str {
    r#"#!/bin/sh
if [ "$1" = "--version" ]; then
  exit 0
fi

if [ "$1 $2" = "pr list" ]; then
  echo '[]'
  exit 0
fi

if [ "$1 $2" = "pr create" ]; then
  echo 'https://example.com/pr/1'
  exit 0
fi

if [ "$1 $2" = "api graphql" ]; then
  echo 'false'
  exit 0
fi

if [ "$1 $2" = "pr view" ]; then
  echo 'https://example.com/pr/1'
  exit 0
fi

if [ "$1 $2" = "pr merge" ]; then
  exit 0
fi

exit 0
"#
}

fn noop_open_script() -> &'static str {
    "#!/bin/sh\nexit 0\n"
}

fn gh_land_script(log_path: &str) -> String {
    format!(
        r#"#!/bin/sh
auto_state="{log_path}.auto"
if [ "$1" = "--version" ]; then
  exit 0
fi
echo "$@" >> "{log_path}"

if [ "$1 $2" = "pr list" ]; then
  echo '[]'
  exit 0
fi

if [ "$1 $2" = "pr create" ]; then
  echo "https://example.com/pr/1"
  exit 0
fi

if [ "$1 $2" = "api graphql" ]; then
  if [ -f "$auto_state" ]; then echo 'true'; else echo 'false'; fi
  exit 0
fi

if [ "$1 $2" = "pr view" ]; then
  echo "https://example.com/pr/1"
  exit 0
fi

if [ "$1 $2" = "pr merge" ]; then
  touch "$auto_state"
  exit 0
fi

exit 0
"#
    )
}

fn gh_existing_pr_script(log_path: &str) -> String {
    format!(
        r#"#!/bin/sh
auto_state="{log_path}.auto"
queue_state="{log_path}.queued"
if [ "$1" = "--version" ]; then
  exit 0
fi
echo "$@" >> "{log_path}"
if [ "$1 $2" = "pr list" ]; then
  head="$(git rev-parse HEAD)"
  echo "[{{\"url\":\"https://example.com/pr/912\",\"state\":\"OPEN\",\"isDraft\":false,\"number\":912,\"mergeCommit\":null,\"headRefOid\":\"$head\"}}]"
  exit 0
fi
if [ "$1 $2" = "api graphql" ]; then
  if [ -f "$auto_state" ] || [ -f "$queue_state" ]; then echo 'true'; else echo 'false'; fi
  exit 0
fi
if [ "$1 $2" = "pr view" ]; then
  echo 'https://example.com/pr/912'
  exit 0
fi
if [ "$1 $2 $3 $4" = "pr merge 912 --disable-auto" ]; then
  rm -f "$auto_state" "$queue_state"
  exit 0
fi
if [ "$1 $2" = "pr merge" ]; then
  touch "$auto_state"
  exit 0
fi
exit 0
"#
    )
}

fn gh_ready_failure_script(log_path: &str) -> String {
    format!(
        r#"#!/bin/sh
if [ "$1" = "--version" ]; then
  exit 0
fi
echo "$@" >> "{log_path}"
if [ "$1 $2" = "pr list" ]; then
  echo '[]'
  exit 0
fi
if [ "$1 $2" = "pr create" ]; then
  echo 'https://example.com/pr/1'
  exit 0
fi
if [ "$1 $2" = "pr view" ]; then
  echo 'https://example.com/pr/1'
  exit 0
fi
if [ "$1 $2" = "pr ready" ]; then
  echo 'ready failed' >&2
  exit 1
fi
exit 0
"#
    )
}

fn gh_auto_failure_script(log_path: &str) -> String {
    format!(
        r#"#!/bin/sh
if [ "$1" = "--version" ]; then
  exit 0
fi
echo "$@" >> "{log_path}"
if [ "$1 $2" = "pr list" ]; then
  head="$(git rev-parse HEAD)"
  echo "[{{\"url\":\"https://example.com/pr/912\",\"state\":\"OPEN\",\"isDraft\":false,\"number\":912,\"mergeCommit\":null,\"headRefOid\":\"$head\"}}]"
  exit 0
fi
if [ "$1 $2" = "api graphql" ]; then
  echo 'false'
  exit 0
fi
if [ "$1 $2" = "pr view" ]; then
  echo 'https://example.com/pr/912'
  exit 0
fi
if [ "$1 $2" = "pr merge" ]; then
  echo 'auto arm failed' >&2
  exit 1
fi
exit 0
"#
    )
}

fn agent_script() -> &'static str {
    "#!/bin/sh\necho '{\"title\":\"generated title\",\"body\":\"generated body\"}'\nexit 0\n"
}

#[test]
fn land_local_squash_merges_to_main() {
    let _env = EnvGuard::new(&[]);
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, "feature");

    land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: true,
            create_pr: false,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: None,
            pr_body: None,
            agent: None,
        },
        &NullProgress,
    )
    .expect("land");

    let output = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(repo.path())
        .output()
        .expect("git rev-parse");
    let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
    assert_eq!(branch, "main");
    assert!(!local_branch_exists(&repo, "feature"));
    assert!(repo.path().join("feature.txt").exists());
}

#[test]
fn land_preserves_main_on_failure() {
    let _env = EnvGuard::new(&[]);
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("conflict.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, "feature");

    repo.checkout("main");
    repo.create_file("conflict.txt", "main");
    repo.stage_all();
    repo.commit("main work");
    repo.push();
    let main_head = repo.head_sha();

    repo.checkout("feature");
    let result = land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: true,
            create_pr: false,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: None,
            pr_body: None,
            agent: None,
        },
        &NullProgress,
    );

    assert!(result.is_err());
    let _ = Command::new("git")
        .args(["rebase", "--abort"])
        .current_dir(repo.path())
        .status();
    let _ = Command::new("git")
        .args(["reset", "--hard"])
        .current_dir(repo.path())
        .status();
    repo.checkout("main");
    assert_eq!(repo.head_sha(), main_head);
}

#[test]
fn land_cleans_up_remote_branch() {
    let _env = EnvGuard::new(&[]);
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, "feature");

    land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: true,
            create_pr: false,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: None,
            pr_body: None,
            agent: None,
        },
        &NullProgress,
    )
    .expect("land");

    assert!(!remote_branch_exists(&repo, "feature"));
}

#[test]
fn land_clears_scratch_and_preserves_gitkeep() {
    let _env = EnvGuard::new(&[]);
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, "feature");

    let scratch = repo.path().join("scratch");
    fs::create_dir_all(scratch.join("nested")).expect("create nested scratch dir");
    fs::write(scratch.join("notes.md"), "review notes").expect("write scratch note");
    fs::write(scratch.join("nested").join("todo.md"), "todo").expect("write nested scratch note");
    let status = Command::new("git")
        .args(["add", "scratch"])
        .current_dir(repo.path())
        .status()
        .expect("git add scratch");
    assert!(status.success(), "git add scratch should succeed");
    let status = Command::new("git")
        .args(["commit", "-m", "add scratch docs"])
        .current_dir(repo.path())
        .status()
        .expect("git commit scratch");
    assert!(status.success(), "git commit scratch should succeed");

    land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: true,
            create_pr: false,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: None,
            pr_body: None,
            agent: None,
        },
        &NullProgress,
    )
    .expect("land should clear scratch");

    let scratch_entries = fs::read_dir(repo.path().join("scratch"))
        .expect("read scratch after land")
        .map(|entry| {
            entry
                .expect("scratch entry")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .collect::<Vec<_>>();
    assert_eq!(scratch_entries, vec![".gitkeep"]);
}

#[test]
fn land_collapses_checkpoint_history_and_pushes_the_final_tree_once() {
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("first.txt", "first");
    repo.stage_all();
    repo.commit("checkpoint: first slice");
    repo.create_file("second.txt", "second");
    repo.stage_all();
    repo.commit("feature behavior");
    let scratch = repo.path().join("scratch");
    fs::create_dir_all(&scratch).expect("create scratch");
    fs::write(scratch.join("working.md"), "discard me").expect("write scratch");
    repo.stage_all();
    repo.commit("checkpoint: notes");
    push_branch(&repo, "feature");

    let push_log = repo.path().join("push.log");
    let hook = repo.bare_path().join("hooks/update");
    fs::write(
        &hook,
        format!(
            "#!/bin/sh\nprintf '%s\\n' \"$1\" >> '{}'\n",
            push_log.display()
        ),
    )
    .expect("write update hook");
    let mut permissions = fs::metadata(&hook).expect("hook metadata").permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&hook, permissions).expect("make hook executable");

    let gh_log = repo.bare_path().join("gh.log");
    let script = gh_land_script(gh_log.to_string_lossy().as_ref());
    let _env = EnvGuard::new(&[("gh", script.as_str()), ("open", noop_open_script())]);
    land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: true,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("collapsed change".to_string()),
            pr_body: Some("proof".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("land collapsed history");

    let output = |args: &[&str]| {
        let result = Command::new("git")
            .args(args)
            .current_dir(repo.path())
            .output()
            .expect("run git proof");
        assert!(result.status.success(), "git {:?} failed", args);
        String::from_utf8_lossy(&result.stdout).trim().to_string()
    };
    assert_eq!(output(&["rev-list", "--count", "origin/main..HEAD"]), "1");
    assert_eq!(
        output(&["rev-parse", "HEAD"]),
        Command::new("git")
            .arg("--git-dir")
            .arg(repo.bare_path())
            .args(["rev-parse", "refs/heads/feature"])
            .output()
            .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
            .expect("read remote head")
    );
    assert!(repo.path().join("first.txt").exists());
    assert!(repo.path().join("second.txt").exists());
    assert!(!repo.path().join("scratch/working.md").exists());
    assert_eq!(
        fs::read_to_string(&push_log)
            .expect("one final push receipt")
            .lines()
            .collect::<Vec<_>>(),
        vec!["refs/heads/feature"],
        "submit/land must push only the verified final head"
    );
    assert!(
        !output(&[
            "for-each-ref",
            "--format=%(refname)",
            "refs/loopflow/recovery/"
        ])
        .is_empty(),
        "the pre-collapse head must remain recoverable"
    );
}

#[test]
fn land_refuses_when_clearing_scratch_leaves_no_authored_change() {
    let repo = TestRepo::new();
    repo.create_file("scratch/.gitkeep", "");
    repo.stage_all();
    repo.commit("track scratch");
    repo.push();
    repo.create_branch("feature");
    repo.create_file("scratch/notes.md", "notes only");
    repo.stage_all();
    repo.commit("checkpoint: notes");
    push_branch(&repo, "feature");
    let remote_head = repo.head_sha();
    let gh_log = repo.bare_path().join("gh.log");
    let script = gh_land_script(gh_log.to_string_lossy().as_ref());
    let _env = EnvGuard::new(&[("gh", script.as_str())]);

    let result = land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: true,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("notes only".to_string()),
            pr_body: Some("proof".to_string()),
            agent: None,
        },
        &NullProgress,
    );

    assert!(
        matches!(result, Err(OpsError::Message(ref message)) if message.contains("no authored changes remain")),
        "scratch-only finalization must refuse actionably: {result:?}"
    );
    assert_eq!(
        Command::new("git")
            .arg("--git-dir")
            .arg(repo.bare_path())
            .args(["rev-parse", "refs/heads/feature"])
            .output()
            .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
            .expect("read untouched remote"),
        remote_head,
        "empty finalization must not push"
    );
    assert!(
        !fs::read_to_string(gh_log)
            .unwrap_or_default()
            .contains("pr create"),
        "empty finalization must not create a PR"
    );
}

#[test]
fn land_does_not_push_when_target_already_contains_the_authored_patch() {
    let repo = TestRepo::new();
    repo.create_file("scratch/.gitkeep", "");
    repo.create_file("shared.txt", "base\n");
    repo.stage_all();
    repo.commit("shared base");
    repo.push();
    repo.create_branch("feature");
    repo.create_file("shared.txt", "same final content\n");
    repo.stage_all();
    repo.commit("feature patch");
    push_branch(&repo, "feature");
    let remote_feature = repo.head_sha();

    repo.checkout("main");
    repo.create_file("shared.txt", "same final content\n");
    repo.stage_all();
    repo.commit("upstream equivalent patch");
    repo.push();
    repo.checkout("feature");

    let gh_log = repo.bare_path().join("gh.log");
    let script = gh_land_script(gh_log.to_string_lossy().as_ref());
    let _env = EnvGuard::new(&[("gh", script.as_str()), ("open", noop_open_script())]);
    let result = land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: true,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("already upstream".to_string()),
            pr_body: Some("proof".to_string()),
            agent: None,
        },
        &NullProgress,
    );

    assert!(
        matches!(result, Err(OpsError::Message(ref message)) if message.contains("expected" ) && message.contains("empty")),
        "an empty final replay must fail before push: {result:?}"
    );
    assert_eq!(
        Command::new("git")
            .arg("--git-dir")
            .arg(repo.bare_path())
            .args(["rev-parse", "refs/heads/feature"])
            .output()
            .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
            .expect("read remote feature"),
        remote_feature,
        "the remote branch must keep its last authored head"
    );
    let gh_calls = fs::read_to_string(gh_log).unwrap_or_default();
    assert!(
        !gh_calls.contains("pr create")
            && !gh_calls.contains("pr edit")
            && !gh_calls.contains("pr ready")
            && !gh_calls.contains("pr merge"),
        "GitHub must not be mutated for an empty replay: {gh_calls}"
    );
}

#[test]
fn land_missing_pr_error_includes_branch_name() {
    let home = tempfile::TempDir::new().expect("temp home");
    let _env = EnvGuard::with_home(
        &[
            ("gh", gh_no_pr_script()),
            ("codex", agent_script()),
            ("open", noop_open_script()),
        ],
        Some(home.path()),
    );
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, "feature");

    let result = land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: false,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("cached title".to_string()),
            pr_body: Some("cached body".to_string()),
            agent: None,
        },
        &NullProgress,
    );

    let Err(OpsError::Message(message)) = result else {
        panic!("expected missing PR message");
    };
    assert!(message.contains("no open PR found for branch 'feature'"));
}

#[test]
fn land_uses_cached_pr_copy_when_available() {
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, "feature");

    let scratch = repo.path().join("scratch");
    fs::create_dir_all(&scratch).expect("create scratch");
    fs::write(scratch.join("pr-title.txt"), "cached title").expect("write title");
    fs::write(scratch.join("pr-body.md"), "cached body").expect("write body");
    fs::write(scratch.join(".pr-copy-ref"), repo.head_sha()).expect("write ref");

    let log_path = repo.bare_path().join("gh.log");
    let script = gh_land_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::new(&[("gh", script.as_str()), ("open", noop_open_script())]);

    land(
        repo.path(),
        &LandOptions {
            strict: false,
            local: false,
            create_pr: true,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: None,
            pr_body: None,
            agent: None,
        },
        &NullProgress,
    )
    .expect("land with cached copy");

    let log = fs::read_to_string(&log_path).expect("read gh log");
    assert!(log.contains("--title cached title"));
    assert!(log.contains("--body cached body"));
}

#[test]
fn submit_and_land_make_no_presentation_attempt() {
    let marker_dir = tempfile::TempDir::new().expect("marker dir");
    let marker = marker_dir.path().join("present.log");
    let open_script = counting_open_script(&marker);

    // submit prepares the PR for a human to merge — and presents nothing.
    let submit_repo = TestRepo::new();
    submit_repo.create_branch("feature");
    submit_repo.create_file("feature.txt", "feature");
    submit_repo.stage_all();
    submit_repo.commit("feature work");
    push_branch(&submit_repo, "feature");
    let submit_log = submit_repo.bare_path().join("gh.log");
    let submit_script = gh_land_script(submit_log.to_string_lossy().as_ref());
    {
        let _env = EnvGuard::new(&[
            ("gh", submit_script.as_str()),
            ("open", open_script.as_str()),
            ("xdg-open", open_script.as_str()),
        ]);
        submit(
            submit_repo.path(),
            &LandOptions {
                strict: true,
                local: false,
                create_pr: true,
                complete: false,
                next_slug: None,
                worktree: None,
                commit_message: None,
                pr_title: Some("test title".to_string()),
                pr_body: Some("test body".to_string()),
                agent: None,
            },
            &NullProgress,
        )
        .expect("submit");
    }
    assert_eq!(
        presentation_attempts(&marker),
        0,
        "submit must open no review surface"
    );

    // land arms auto-merge and walks away — also presenting nothing.
    let land_repo = TestRepo::new();
    land_repo.create_branch("feature");
    land_repo.create_file("feature.txt", "feature");
    land_repo.stage_all();
    land_repo.commit("feature work");
    push_branch(&land_repo, "feature");
    let land_log = land_repo.bare_path().join("gh.log");
    let land_script = gh_land_script(land_log.to_string_lossy().as_ref());
    {
        let _env = EnvGuard::new(&[
            ("gh", land_script.as_str()),
            ("open", open_script.as_str()),
            ("xdg-open", open_script.as_str()),
        ]);
        land(
            land_repo.path(),
            &LandOptions {
                strict: true,
                local: false,
                create_pr: true,
                complete: false,
                next_slug: None,
                worktree: None,
                commit_message: None,
                pr_title: Some("test title".to_string()),
                pr_body: Some("test body".to_string()),
                agent: None,
            },
            &NullProgress,
        )
        .expect("land");
    }
    assert_eq!(
        presentation_attempts(&marker),
        0,
        "land must open no review surface"
    );
}

#[test]
fn submit_assigns_reviewer_and_skips_auto_merge() {
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, "feature");

    let log_path = repo.bare_path().join("gh.log");
    let script = gh_land_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::new(&[("gh", script.as_str()), ("open", noop_open_script())]);

    submit(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: true,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("test title".to_string()),
            pr_body: Some("test body".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("submit");

    // submit prepares but never merges — that click is the human's.
    let log = fs::read_to_string(&log_path).expect("read gh log");
    // Assigns the PR to the current user for a required, manual merge.
    assert!(log.contains("pr edit --add-assignee @me"));
    // Marks the PR ready, but does NOT arm auto-merge.
    assert!(log.contains("pr ready"));
    assert!(!log.contains("merge --auto"));
}

#[test]
fn submit_surfaces_ready_failure_before_assignment() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();
    let branch = "jack/task-ready-failure";
    repo.create_branch(branch);
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, branch);

    let log_path = repo.bare_path().join("gh.log");
    let script = gh_ready_failure_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );
    let task = register_task(home.path(), repo.path(), branch, &base);

    let result = submit(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: true,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("test title".to_string()),
            pr_body: Some("test body".to_string()),
            agent: None,
        },
        &NullProgress,
    );

    assert!(matches!(result, Err(OpsError::CommandFailed { .. })));
    let runtime = tokio::runtime::Runtime::new().expect("task runtime");
    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert!(
        pr.merge_request().is_none(),
        "failed remote finalization must not leave a false settlement owner"
    );
    let log = fs::read_to_string(&log_path).expect("read gh log");
    assert!(log.contains("pr ready"));
    assert!(!log.contains("pr edit --add-assignee @me"));
}

#[test]
fn land_clears_the_durable_request_when_auto_arm_fails() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();
    let branch = "jack/task-auto-failure";
    repo.create_branch(branch);
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, branch);

    let log_path = home.path().join("gh.log");
    let script = gh_auto_failure_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );
    let task = register_task(home.path(), repo.path(), branch, &base);

    let result = land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: false,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("test title".to_string()),
            pr_body: Some("test body".to_string()),
            agent: None,
        },
        &NullProgress,
    );

    assert!(matches!(result, Err(OpsError::CommandFailed { .. })));
    let runtime = tokio::runtime::Runtime::new().expect("task runtime");
    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert!(
        pr.merge_request().is_none(),
        "a failed Auto handoff must not leave GitHub as a false owner"
    );
    let log = fs::read_to_string(log_path).expect("read gh log");
    assert!(log.contains("pr merge 912 --squash --auto --match-head-commit"));
}

#[test]
fn latest_land_disposition_wins_before_merge() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let log_path = home.path().join("gh.log");
    let script = gh_existing_pr_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );
    let base = repo.head_sha();
    let branch = "jack/task-pr-proof";
    repo.create_branch(branch);
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    repo.push_new_branch(branch);
    let task = register_task(home.path(), repo.path(), branch, &base);
    fs::write(format!("{}.auto", log_path.display()), "armed externally")
        .expect("seed external auto-merge state");

    land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: false,
            complete: true,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("test title".to_string()),
            pr_body: Some("test body".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("land as completing PR");
    let head = repo.head_sha();

    create_or_update_pr(
        repo.path(),
        &PrOptions {
            title: Some("refresh published PR".to_string()),
            body: Some("same head".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("refresh same-head publication");

    let runtime = tokio::runtime::Runtime::new().expect("read task runtime");
    let preserved = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    let preserved = preserved.merge_request().expect("preserved merge request");
    assert_eq!(preserved.after_merge, AfterMerge::CompleteTask);
    assert_eq!(preserved.head_sha, head);

    let hook = repo.bare_path().join("hooks/pre-receive");
    fs::write(
        &hook,
        format!(
            "#!/bin/sh\necho git-push >> '{}'\ncat >/dev/null\n",
            log_path.display()
        ),
    )
    .expect("write remote push hook");
    let mut permissions = fs::metadata(&hook)
        .expect("read hook metadata")
        .permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&hook, permissions).expect("make push hook executable");

    land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: false,
            complete: false,
            next_slug: Some("follow-up-proof".to_string()),
            worktree: None,
            commit_message: None,
            pr_title: Some("test title".to_string()),
            pr_body: Some("test body".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("revise land disposition");
    let revised_head = repo.head_sha();

    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert_eq!(pr.phase(), PrPhase::Open);
    let publication = pr.publication.expect("publication");
    assert_eq!(publication.github.map(|pr| pr.number), Some(912));
    let merge = publication.merge.expect("explicit merge request");
    assert_eq!(merge.mode, PrMergeMode::Auto);
    assert_eq!(merge.head_sha, revised_head);
    assert_eq!(merge.after_merge, AfterMerge::ContinueTask);
    assert_eq!(merge.next_slug.as_deref(), Some("follow-up-proof"));
    let log = fs::read_to_string(&log_path).expect("read gh log");
    assert!(log.contains(&format!(
        "pr merge 912 --squash --auto --match-head-commit {revised_head}"
    )));
    let first_disable = log
        .find("pr merge 912 --disable-auto")
        .expect("pre-existing Auto is replaced");
    let first_arm = log
        .find("pr merge 912 --squash --auto --match-head-commit")
        .expect("land arms the exact prepared head");
    assert!(
        first_disable < first_arm,
        "external Auto must be replaced by the exact-head command:\n{log}"
    );
    let disable = log
        .rfind("pr merge 912 --disable-auto")
        .expect("second land revokes prior Auto request");
    if revised_head != head {
        let push = log
            .find("git-push")
            .expect("a changed head is pushed by the second land");
        assert!(
            disable < push,
            "Auto intent must be revoked before the LF-owned head-changing push:\n{log}"
        );
    } else {
        assert!(
            !log.contains("git-push"),
            "an unchanged head needs no replacement push:\n{log}"
        );
    }

    submit(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: false,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("test title".to_string()),
            pr_body: Some("test body".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("replace auto merge with user merge request");
    let submitted_head = repo.head_sha();

    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    let request = pr.merge_request().expect("user merge request");
    assert_eq!(request.mode, PrMergeMode::User);
    assert_eq!(request.head_sha, submitted_head);
    let log = fs::read_to_string(&log_path).expect("read gh log");
    assert!(log.contains("pr merge 912 --disable-auto"));
    assert!(log.contains("pr edit --add-assignee @me"));
}

#[test]
fn repeated_identical_land_preserves_the_armed_task_request() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let log_path = home.path().join("gh.log");
    let script = gh_existing_pr_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );
    let base = repo.head_sha();
    let branch = "jack/replay-safe-land";
    repo.create_branch(branch);
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    repo.push_new_branch(branch);
    let task = register_task(home.path(), repo.path(), branch, &base);
    let options = LandOptions {
        strict: true,
        local: false,
        create_pr: false,
        complete: true,
        next_slug: None,
        worktree: None,
        commit_message: None,
        pr_title: Some("test title".to_string()),
        pr_body: Some("test body".to_string()),
        agent: None,
    };

    land(repo.path(), &options, &NullProgress).expect("first land arms the request");
    let armed_head = repo.head_sha();
    let first_log = fs::read_to_string(&log_path).expect("read first gh log");
    let first_merge_calls = first_log
        .lines()
        .filter(|line| line.starts_with("pr merge"))
        .count();

    land(repo.path(), &options, &NullProgress).expect("identical land is replay-safe");

    assert_eq!(
        repo.head_sha(),
        armed_head,
        "replay must not rewrite the head"
    );
    let pr = tokio::runtime::Runtime::new()
        .expect("task runtime")
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    let request = pr.merge_request().expect("preserved merge request");
    assert_eq!(request.mode, PrMergeMode::Auto);
    assert_eq!(request.after_merge, AfterMerge::CompleteTask);
    assert_eq!(request.head_sha, armed_head);
    let replay_log = fs::read_to_string(&log_path).expect("read replay gh log");
    assert_eq!(
        replay_log
            .lines()
            .filter(|line| line.starts_with("pr merge"))
            .count(),
        first_merge_calls,
        "replay must neither disable nor arm auto-merge again:\n{replay_log}"
    );
    assert!(!replay_log.contains("--disable-auto"));
}

#[test]
fn non_task_land_leaves_the_merge_queue_before_pushing_a_new_head() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let log_path = home.path().join("gh.log");
    let script = gh_existing_pr_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );
    let branch = "jack/wave-repair";
    repo.create_branch(branch);
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    repo.push_new_branch(branch);
    fs::write(format!("{}.queued", log_path.display()), "queued")
        .expect("seed remote auto-merge state");
    let hook = repo.bare_path().join("hooks/pre-receive");
    fs::write(
        &hook,
        format!(
            "#!/bin/sh\necho git-push >> '{}'\ncat >/dev/null\n",
            log_path.display()
        ),
    )
    .expect("write remote push hook");
    let mut permissions = fs::metadata(&hook)
        .expect("read hook metadata")
        .permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&hook, permissions).expect("make push hook executable");

    land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: false,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("test title".to_string()),
            pr_body: Some("test body".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("non-Task land");

    let log = fs::read_to_string(&log_path).expect("read gh log");
    let disable = log
        .find("pr merge 912 --disable-auto")
        .expect("queued Auto is revoked");
    let push = log.find("git-push").expect("prepared head is pushed");
    let arm = log
        .rfind("pr merge 912 --squash --auto --match-head-commit")
        .expect("prepared head is re-armed");
    assert!(
        disable < push && push < arm,
        "unexpected settlement order:\n{log}"
    );
}

#[test]
fn submit_does_not_rotate_worktree() {
    let repo = TestRepo::new();
    let log_path = repo.bare_path().join("gh.log");
    let script = gh_land_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::new(&[("gh", script.as_str()), ("open", noop_open_script())]);

    let worktree = create_named_worktree(repo.path(), "sub", None, false).expect("create worktree");
    fs::write(worktree.path.join("feature.txt"), "feature").expect("write feature file");
    let status = Command::new("git")
        .args(["add", "."])
        .current_dir(&worktree.path)
        .status()
        .expect("git add");
    assert!(status.success(), "git add should succeed");
    let status = Command::new("git")
        .args(["commit", "-m", "feature work"])
        .current_dir(&worktree.path)
        .status()
        .expect("git commit");
    assert!(status.success(), "git commit should succeed");
    push_branch(&repo, &worktree.branch);

    submit(
        &worktree.path,
        &LandOptions {
            strict: true,
            local: false,
            create_pr: true,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: Some("test title".to_string()),
            pr_body: Some("test body".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("submit from worktree");

    // The worktree stays put — no preserve, no next-item rotation.
    assert!(worktree.path.exists());
}

#[test]
fn land_generates_copy_when_cached_pr_copy_is_stale() {
    let home = tempfile::TempDir::new().expect("temp home");
    let _env = EnvGuard::with_home(
        &[
            ("gh", gh_no_pr_script()),
            ("codex", agent_script()),
            ("open", noop_open_script()),
        ],
        Some(home.path()),
    );
    let repo = TestRepo::new();
    repo.create_branch("feature");
    repo.create_file("feature.txt", "feature");
    repo.stage_all();
    repo.commit("feature work");
    push_branch(&repo, "feature");

    let scratch = repo.path().join("scratch");
    fs::create_dir_all(&scratch).expect("create scratch");
    fs::write(scratch.join("pr-title.txt"), "stale title").expect("write title");
    fs::write(scratch.join("pr-body.md"), "stale body").expect("write body");
    fs::write(
        scratch.join(".pr-copy-ref"),
        "0000000000000000000000000000000000000000",
    )
    .expect("write stale ref");
    let status = Command::new("git")
        .args(["add", "scratch"])
        .current_dir(repo.path())
        .status()
        .expect("git add scratch");
    assert!(status.success(), "git add scratch should succeed");
    let status = Command::new("git")
        .args(["commit", "-m", "add stale gate copy"])
        .current_dir(repo.path())
        .status()
        .expect("git commit scratch");
    assert!(status.success(), "git commit scratch should succeed");

    land(
        repo.path(),
        &LandOptions {
            strict: true,
            local: false,
            create_pr: true,
            complete: false,
            next_slug: None,
            worktree: None,
            commit_message: None,
            pr_title: None,
            pr_body: None,
            agent: None,
        },
        &NullProgress,
    )
    .expect("land with stale cached copy should regenerate");
}

#[test]
fn lf_pr_land_publishes_without_create_flag_and_leaves_worktree_in_place() {
    let repo = TestRepo::new();
    let log_path = repo.bare_path().join("gh.log");
    let script = gh_land_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::new(&[("gh", script.as_str()), ("open", noop_open_script())]);

    let worktree = repo.create_named_worktree("land");
    let branch = "land";

    fs::write(worktree.join("feature.txt"), "feature").expect("write feature file");
    let status = Command::new("git")
        .args(["add", "."])
        .current_dir(&worktree)
        .status()
        .expect("git add");
    assert!(status.success(), "git add should succeed");
    let status = Command::new("git")
        .args(["commit", "-m", "feature work"])
        .current_dir(&worktree)
        .status()
        .expect("git commit");
    assert!(status.success(), "git commit should succeed");
    assert!(
        !remote_branch_exists(&repo, branch),
        "the test must begin before publication"
    );

    let directive_path = repo.path().join("directive.txt");
    let status = Command::new(env!("CARGO_BIN_EXE_lf"))
        .args([
            "pr",
            "land",
            "--strict",
            "--title",
            "test title",
            "--body",
            "test body",
        ])
        .current_dir(&worktree)
        .env("LOOPFLOW_DIRECTIVE_FILE", &directive_path)
        .status()
        .expect("run lf pr land");
    assert!(status.success(), "lf pr land should succeed");
    assert!(
        remote_branch_exists(&repo, branch),
        "lf pr land should push its branch"
    );
    let gh_log = fs::read_to_string(&log_path).expect("read gh log");
    assert!(
        gh_log.lines().any(|line| line.starts_with("pr create ")),
        "lf pr land should create its missing PR, got: {gh_log}"
    );

    // The wave home is permanent: land never rotates the worktree or cds away.
    assert!(
        worktree.exists(),
        "worktree should stay in place after land"
    );
    let directive = fs::read_to_string(&directive_path).unwrap_or_default();
    assert!(
        !directive.contains("cd "),
        "land should not emit a cd directive, got: {directive}"
    );
}