git-stk 0.12.2

Git-native stacked branch workflow helper
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
mod common;

use common::{FakeProvider, TestRepo};
use predicates::prelude::PredicateBooleanExt;

/// Run a git plumbing command in `dir`, feeding `stdin`, returning trimmed
/// stdout. For crafting refs the TestRepo helper can't (it has no stdin).
fn git_in(dir: &std::path::Path, args: &[&str], stdin: &str) -> String {
    use std::io::Write;
    use std::process::{Command, Stdio};
    let mut child = Command::new("git")
        .args(args)
        .current_dir(dir)
        .env("GIT_AUTHOR_NAME", "t")
        .env("GIT_AUTHOR_EMAIL", "t@t.t")
        .env("GIT_COMMITTER_NAME", "t")
        .env("GIT_COMMITTER_EMAIL", "t@t.t")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn git");
    child
        .stdin
        .take()
        .unwrap()
        .write_all(stdin.as_bytes())
        .unwrap();
    let out = child.wait_with_output().expect("git plumbing");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).trim().to_owned()
}

#[test]
fn repair_reconstructs_wiped_stack_from_ancestry() {
    let repo = TestRepo::new();

    // Build a 3-branch stack with real commits, then wipe all metadata -
    // the config-blown-away incident.
    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "a work");
    repo.stack().args(["new", "feature/b"]).assert().success();
    repo.commit_file("b.txt", "b\n", "b work");
    repo.stack().args(["new", "feature/c"]).assert().success();
    repo.commit_file("c.txt", "c\n", "c work");

    for branch in ["feature/a", "feature/b", "feature/c"] {
        repo.git(["config", "--unset", &format!("branch.{branch}.stkParent")]);
        repo.git(["config", "--unset", &format!("branch.{branch}.stkBase")]);
    }

    repo.stack()
        .arg("repair")
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "feature/a: set parent main (from ancestry)",
        ))
        .stdout(predicates::str::contains(
            "feature/b: set parent feature/a (from ancestry)",
        ))
        .stdout(predicates::str::contains(
            "feature/c: set parent feature/b (from ancestry)",
        ))
        .stdout(predicates::str::contains(
            "repair complete: 3 repaired, 0 verified, 0 unresolved",
        ));

    assert_eq!(
        repo.git(["config", "--get", "branch.feature/b.stkParent"]),
        "feature/a"
    );
    assert_eq!(
        repo.git(["config", "--get", "branch.feature/b.stkBase"]),
        repo.git(["rev-parse", "feature/a"])
    );
    // Trunk must never be assigned a parent.
    assert_eq!(
        repo.git_status(["config", "--get", "branch.main.stkParent"])
            .status
            .code(),
        Some(1)
    );
}

#[test]
fn repair_prefers_provider_review_base_over_ancestry() {
    let repo = TestRepo::new();
    repo.git(["config", "stk.provider", "github"]);

    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "a work");
    repo.stack().args(["new", "feature/b"]).assert().success();
    repo.commit_file("b.txt", "b\n", "b work");
    repo.git(["config", "--unset", "branch.feature/b.stkParent"]);
    repo.git(["config", "--unset", "branch.feature/b.stkBase"]);

    let fake = FakeProvider::new()
        .on(
            "feature/b",
            r##"[{"number":7,"state":"OPEN","baseRefName":"feature/a","headRefName":"feature/b","url":"https://github.com/owner/repo/pull/7"}]"##,
        )
        .fallback("[]")
        .install(&repo);

    repo.stack_faked(&fake)
        .arg("repair")
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "feature/b: set parent feature/a (from github review #7)",
        ));

    assert_eq!(
        repo.git(["config", "--get", "branch.feature/b.stkParent"]),
        "feature/a"
    );
}

#[test]
fn repair_re_records_stale_fork_point() {
    let repo = TestRepo::new();

    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "a work");
    repo.git([
        "config",
        "branch.feature/a.stkBase",
        "0000000000000000000000000000000000000000",
    ]);

    repo.stack()
        .arg("repair")
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "feature/a: re-recorded fork point from main",
        ))
        .stdout(predicates::str::contains("1 repaired, 0 verified"));

    assert_eq!(
        repo.git(["config", "--get", "branch.feature/a.stkBase"]),
        repo.git(["rev-parse", "main"])
    );
}

