loopflow 0.12.13

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
//! End-to-end proof for W2-138 and W2-255 — every Task PR contains only that
//! Task's work, and ambiguous ancestry refusal is actionable.
//!
//! The verdict logic lives in `ops::task::verify_task_pr_range` and is unit
//! tested there. These tests drive the *real* `submit`/`land` publication path
//! over a bare-origin fixture to prove the observable acceptance property the
//! design demands: a contaminated range is refused **before any push or
//! `gh pr`**, and a stale serial base heals so GitHub's range, `lf task
//! changes`, and the recorded `base_commit` agree. W2-255 extends the proof
//! matrix to divergent ancestry (both sides named), squash-merged parents,
//! no-remote refusal, and serial rotation.

mod support;

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

use loopflow::ops::{
    create_or_update_pr, land, rebase_with_recovery, submit, LandOptions, NullProgress, PrOptions,
    RebaseOptions,
};
use loopflow::task::{
    AfterMerge, GithubPr, PrMergeMode, PrMergeRequest, PrPresentation, PrPublication,
};
use loopflow_test_support::TestRepo;
use support::{register_task, EnvGuard};
use time::OffsetDateTime;

fn land_options(create_pr: bool, pr_title: &str) -> LandOptions {
    LandOptions {
        strict: true,
        local: false,
        create_pr,
        complete: false,
        next_slug: None,
        worktree: None,
        commit_message: None,
        pr_title: Some(pr_title.to_string()),
        pr_body: Some("proof body".to_string()),
        agent: None,
    }
}

/// A `gh` that records every non-`--version` invocation to `log_path` and
/// reports an already-open PR, so `land` finds a PR to finalize without
/// creating one.
fn gh_open_pr_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
  head=$(git rev-parse HEAD)
  printf '[{{"url":"https://example.com/pr/925","state":"OPEN","isDraft":false,"number":925,"mergeCommit":null,"headRefOid":"%s"}}]\n' "$head"
  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/925'
  exit 0
fi
if [ "$1 $2" = "pr merge" ]; then
  touch "$auto_state"
  exit 0
fi
exit 0
"#
    )
}

fn gh_auto_enabled_script(log_path: &str) -> String {
    format!(
        r#"#!/bin/sh
if [ "$1" = "--version" ]; then
  exit 0
fi
echo "$@" >> "{log_path}"
if [ "$1 $2" = "api graphql" ]; then
  echo 'true'
  exit 0
fi
if [ "$1 $2 $3 $4" = "pr merge 912 --disable-auto" ]; then
  exit 0
fi
exit 0
"#
    )
}

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

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 git_out(repo: &TestRepo, args: &[&str]) -> String {
    let output = Command::new("git")
        .current_dir(repo.path())
        .args(args)
        .output()
        .expect("run git");
    assert!(
        output.status.success(),
        "git {} failed: {}",
        args.join(" "),
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

/// The #877/#882 acceptance case: the recorded base carries a foreign,
/// unpushed canonical-main commit (M < B). `submit` must refuse, name the
/// foreign commit and the recovery, and touch neither the remote nor `gh pr`.
#[test]
fn submit_refuses_a_contaminated_range_before_any_push() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new(); // origin/main = P (pushed)

    let log_path = home.path().join("gh.log");
    let script = gh_open_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(),
    );

    // A foreign commit advances local main ahead of origin and is never pushed —
    // the branch cut from it inherits off-origin ancestry.
    repo.create_file("foreign.txt", "not this task's work\n");
    repo.stage_all();
    repo.commit("foreign canonical-main commit");
    let contaminated_base = repo.head_sha();

    let branch = "jack/contaminated";
    repo.create_branch(branch); // cut from the contaminated base
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");
    // Deliberately NOT pushed: the refusal must precede the first push.

    register_task(home.path(), repo.path(), branch, &contaminated_base);

    let err = submit(
        repo.path(),
        &land_options(true, "contaminated"),
        &NullProgress,
    )
    .expect_err("contaminated range must refuse");
    let message = err.to_string();
    assert!(
        message.contains("contaminated"),
        "expected contamination refusal, got: {message}"
    );
    assert!(
        message.contains("foreign canonical-main commit"),
        "refusal must name the foreign commit, got: {message}"
    );
    assert!(
        message.contains("rebase --onto"),
        "refusal must print the recovery action, got: {message}"
    );

    // The proof: no GitHub side effect happened before the refusal.
    assert!(
        !remote_branch_exists(&repo, branch),
        "the branch must never reach the remote when the range is refused"
    );
    let log = fs::read_to_string(&log_path).unwrap_or_default();
    assert!(
        !log.contains("pr create") && !log.contains("pr edit") && !log.contains("pr ready"),
        "no gh PR mutation may be issued before refusal, got log:\n{log}"
    );
}