#[test]
fn repair_re_records_a_stale_but_still_ancestor_fork_point() {
    let repo = TestRepo::new();

    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "a work");
    let old_base = repo.git(["config", "--get", "branch.feature/a.stkBase"]);

    // Trunk advances, then feature/a moves onto it *outside git-stk*: the
    // recorded base is still an ancestor of feature/a, but the true fork point
    // has advanced past it. The old "any ancestor" check called this verified;
    // it must now be recognized as stale and re-recorded.
    repo.git(["switch", "main"]);
    repo.commit_file("m.txt", "m\n", "trunk moves");
    repo.git(["switch", "feature/a"]);
    repo.git(["rebase", "--onto", "main", &old_base, "feature/a"]);

    repo.stack()
        .arg("repair")
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "feature/a: re-recorded fork point from main",
        ))
        .stdout(predicates::str::contains("1 repaired, 0 verified"));

    assert_eq!(
        repo.git(["config", "--get", "branch.feature/a.stkBase"]),
        repo.git(["rev-parse", "main"])
    );
}

#[test]
fn repair_verifies_a_current_fork_point() {
    let repo = TestRepo::new();

    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "a work");
    repo.stack().args(["new", "feature/b"]).assert().success();
    repo.commit_file("b.txt", "b\n", "b work");

    // A freshly built stack: both fork points are current, so repair verifies
    // them and re-records nothing.
    repo.stack()
        .arg("repair")
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "repair complete: 0 repaired, 2 verified, 0 unresolved",
        ));
}

#[test]
fn repair_dry_run_changes_nothing() {
    let repo = TestRepo::new();

    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "a work");
    repo.git(["config", "--unset", "branch.feature/a.stkParent"]);
    repo.git(["config", "--unset", "branch.feature/a.stkBase"]);

    repo.stack()
        .args(["repair", "--dry-run"])
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "feature/a: would set parent main (from ancestry)",
        ));

    assert_eq!(
        repo.git_status(["config", "--get", "branch.feature/a.stkParent"])
            .status
            .code(),
        Some(1)
    );
}

#[test]
fn repair_reports_unrepairable_branches() {
    let repo = TestRepo::new();

    // A branch with no commits of its own and equal tip to main: direction
    // is ambiguous, so repair must not guess.
    repo.git(["switch", "-c", "feature/empty"]);
    repo.git(["switch", "main"]);

    repo.stack()
        .arg("repair")
        .assert()
        .success()
        .stdout(predicates::str::contains("feature/empty: no parent found"))
        .stdout(predicates::str::contains(
            "0 repaired, 0 verified, 1 unresolved",
        ));
}

#[test]
fn repair_from_remote_rebuilds_a_stack_from_the_pushed_metadata() {
    let repo = TestRepo::new();
    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "add a");
    repo.stack().args(["new", "feature/b"]).assert().success();
    repo.commit_file("b.txt", "b\n", "add b");

    // Pushing the branches publishes the shared metadata ref alongside them.
    let _origin = repo.add_bare_origin(&["main"]);
    repo.stack().args(["restack", "--push"]).assert().success();

    // A fresh clone would have no local stack metadata; simulate that.
    repo.git(["config", "--unset", "branch.feature/a.stkParent"]);
    repo.git(["config", "--unset", "branch.feature/b.stkParent"]);

    // Rebuild it purely from the metadata ref on the remote.
    repo.stack()
        .args(["repair", "--from-remote"])
        .assert()
        .success()
        .stdout(predicates::str::contains("attached feature/a to main"))
        .stdout(predicates::str::contains("attached feature/b to feature/a"))
        .stdout(predicates::str::contains("rebuilt 2 branches"));

    assert_eq!(
        repo.git(["config", "--get", "branch.feature/a.stkParent"]),
        "main"
    );
    assert_eq!(
        repo.git(["config", "--get", "branch.feature/b.stkParent"]),
        "feature/a"
    );
}

#[test]
fn repair_from_remote_errors_clearly_when_no_metadata_was_published() {
    let repo = TestRepo::new();
    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "add a");

    // A remote exists, but nothing ever pushed the metadata ref to it.
    let _origin = repo.add_bare_origin(&["main", "feature/a"]);

    repo.stack()
        .args(["repair", "--from-remote"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("no stack metadata on the remote"));
}

#[test]
fn repair_from_remote_conflicts_with_dry_run() {
    let repo = TestRepo::new();

    // The two modes are mutually exclusive; clap must reject the combination.
    repo.stack()
        .args(["repair", "--from-remote", "--dry-run"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("cannot be used with"));
}

#[test]
fn repair_from_remote_skips_unsafe_metadata_names() {
    let repo = TestRepo::new();
    repo.stack().args(["new", "feature/a"]).assert().success();
    repo.commit_file("a.txt", "a\n", "add a");
    let origin = repo.add_bare_origin(&["main", "feature/a"]);
    let bare = origin.path();

    // Craft a metadata ref on the origin: a malicious name git would parse as
    // an option (`--upload-pack=...`) alongside a legitimate one.
    let json =
        r#"{"trunk":"main","parents":{"--upload-pack=touch PWNED":"main","feature/a":"main"}}"#;
    let blob = git_in(bare, &["hash-object", "-w", "--stdin"], json);
    let tree = git_in(
        bare,
        &["mktree"],
        &format!("100644 blob {blob}\tstack.json\n"),
    );
    let commit = git_in(bare, &["commit-tree", &tree, "-m", "metadata"], "");
    git_in(bare, &["update-ref", "refs/stk/metadata", &commit], "");

    // Fresh-clone state: drop the local metadata so repair rebuilds it.
    repo.git(["config", "--unset", "branch.feature/a.stkParent"]);

    repo.stack()
        .args(["repair", "--from-remote"])
        .assert()
        .success()
        .stdout(predicates::str::contains("attached feature/a to main"))
        .stderr(predicates::str::contains(
            "skipping unsafe stack metadata entry",
        ));

    // The legit branch was attached; the malicious entry did nothing - it was
    // never fetched and no command ran.
    assert_eq!(
        repo.git(["config", "--get", "branch.feature/a.stkParent"]),
        "main"
    );
    assert!(
        !repo.path().join("PWNED").exists(),
        "the malicious metadata name must not have executed anything"
    );
}

/// The branch a stack sits on has no parent, so it is absent from the parent
/// map - and without it the other machine cannot tell a stack's base from a
/// branch whose metadata is missing. It rides the metadata ref too.
#[test]
fn repair_from_remote_restores_the_stack_base() {
    let repo = TestRepo::new();
    repo.git(["switch", "-c", "rc-20260817"]);
    repo.commit_file("rc.txt", "rc\n", "release commit");
    repo.stack().args(["new", "fix/shared"]).assert().success();
    repo.commit_file("shared.txt", "shared\n", "shared work");

    let _origin = repo.add_bare_origin(&["main", "rc-20260817"]);
    repo.stack().args(["restack", "--push"]).assert().success();

    // A fresh clone: no local stack metadata, and no local base branch either -
    // it is only a parent, so nothing else pulls it down.
    repo.git(["config", "--unset", "branch.fix/shared.stkParent"]);
    repo.git(["config", "--unset", "branch.rc-20260817.stkFloor"]);
    repo.git(["branch", "-D", "rc-20260817"]);

    repo.stack()
        .args(["repair", "--from-remote"])
        .assert()
        .success()
        // Recording a base another machine chose changes what this clone will
        // rebase, so it is said out loud.
        .stdout(predicates::str::contains("rc-20260817 is now a stack base"));

    assert_eq!(
        repo.git(["config", "--get", "branch.fix/shared.stkParent"]),
        "rc-20260817"
    );
    assert!(
        !repo
            .git_status(["branch", "--list", "rc-20260817"])
            .stdout
            .is_empty(),
        "the base should have been fetched: the stack is unusable without it"
    );
    assert_eq!(
        repo.git(["config", "--get", "branch.rc-20260817.stkFloor"]),
        "true",
        "the base should have been restored from the metadata ref"
    );
}

/// The metadata ref has to be able to revoke a base, not only record one: a
/// branch the other machine lists with a parent is a layer there, so a floor
/// held here is stale.
#[test]
fn repair_from_remote_clears_a_base_the_other_machine_adopted() {
    let repo = TestRepo::new();
    repo.git(["switch", "-c", "rc-20260817"]);
    repo.commit_file("rc.txt", "rc\n", "release commit");
    repo.stack().args(["new", "fix/shared"]).assert().success();
    repo.commit_file("shared.txt", "shared\n", "shared work");

    let _origin = repo.add_bare_origin(&["main", "rc-20260817"]);
    // The other machine decided the base is a layer after all, and pushed that.
    repo.stack()
        .args(["adopt", "rc-20260817", "--parent", "main"])
        .assert()
        .success();
    repo.stack().args(["restack", "--push"]).assert().success();

    // This clone still has it marked.
    repo.git(["config", "branch.rc-20260817.stkFloor", "true"]);

    repo.stack()
        .args(["repair", "--from-remote"])
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "rc-20260817 is no longer a stack base",
        ));

    assert_eq!(
        repo.git_status(["config", "--get", "branch.rc-20260817.stkFloor"])
            .stdout
            .len(),
        0
    );
}