/// The serial / dogfood shape: a continuation PR's recorded base sits behind the
/// current `origin/main` because a sibling landed. `land` rebases, heals the
/// base to the true fork point, and publishes a minimal range — proving the
/// three views (recorded base, `lf task changes`, GitHub range) agree.
#[test]
fn serial_pr_heals_stale_base_and_aligns_the_three_views() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new(); // origin/main = P
    let stale_base = repo.head_sha(); // the base recorded at placement time

    let log_path = home.path().join("gh.log");
    let script = gh_open_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(),
    );

    // The serial PR's own commit, cut from the (soon stale) base and pushed.
    let branch = "jack/serial-pr-proof";
    repo.create_branch(branch);
    repo.create_file("task.txt", "serial PR work\n");
    repo.stage_all();
    repo.commit("serial PR commit");
    repo.push_new_branch(branch);

    // A sibling lands: origin/main advances past the recorded base.
    repo.checkout("main");
    repo.create_file("upstream.txt", "landed upstream\n");
    repo.stage_all();
    repo.commit("upstream advance");
    repo.push();
    let advanced = repo.head_sha();
    repo.checkout(branch);

    let task = register_task(home.path(), repo.path(), branch, &stale_base);

    land(
        repo.path(),
        &land_options(false, "serial pr"),
        &NullProgress,
    )
    .expect("stale serial base heals and lands");

    // The recorded base healed forward to the current origin tip.
    let runtime = tokio::runtime::Runtime::new().expect("read task runtime");
    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert_eq!(
        pr.base_commit, advanced,
        "the stale serial base must heal forward to origin/main"
    );

    // The three views agree. The recorded base is exactly the fork point
    // GitHub would compute for the PR range — proving `lf task changes`
    // (base..HEAD), the GitHub range (merge-base(origin/main, HEAD)..HEAD), and
    // the recorded base all describe the same commits.
    let github_fork_point = git_out(&repo, &["merge-base", "origin/main", "HEAD"]);
    assert_eq!(
        pr.base_commit, github_fork_point,
        "recorded base must equal GitHub's range fork point"
    );

    // The already-merged upstream commit is dropped from the range, while the
    // Task's own work is included — no manual commit dropping.
    let range = format!("{}..HEAD", pr.base_commit);
    let range_commits = git_out(&repo, &["log", "--oneline", "--no-decorate", &range]);
    assert!(
        !range_commits.contains("upstream advance"),
        "the merged upstream commit must be excluded from the range, got:\n{range_commits}"
    );
    assert_eq!(
        range_commits.lines().count(),
        1,
        "final range is one commit"
    );
    assert!(
        range_commits.contains("lf land: collapse authored history"),
        "the Task's authored tree must be represented by the final commit, got:\n{range_commits}"
    );
    let files = git_out(&repo, &["diff", "--name-only", &range]);
    assert!(
        files.contains("task.txt") && !files.contains("upstream.txt"),
        "the aligned range must show this Task's file and never the upstream file, got:\n{files}"
    );
}

#[test]
fn failed_rebase_push_does_not_advance_the_recorded_task_base() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let stale_base = repo.head_sha();
    let _env = EnvGuard::with_lf_home(&[], home.path());

    let branch = "jack/rejected-rebase-push";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");
    repo.push_new_branch(branch);

    repo.checkout("main");
    repo.create_file("upstream.txt", "landed upstream\n");
    repo.stage_all();
    repo.commit("upstream advance");
    repo.push();
    let target = repo.head_sha();
    repo.checkout(branch);

    let task = register_task(home.path(), repo.path(), branch, &stale_base);
    let hook = repo.bare_path().join("hooks/pre-receive");
    fs::write(
        &hook,
        format!(
            "#!/bin/sh\nwhile read old new ref; do\n  if [ \"$ref\" = \"refs/heads/{branch}\" ]; then exit 1; fi\ndone\nexit 0\n"
        ),
    )
    .expect("write rejecting 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 error = rebase_with_recovery(
        repo.path(),
        &RebaseOptions {
            onto: "origin/main".to_string(),
            push: true,
            fork_base: None,
        },
        &NullProgress,
    )
    .expect_err("the remote must reject the rewritten branch");
    assert!(
        error.to_string().contains("git push --force-with-lease"),
        "expected the push failure, got: {error}"
    );
    assert!(
        loopflow::engine::git::is_ancestor(repo.path(), &target, &repo.head_sha()).unwrap(),
        "the local rebase must complete before the rejected push"
    );

    let runtime = tokio::runtime::Runtime::new().expect("read task runtime");
    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert_eq!(
        pr.base_commit, stale_base,
        "a failed remote postcondition must not advance durable Task metadata"
    );
}

#[test]
fn rebase_revokes_auto_before_force_pushing_a_new_task_head() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let stale_base = repo.head_sha();
    let log_path = home.path().join("rebase.log");
    let script = gh_auto_enabled_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(&[("gh", script.as_str())], home.path());

    let branch = "jack/rebase-revokes-auto";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");
    repo.push_new_branch(branch);
    let task = register_task(home.path(), repo.path(), branch, &stale_base);
    let old_head = repo.head_sha();
    let now = OffsetDateTime::now_utc();
    let mut pr = task.pr.clone();
    pr.publication = Some(PrPublication {
        requested_at: now,
        presentation: Some(PrPresentation {
            title: "Rebase proof".to_string(),
            body: "Reviewer context".to_string(),
            head_sha: old_head.clone(),
        }),
        github: Some(GithubPr {
            number: 912,
            url: "https://example.com/pr/912".to_string(),
            head_sha: Some(old_head.clone()),
        }),
        merge: Some(PrMergeRequest {
            mode: PrMergeMode::Auto,
            requested_at: now,
            head_sha: old_head,
            after_merge: AfterMerge::CompleteTask,
            next_slug: None,
        }),
    });
    let runtime = tokio::runtime::Runtime::new().expect("task runtime");
    runtime
        .block_on(task.store.update_task_pr(&pr))
        .expect("store Auto request");

    repo.checkout("main");
    repo.create_file("upstream.txt", "upstream advance\n");
    repo.stage_all();
    repo.commit("upstream advance");
    repo.push();
    repo.checkout(branch);

    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 push hook");
    let mut permissions = fs::metadata(&hook).expect("hook metadata").permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&hook, permissions).expect("make hook executable");

    rebase_with_recovery(
        repo.path(),
        &RebaseOptions {
            onto: "origin/main".to_string(),
            push: true,
            fork_base: None,
        },
        &NullProgress,
    )
    .expect("rebase and push Task head");

    let persisted = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert!(persisted.merge_request().is_none());
    let log = fs::read_to_string(log_path).expect("read operation log");
    let disable = log
        .find("pr merge 912 --disable-auto")
        .expect("Auto is revoked");
    let push = log.find("git-push").expect("rebased head is pushed");
    assert!(
        disable < push,
        "Auto must be revoked before rebase push:\n{log}"
    );
}