/// A base that picked up a stray `stkParent` must still publish as a base.
/// Published as a layer it arrives with an empty `floors` list, and the
/// revocation on the receiving clone then clears the marker there - the one
/// protected machine exporting the damage.
#[test]
fn publish_metadata_keeps_a_base_a_base_even_with_a_stray_parent() {
    let repo = TestRepo::new();
    repo.git(["switch", "-c", "rc-20260817"]);
    repo.commit_file("rc.txt", "rc\n", "release commit");
    repo.stack().args(["new", "fix/shared"]).assert().success();
    repo.commit_file("shared.txt", "shared\n", "shared work");
    // What `repair` would write from the base's own release PR.
    repo.git(["config", "branch.rc-20260817.stkParent", "main"]);

    let _origin = repo.add_bare_origin(&["main", "rc-20260817"]);
    repo.stack().args(["restack", "--push"]).assert().success();

    // Simulate the other clone: drop the marker, then rebuild from the ref.
    repo.git(["config", "--unset", "branch.rc-20260817.stkFloor"]);
    repo.stack()
        .args(["repair", "--from-remote"])
        .assert()
        .success();

    assert_eq!(
        repo.git(["config", "--get", "branch.rc-20260817.stkFloor"]),
        "true",
        "a base with a stray parent must publish as a base, not a layer"
    );
}

/// A recorded base is not a branch missing a parent. Inferring one from its
/// own review writes metadata that contradicts the marker and that every
/// rewrite path then ignores.
#[test]
fn repair_leaves_a_recorded_stack_base_alone() {
    let repo = TestRepo::new();
    repo.git(["switch", "-c", "rc-20260817"]);
    repo.commit_file("rc.txt", "rc\n", "release commit");
    repo.stack().args(["new", "fix/shared"]).assert().success();
    repo.commit_file("shared.txt", "shared\n", "shared work");

    repo.stack()
        .args(["repair"])
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "rc-20260817: stack base, left alone",
        ));

    assert_eq!(
        repo.git_status(["config", "--get", "branch.rc-20260817.stkParent"])
            .stdout
            .len(),
        0,
        "repair must not invent a parent for a recorded base"
    );
}

/// Metadata written before bases were recorded has no `floors` key at all -
/// which is "this writer did not know about them", not "there are none". An
/// un-upgraded clone must not be able to revoke a marker here.
#[test]
fn repair_from_remote_keeps_a_base_when_the_remote_predates_floors() {
    let repo = TestRepo::new();
    repo.git(["switch", "-c", "rc-20260817"]);
    repo.commit_file("rc.txt", "rc\n", "release commit");
    repo.stack().args(["new", "fix/shared"]).assert().success();
    repo.commit_file("shared.txt", "shared\n", "shared work");

    let _origin = repo.add_bare_origin(&["main", "rc-20260817"]);
    repo.stack().args(["restack", "--push"]).assert().success();

    // An older git-stk publishing the same stack: it adopted the base, so the
    // base appears as an ordinary layer and the document has no floors key.
    let older = r#"{"trunk":"main","parents":{"fix/shared":"rc-20260817","rc-20260817":"main"}}"#;
    repo.write_metadata_ref(older);

    repo.stack()
        .args(["repair", "--from-remote"])
        .assert()
        .success();

    assert_eq!(
        repo.git(["config", "--get", "branch.rc-20260817.stkFloor"]),
        "true",
        "a floors-less document must not revoke a recorded base"
    );
}

/// GitHub's own stack outranks the review base: it is an ordering someone
/// stated rather than one inferred, and it is right even where a review has
/// since been retargeted.
#[test]
fn repair_prefers_githubs_stack_to_the_review_base() {
    let repo = TestRepo::new();
    repo.git(["config", "stk.provider", "github"]);
    repo.git(["config", "stk.githubStacks", "true"]);
    repo.git(["switch", "-c", "feature/a"]);
    repo.commit_file("a.txt", "a\n", "a work");
    repo.git(["switch", "-c", "feature/b"]);
    repo.commit_file("b.txt", "b\n", "b work");

    // Both layers still open, so the stack's ordering is current: nothing has
    // landed for the platform to have retargeted anything away from.
    let stacks = r##"[{"number":4,"open":true,"base":{"ref":"main"},"pull_requests":[
        {"number":12,"state":"open","head":{"ref":"feature/a"}},
        {"number":13,"state":"open","head":{"ref":"feature/b"}}]}]"##;
    let fake = FakeProvider::new()
        .on("repo view", r##"{"nameWithOwner":"owner/repo"}"##)
        .on("repos/owner/repo/stacks", stacks)
        // The review targets the trunk - opened against it, then added to the
        // stack - so the stated ordering is the better answer.
        .on("feature/b", r##"[{"number":13,"state":"OPEN","baseRefName":"main","headRefName":"feature/b","url":"https://example.com/13"}]"##)
        .fallback("[]")
        .install(&repo);

    repo.stack_faked(&fake)
        .args(["repair"])
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "feature/b: set parent feature/a (from stack 4 (#13))",
        ));

    assert_eq!(
        repo.git(["config", "--get", "branch.feature/b.stkParent"]),
        "feature/a"
    );
}

/// Detection is not gated on `stk.githubStacks` - that setting says whether
/// git-stk *registers* a stack, and a stack GitHub records is the most
/// authoritative ordering there is whoever created it.
#[test]
fn repair_uses_githubs_stack_even_when_registration_is_off() {
    let repo = TestRepo::new();
    repo.git(["config", "stk.provider", "github"]);
    // Deliberately NOT set.
    repo.git(["switch", "-c", "feature/a"]);
    repo.commit_file("a.txt", "a\n", "a work");
    repo.git(["switch", "-c", "feature/b"]);
    repo.commit_file("b.txt", "b\n", "b work");

    // Both layers open, so the stack's ordering is still current.
    let stacks = r##"[{"number":4,"open":true,"base":{"ref":"main"},"pull_requests":[
        {"number":12,"state":"open","head":{"ref":"feature/a"}},
        {"number":13,"state":"open","head":{"ref":"feature/b"}}]}]"##;
    let fake = FakeProvider::new()
        .on("repo view", r##"{"nameWithOwner":"owner/repo"}"##)
        .on("repos/owner/repo/stacks", stacks)
        .on("feature/b", r##"[{"number":13,"state":"OPEN","baseRefName":"main","headRefName":"feature/b","url":"https://example.com/13"}]"##)
        .fallback("[]")
        .install(&repo);

    repo.stack_faked(&fake)
        .args(["repair"])
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "feature/b: set parent feature/a (from stack 4 (#13))",
        ));

    assert_eq!(
        repo.git(["config", "--get", "branch.feature/b.stkParent"]),
        "feature/a"
    );
}