/// Publication is not an integration boundary. A branch behind origin is
/// pushed unchanged, its recorded fork remains authoritative, and a later
/// explicit rebase owns the rewrite.
#[test]
fn publish_keeps_a_behind_branch_and_recorded_base_unchanged() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new(); // origin/main = P
    let stale_base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_open_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(),
    );

    // The Task branch, cut from the base and pushed.
    let branch = "jack/publish-heal-proof";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");
    repo.push_new_branch(branch);

    // origin/main advances past the recorded base. Publication must not rebase.
    repo.checkout("main");
    repo.create_file("upstream.txt", "landed upstream\n");
    repo.stage_all();
    repo.commit("upstream advance");
    repo.push();
    repo.checkout(branch);
    let before_publish = repo.head_sha();

    let task = register_task(home.path(), repo.path(), branch, &stale_base);

    create_or_update_pr(
        repo.path(),
        &PrOptions {
            title: Some("publish heal".to_string()),
            body: Some("proof body".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("publish without integration");

    assert_eq!(
        repo.head_sha(),
        before_publish,
        "a clean publication must not rewrite local HEAD"
    );
    let runtime = tokio::runtime::Runtime::new().expect("read task runtime");
    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert_eq!(
        pr.base_commit, stale_base,
        "publication must not advance the recorded integration base"
    );
    let files = git_out(
        &repo,
        &["diff", "--name-only", &format!("{}..HEAD", pr.base_commit)],
    );
    assert!(
        files.contains("task.txt") && !files.contains("upstream.txt"),
        "the original authored range must remain intact, got:\n{files}"
    );
    assert!(
        !std::path::Path::new(&git_out(&repo, &["rev-parse", "--absolute-git-dir"]))
            .join("loopflow/rebase-owner.json")
            .exists(),
        "publication must not create rebase ownership state"
    );
}

/// Divergent ancestry: the branch was cut from a contaminated base, then
/// rebased onto the current origin without updating the recorded base. The
/// recorded base and origin diverge from the initial commit — neither is an
/// ancestor of the other. `submit` must refuse, name the commits and files on
/// **both sides**, and touch neither the remote nor `gh pr`.
#[test]
fn submit_refuses_divergent_ancestry_naming_both_sides() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let origin_tip = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_open_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(),
    );

    // A foreign commit advances local main ahead of origin (not pushed).
    repo.create_file("foreign.txt", "not this task's work\n");
    repo.stage_all();
    repo.commit("foreign canonical-main commit");
    let contaminated_base = repo.head_sha();

    // Cut the task branch from the contaminated base.
    let branch = "jack/divergent-proof";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");

    // Undo the foreign commit on main and advance origin with a different
    // commit so the recorded base and origin diverge from the initial commit.
    repo.checkout("main");
    git_out(&repo, &["reset", "--hard", &origin_tip]);
    repo.create_file("upstream.txt", "landed upstream\n");
    repo.stage_all();
    repo.commit("upstream advance");
    repo.push();

    // Rebase the task branch onto the current origin, simulating a manual
    // recovery that forgot to update the recorded base.
    repo.checkout(branch);
    git_out(
        &repo,
        &[
            "rebase",
            "--onto",
            "origin/main",
            &contaminated_base,
            branch,
        ],
    );

    register_task(home.path(), repo.path(), branch, &contaminated_base);

    let err = submit(repo.path(), &land_options(true, "divergent"), &NullProgress)
        .expect_err("divergent ancestry must refuse");
    let message = err.to_string();
    assert!(
        message.contains("diverged"),
        "expected divergence refusal, got: {message}"
    );
    // Base side (M..B): the foreign commit and its file.
    assert!(
        message.contains("foreign canonical-main commit"),
        "refusal must name the base-side foreign commit, got: {message}"
    );
    assert!(
        message.contains("foreign.txt"),
        "refusal must name the base-side file, got: {message}"
    );
    // Upstream side (B..M): the upstream commit and its file.
    assert!(
        message.contains("upstream advance"),
        "refusal must name the upstream-side commit, got: {message}"
    );
    assert!(
        message.contains("upstream.txt"),
        "refusal must name the upstream-side file, got: {message}"
    );
    assert!(
        message.contains("rebase --onto"),
        "refusal must print the recovery action, got: {message}"
    );

    // No GitHub side effect happened before the refusal.
    assert!(
        !remote_branch_exists(&repo, branch),
        "the branch must never reach the remote when ancestry is refused"
    );
    let log = fs::read_to_string(&log_path).unwrap_or_default();
    assert!(
        !log.contains("pr create") && !log.contains("pr edit") && !log.contains("pr ready"),
        "no gh PR mutation may be issued before refusal, got log:\n{log}"
    );
}

/// Squash-merged parent: PR1 was squash-merged, so origin/main carries a single
/// squash commit. PR2 was cut from PR1's original tip (not the squash), so its
/// recorded base carries commits origin/main doesn't have — the contaminated
/// case. `submit` must refuse and name the pre-squash commits.
#[test]
fn submit_refuses_contaminated_range_after_squash_merged_parent() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();

    let log_path = home.path().join("gh.log");
    let script = gh_open_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(),
    );

    // PR1: two commits cut from the initial origin tip.
    let first_branch = "jack/pr-one";
    repo.create_branch(first_branch);
    repo.create_file("pr1-a.txt", "a\n");
    repo.stage_all();
    repo.commit("PR1 first commit");
    repo.create_file("pr1-b.txt", "b\n");
    repo.stage_all();
    repo.commit("PR1 second commit");
    let pr1_tip = repo.head_sha();

    // Squash-merge PR1 onto main and push.
    repo.checkout("main");
    git_out(&repo, &["merge", "--squash", first_branch]);
    repo.stage_all();
    repo.commit("squash-merge PR1");
    repo.push();

    // PR2 cut from PR1's original tip — the real-world mistake.
    let second_branch = "jack/pr-two";
    git_out(&repo, &["branch", second_branch, &pr1_tip]);
    repo.checkout(second_branch);
    repo.create_file("pr2.txt", "PR2 work\n");
    repo.stage_all();
    repo.commit("PR2 commit");

    register_task(home.path(), repo.path(), second_branch, &pr1_tip);

    let err = submit(
        repo.path(),
        &land_options(true, "squash-merged parent"),
        &NullProgress,
    )
    .expect_err("squash-merged parent contamination must refuse");
    let message = err.to_string();
    assert!(
        message.contains("contaminated"),
        "expected contamination refusal, got: {message}"
    );
    assert!(
        message.contains("PR1 first commit"),
        "refusal must name the first pre-squash commit, got: {message}"
    );
    assert!(
        message.contains("PR1 second commit"),
        "refusal must name the second pre-squash commit, got: {message}"
    );
    assert!(
        message.contains("rebase --onto"),
        "refusal must print the recovery action, got: {message}"
    );

    assert!(
        !remote_branch_exists(&repo, second_branch),
        "the branch must never reach the remote when the range is refused"
    );
}

/// No-remote refusal: a repo with no remote must still catch a contaminated
/// range. The verification falls back to local main; if the recorded base
/// carries commits local main doesn't have, `submit` refuses before any push.
#[test]
fn submit_refuses_contaminated_range_without_a_remote() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_open_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(),
    );

    // Drop the remote entirely.
    git_out(&repo, &["remote", "remove", "origin"]);

    // Advance local main with a foreign commit, cut the branch from it, then
    // reset main to the original tip — the recorded base is off-local-main.
    repo.create_file("foreign.txt", "not this task's work\n");
    repo.stage_all();
    repo.commit("foreign local-main commit");
    let contaminated_base = repo.head_sha();

    let branch = "jack/no-remote-contaminated";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");

    repo.checkout("main");
    git_out(&repo, &["reset", "--hard", &base]);
    repo.checkout(branch);

    register_task(home.path(), repo.path(), branch, &contaminated_base);

    let err = submit(
        repo.path(),
        &land_options(true, "no-remote contaminated"),
        &NullProgress,
    )
    .expect_err("no-remote contaminated range must refuse");
    let message = err.to_string();
    assert!(
        message.contains("contaminated"),
        "expected contamination refusal, got: {message}"
    );
    assert!(
        message.contains("foreign local-main commit"),
        "refusal must name the foreign commit, got: {message}"
    );
    assert!(
        message.contains("rebase --onto"),
        "refusal must print the recovery action, got: {message}"
    );
}