/// The stacks listing is asked once per command, not once per branch - and
/// that holds for the 404 a repo without the preview answers, which is the
/// only reason failures are cached at all. Detection is unconditional, so
/// `repair` on a wiped config would otherwise make one `gh` call per
/// parentless branch, every one of them a 404, on a repo that will never
/// have a stack.
#[test]
fn repair_asks_github_for_the_stack_listing_once_per_run() {
    let repo = TestRepo::new();
    repo.git(["config", "stk.provider", "github"]);

    for (branch, file) in [
        ("feature/a", "a.txt"),
        ("feature/b", "b.txt"),
        ("feature/c", "c.txt"),
        ("feature/d", "d.txt"),
    ] {
        repo.stack().args(["new", branch]).assert().success();
        repo.commit_file(file, "x\n", "work");
    }
    // Wipe the metadata only once the chain exists, so unsetting one parent
    // does not make the branch below it look like a stack base - which
    // `repair` skips, and which would leave nothing asking the provider.
    for branch in ["feature/a", "feature/b", "feature/c", "feature/d"] {
        for key in ["stkParent", "stkBase", "stkFloor"] {
            // `git_status`, not `git`: `--unset` exits non-zero for a key that
            // is not set, and not every branch carries every one of these. It
            // is also the helper that isolates the ambient git config, which a
            // raw `Command` would inherit.
            let _ = repo.git_status(["config", "--unset", &format!("branch.{branch}.{key}")]);
        }
    }

    let fake = FakeProvider::new()
        .log_all("calls.txt")
        .on("repo view", r##"{"nameWithOwner":"owner/repo"}"##)
        // What a repo without the preview answers, for every branch.
        .fail("repos/owner/repo/stacks", "gh: Not Found (HTTP 404)")
        .fallback("[]")
        .install(&repo);

    repo.stack_faked(&fake).args(["repair"]).assert().success();

    let calls = std::fs::read_to_string(repo.path().join("calls.txt")).expect("call log");
    let listings = calls
        .lines()
        .filter(|line| line.contains("repos/owner/repo/stacks"))
        .count();
    assert_eq!(
        listings, 1,
        "the listing is asked once per command, not once per branch:\n{calls}"
    );
}

/// But not once the layer below has landed. The platform keeps a landed layer
/// listed, so the ordering goes on naming a merged branch as the parent - while
/// the platform itself already retargeted the review away from it, and is the
/// only thing that can, since it refuses a base change by hand. Taking the
/// stale answer would write a `stkParent` pointing at a merged branch for
/// `restack` to rebase and force-push against.
#[test]
fn repair_prefers_the_review_base_once_the_layer_below_has_landed() {
    let repo = TestRepo::new();
    repo.git(["config", "stk.provider", "github"]);
    repo.git(["config", "stk.githubStacks", "true"]);
    repo.git(["switch", "-c", "feature/a"]);
    repo.commit_file("a.txt", "a\n", "a work");
    repo.git(["switch", "-c", "feature/b"]);
    repo.commit_file("b.txt", "b\n", "b work");

    // feature/a landed and stays listed; the platform moved #13 onto main.
    let stacks = r##"[{"number":4,"open":true,"base":{"ref":"main"},"pull_requests":[
        {"number":12,"state":"closed","head":{"ref":"feature/a"}},
        {"number":13,"state":"open","head":{"ref":"feature/b"}}]}]"##;
    let fake = FakeProvider::new()
        .on("repo view", r##"{"nameWithOwner":"owner/repo"}"##)
        .on("repos/owner/repo/stacks", stacks)
        .on("feature/b", r##"[{"number":13,"state":"OPEN","baseRefName":"main","headRefName":"feature/b","url":"https://example.com/13"}]"##)
        .fallback("[]")
        .install(&repo);

    repo.stack_faked(&fake)
        .args(["repair"])
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "feature/b: set parent main (from github review #13)",
        ))
        // feature/a still reads from the stack: its parent is the stack's own
        // base, which no layer landing can stale.
        .stdout(predicates::str::contains("feature/b: set parent feature/a").not());

    assert_eq!(
        repo.git(["config", "--get", "branch.feature/b.stkParent"]),
        "main",
        "the parent must be where the platform actually put the base"
    );
}