/// Serial rotation: a continuation PR's recorded base sits behind origin/main
/// because a sibling landed. `land` rebases, heals the base to the true fork
/// point, and publishes — proving the three views agree. This is the serial
/// rotation case from the proof matrix, exercised end-to-end through `land`.
#[test]
fn serial_rotation_heals_stale_base_and_lands_the_continuation() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let stale_base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_open_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(),
    );

    // The serial PR's own commit, cut from the (soon stale) base and pushed.
    let branch = "jack/serial-rotation-proof";
    repo.create_branch(branch);
    repo.create_file("task.txt", "serial rotation work\n");
    repo.stage_all();
    repo.commit("serial rotation commit");
    repo.push_new_branch(branch);

    // A sibling lands: origin/main advances past the recorded base.
    repo.checkout("main");
    repo.create_file("upstream.txt", "landed upstream\n");
    repo.stage_all();
    repo.commit("upstream advance");
    repo.push();
    let advanced = repo.head_sha();
    repo.checkout(branch);

    let task = register_task(home.path(), repo.path(), branch, &stale_base);

    land(
        repo.path(),
        &land_options(false, "serial rotation"),
        &NullProgress,
    )
    .expect("serial rotation heals stale base and lands");

    // The recorded base healed forward to the current origin tip.
    let runtime = tokio::runtime::Runtime::new().expect("read task runtime");
    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert_eq!(
        pr.base_commit, advanced,
        "the stale serial base must heal forward to origin/main"
    );

    // The three views agree: recorded base == GitHub fork point.
    let github_fork_point = git_out(&repo, &["merge-base", "origin/main", "HEAD"]);
    assert_eq!(
        pr.base_commit, github_fork_point,
        "recorded base must equal GitHub's range fork point"
    );

    // The Task's authored tree is one final commit; upstream stays excluded.
    let range = format!("{}..HEAD", pr.base_commit);
    let range_commits = git_out(&repo, &["log", "--oneline", "--no-decorate", &range]);
    assert!(
        !range_commits.contains("upstream advance"),
        "the merged upstream commit must be excluded, got:\n{range_commits}"
    );
    assert_eq!(
        range_commits.lines().count(),
        1,
        "final range is one commit"
    );
    assert!(
        range_commits.contains("lf land: collapse authored history"),
        "the Task's authored tree must be represented by the final commit, got:\n{range_commits}"
    );
    let files = git_out(&repo, &["diff", "--name-only", &range]);
    assert!(
        files.contains("task.txt") && !files.contains("upstream.txt"),
        "the collapsed range must preserve only Task work, got:\n{files}"
    );
}

/// The core hole W2-254 closes: an existing PR (already has a GitHub number)
/// that is reset or rebased empty must refuse before any `gh pr` mutation. The
/// old `task_pr_has_changes` guard ran only when `pr.github().is_none()`; once
/// a PR had a number, an empty update sailed through to `gh pr edit`/`ready`/
/// `merge`. The shared verifier is unconditional, so `submit` on an empty
/// branch refuses before any `gh` call.
#[test]
fn submit_refuses_an_empty_range_before_any_gh_call() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_open_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/empty-range";
    repo.create_branch(branch);
    let task = register_task(home.path(), repo.path(), branch, &base);

    // Simulate a previously-published PR so the old guard's
    // `pr.github().is_none()` condition is false — the exact case it skipped.
    let runtime = tokio::runtime::Runtime::new().expect("update PR runtime");
    runtime.block_on(async {
        let mut pr = task
            .store
            .active_task_pr(&task.task.id)
            .await
            .expect("read active PR")
            .expect("active PR exists");
        pr.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            presentation: None,
            github: Some(GithubPr {
                number: 925,
                url: "https://example.com/pr/925".to_string(),
                head_sha: None,
            }),
            merge: None,
        });
        pr.updated_at = OffsetDateTime::now_utc();
        task.store
            .update_task_pr(&pr)
            .await
            .expect("set github number");
    });

    let err = submit(
        repo.path(),
        &land_options(true, "empty range"),
        &NullProgress,
    )
    .expect_err("empty range must refuse");
    assert!(
        err.to_string().contains("empty"),
        "expected empty-range refusal, got: {err}"
    );

    // No GitHub side effect happened before the refusal.
    let log = fs::read_to_string(&log_path).unwrap_or_default();
    assert!(
        !log.contains("pr create") && !log.contains("pr edit") && !log.contains("pr ready"),
        "no gh PR mutation may be issued for an empty range, got log:\n{log}"
    );
}