magi-cli 0.272.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
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
//! Explicit recovery of a task's public implementation, independent of historical candidates.

use std::path::Path;

use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};

use crate::{
    config::{Config, MergeMode},
    git, land,
};

/// Explicit purpose of an existing-PR recovery; never inferred from task prose.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum Disposition {
    /// Validate, publish to the selected PR and request fresh owner-approved landing.
    Land,
    /// Finish after local review, without public delivery.
    Review,
}

/// Inputs of the single configuration load used to start a recovery.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigEvidence {
    /// Ordered configuration inputs; remote cache paths include the immutable source commit.
    pub layers: Vec<std::path::PathBuf>,
    /// Task options applied after loading the layers.
    pub overrides: Option<crate::queue::RunOverrides>,
    /// Daemon merge override, only when this task inherits daemon options.
    pub daemon_merge: Option<String>,
}

/// Durable operator selection. Only the recovery command creates this record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Selection {
    /// Existing pull request in this repository.
    pub url: String,
    /// Task-scoped public branch.
    pub branch: String,
    /// Initial public publication lease, independent of the implementation source.
    pub head: String,
    /// Full immutable source commit; older selections used the public lease.
    #[serde(default)]
    pub source_head: Option<String>,
    /// Historical run explicitly selected to prove a launcher rebase.
    #[serde(default)]
    pub source_run: Option<String>,
    /// Immutable proof, recomputed before starting or resuming work.
    #[serde(default)]
    pub source_proof: Option<Box<SourceProof>>,
    /// Missing on old records: requires an explicit new selection before work.
    #[serde(default)]
    pub disposition: Option<Disposition>,
    /// Criteria the operator approved, retained without rewriting them.
    pub instruction: String,
    /// Approval generation: a later selection does not resume an earlier run.
    pub approved_at: jiff::Timestamp,
}

/// Audit receipt for ending delivery ownership without discarding source history.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClosedRetirement {
    /// Closed, unmerged pull request URL.
    pub old_pr: String,
    /// Native inquiry whose accepted legacy effect was cancelled.
    pub inquiry: String,
    /// Exact replacement selection, including its approval generation.
    pub selection: Selection,
    /// Repository assignment owning both executions.
    pub assignment: usize,
    /// Time of the original retirement save.
    pub at: jiff::Timestamp,
}

/// Explicit terminal-only reconciliation of a cancelled legacy approval.
pub async fn retire_closed(
    queue: &crate::queue::Queue,
    home: &Path,
    task_id: &str,
    run_id: &str,
    inquiry_id: &str,
) -> Result<()> {
    retire_closed_with(
        queue,
        home,
        task_id,
        run_id,
        inquiry_id,
        async |task, state, selected| {
            let lifecycle = land::lifecycle(
                &task.repo,
                &state.pr.as_ref().context("missing old PR")?.url,
            )
            .await?;
            if matches!(lifecycle, land::PrLifecycle::Closed) {
                let (remote, base) = replacement_target(task, selected).await?;
                selected
                    .verify(&task.repo, &remote, &base, &selected.head)
                    .await?;
            }
            Ok(lifecycle)
        },
    )
    .await
}

async fn replacement_target(
    task: &crate::queue::Task,
    selected: &Selection,
) -> Result<(String, String)> {
    let explicit = task.overrides.as_ref().and_then(|o| o.config.as_deref());
    let (mut config, _) = Config::discover(&task.repo, explicit)?;
    if let Some(overrides) = &task.overrides {
        overrides.apply(&mut config);
    }
    selected.configure(&mut config)?;
    let base = git::merge_base_branch(
        &task.repo,
        &config.merge.remote,
        config.merge.base.as_deref(),
    )
    .await?;
    Ok((config.merge.remote, base))
}

async fn retire_closed_with(
    queue: &crate::queue::Queue,
    home: &Path,
    task_id: &str,
    run_id: &str,
    inquiry_id: &str,
    observe: impl AsyncFnOnce(
        &crate::queue::Task,
        &crate::run::RunState,
        &Selection,
    ) -> Result<land::PrLifecycle>,
) -> Result<()> {
    use crate::{
        ask::Questions,
        queue::{HoldSource, TaskStatus},
        run::{Liveness, RunState, RunStatus},
    };
    let id = queue.resolve_id(task_id)?;
    let _claim = queue.claim(&id)?;
    let task = queue.get(&id)?;
    ensure!(
        task.fresh_start && task.execution_runs().last().is_some_and(|r| r == run_id),
        "retirement requires the latest execution and an already selected fresh start"
    );
    let selected = task
        .pr_recovery
        .clone()
        .context("no saved replacement selection")?;
    selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len())?;
    ensure!(
        selected.disposition == Some(Disposition::Land),
        "replacement must be selected for delivery"
    );
    let outbox = crate::task_inquiry::Outbox::at(home);
    let _effect = outbox.execution_claim(inquiry_id)?;
    let inquiry = outbox.get(inquiry_id)?;
    ensure!(crate::run::is_run_id(run_id), "full run id required");
    let _owner = crate::pr_head::owner_lock(home, run_id)?;
    let state = RunState::load_under(run_id, home)?;
    ensure!(
        state.liveness_under(
            home,
            crate::daemon::is_working_on_other(home, run_id, jiff::Timestamp::now())?
        ) == Liveness::Dead,
        "obsolete execution is live or unknown"
    );
    let _execution = crate::driver::maintenance(home, run_id)?;
    let mut state = RunState::load_under(run_id, home)?;
    let repo = git::toplevel(&task.repo).await?.canonicalize()?;
    ensure!(
        state.id == run_id
            && state.origin.as_ref().and_then(|o| o.task.as_deref()) == Some(task.id.as_str())
            && state.task_assignment == task.reassignments.len()
            && git::toplevel(&state.repo).await?.canonicalize()? == repo
            && inquiry.task == task.id
            && inquiry.run.as_deref() == Some(run_id)
            && git::toplevel(&inquiry.repo).await?.canonicalize()? == repo,
        "retirement ownership does not match task, run and repository assignment"
    );
    ensure!(
        !state.released()
            && state.retired_to.is_none()
            && state.pr_taken_over_by.is_none()
            && !state.pr_publication_pending
            && state.land_armed_head.is_none()
            && !state.land_sync_pending
            && state.land_rebase_from.is_none()
            && state.land_sync_target.is_none()
            && state.sequencer_stop.is_none()
            && state.merge_repairs.is_empty()
            && state.merge_decision.is_none()
            && state.pr_merged_head.is_none(),
        "execution has competing ownership or an unresolved publication or repair checkpoint"
    );
    let pr = state.pr.as_ref().context("missing old PR")?;
    ensure!(
        pr.url != selected.url
            && land::slug_of_pr_url(&pr.url) == land::slug_of_pr_url(&selected.url),
        "replacement must be a different PR in the same repository"
    );
    let approval = state
        .land_approval
        .as_ref()
        .context("missing old approval binding")?;
    let questions = Questions::at(home.join("questions"));
    let question = questions.read_history(&approval.question)?;
    let decision = inquiry
        .decision
        .as_ref()
        .context("missing native decision")?;
    ensure!(
        inquiry.id == inquiry_id
            && inquiry.key == format!("question:{}", approval.question)
            && question.id == approval.question
            && question.run == run_id
            && question.node == land::APPROVAL_NODE
            && question
                .merge_target
                .as_ref()
                .is_some_and(|t| t.pr == pr.url && t.head == approval.head)
            && decision.status == crate::task_decision::Status::Resolved
            && decision.legacy_settled
            && decision.request.as_deref() == Some("decision: merge")
            && decision.error.is_none()
            && decision.source_answer_at.is_some()
            && decision.source_answer_at == question.answered_at
            && question.resolution().as_deref() == Some("merge")
            && !task.actions_applied.contains(&question.id)
            && !task.decision_effects.contains_key(inquiry_id)
            && !task.decision_effects.contains_key(&question.id),
        "old approval lacks an explicit settled cancellation or has conflicting effect evidence"
    );
    for other in outbox
        .list()
        .context("reading the obsolete run's inquiries")?
    {
        ensure!(
            other.id == inquiry_id
                || other.run.as_deref() != Some(run_id)
                || other
                    .decision
                    .as_ref()
                    .is_none_or(|d| { d.status == crate::task_decision::Status::Resolved }),
            "inquiry {} of this run still has an unresolved decision; reconcile it first",
            other.id
        );
    }
    let pending = crate::task_chat::migration_pending(home)?;
    let issues = crate::task_chat::migration_issues(home);
    ensure!(
        !issues.iter().any(|issue| issue.id == "migration"),
        "inquiry migration needs reconciliation"
    );
    for id in crate::queue::record_ids(&home.join("questions"), "json")? {
        let other = questions.read_history(&id)?;
        if other.run != run_id || id == approval.question {
            continue;
        }
        ensure!(
            !other.status.open()
                && !questions.held_reply(&id)
                && !pending.contains(&id)
                && !issues.iter().any(|issue| issue.id == id),
            "legacy question {id} of this run still needs reconciliation"
        );
    }
    let expected_hold =
        |reason: &str| reason.starts_with(&format!("Existing PR belongs to run {run_id};"));
    ensure!(
        task.status == TaskStatus::Queued
            || (task.status == TaskStatus::Held
                && task.hold_source == Some(HoldSource::Machine)
                && task.hold_reason.as_deref().is_some_and(expected_hold)),
        "task is not queued or held for this exact obsolete public owner"
    );
    let receipt = ClosedRetirement {
        old_pr: pr.url.clone(),
        inquiry: inquiry_id.into(),
        selection: selected.clone(),
        assignment: task.reassignments.len(),
        at: state
            .closed_pr_retirement
            .as_ref()
            .map_or_else(jiff::Timestamp::now, |r| r.at),
    };
    if let Some(saved) = &state.closed_pr_retirement {
        ensure!(
            saved == &receipt && state.status == RunStatus::Superseded && pr.state == "closed",
            "retirement receipt differs from this request"
        );
    } else {
        ensure!(
            crate::handover::landing_checkpoint(&state),
            "old run is not a retained public owner"
        );
    }
    match observe(&task, &state, &selected).await {
        Ok(land::PrLifecycle::Closed) => {}
        Ok(land::PrLifecycle::Merged) => anyhow::bail!(
            "old PR {} was merged; use merged-PR correction rather than retirement",
            pr.url
        ),
        Ok(land::PrLifecycle::Open) => anyhow::bail!("old PR {} is still open", pr.url),
        Err(error) => return Err(error.context("cannot verify old PR lifecycle or replacement")),
    }
    selected.verify_source_under(&task.repo, home).await?;
    retain_sources(&task, home)?;
    if state.closed_pr_retirement.is_none() {
        state.pr.as_mut().unwrap().state = "closed".into();
        state.status = RunStatus::Superseded;
        state.closed_pr_retirement = Some(receipt);
        state.event(
            "recovery",
            "explicitly retired cancelled closed PR delivery ownership",
        );
        state.save_under(home)?;
    }
    // The cancelled question remains quarantined, including its original answer.
    // No legacy consumer may interpret cancellation as a fallback decision.
    if task.status == TaskStatus::Held {
        ensure!(
            queue.modify(&task.id, |current| {
                if current.status != task.status
                    || current.held_at != task.held_at
                    || current.hold_reason != task.hold_reason
                    || current.hold_source != task.hold_source
                    || current.pr_recovery != task.pr_recovery
                    || current.operator_decided_at != task.operator_decided_at
                    || current.runs != task.runs
                    || current.reassignments.len() != task.reassignments.len()
                    || !current.fresh_start
                {
                    return false;
                }
                let attempts = current.attempts;
                current.release();
                current.attempts = attempts;
                current.fresh_start = true;
                true
            })?,
            "task changed during retirement; inspect its current hold before retrying"
        );
    }
    Ok(())
}

mod lineage;
pub use lineage::SourceProof;

const RETAIN_SOURCES: &str = "retain-recovery-sources";

/// Preserve every historical run's source artifacts before releasing a recovery task.
/// A sidecar survives stale run-state saves and applies even to older run schemas.
pub fn retain_sources(task: &crate::queue::Task, home: &Path) -> Result<()> {
    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
        ensure!(
            crate::run::is_run_id(id),
            "invalid historical run id; refusing source retention"
        );
        let dir = home.join("runs").join(id);
        ensure!(
            dir.is_dir(),
            "historical run {id} is missing; cannot retain its sources"
        );
        std::fs::write(dir.join(RETAIN_SOURCES), &task.id)
            .with_context(|| format!("retaining sources of historical run {id}"))?;
    }
    Ok(())
}

/// Return the retention reason rather than silently treating fold as successful.
pub(crate) fn source_retention_reason(home: &Path, state: &crate::run::RunState) -> Option<String> {
    if explicit_sources_retained(home, &state.id) {
        return Some("explicitly retained recovery source".into());
    }
    // A confirmed merge admits fold preflight even while the queue is held.
    // fold_run must still prove each deletion target under its ownership and
    // output locks. Ready/Failed/Superseded and PR creation alone do not qualify.
    if state.status == crate::run::RunStatus::Merged
        && state.merge.as_ref().is_some_and(|merged| merged.ok)
    {
        return None;
    }
    crate::queue::Queue::at(home.join("queue"))
        .list()
        .iter()
        // Queue completion does not prove that every historical candidate
        // landed. In particular, Superseded and Failed-without-tally runs
        // may still own independent implementations. Keep those sources
        // until recovery transfers them or confirmed-merge preflight captures
        // durable source evidence; Done is not deletion authority.
        .find(|task| task.runs.contains(&state.id))
        .map(|task| {
            format!(
                "source of task {}; inspect recovery lineage before folding",
                task.id
            )
        })
}

pub(crate) fn explicit_sources_retained(home: &Path, id: &str) -> bool {
    home.join("runs")
        .join(id)
        .join(RETAIN_SOURCES)
        .try_exists()
        .unwrap_or(true)
}

impl Selection {
    /// Immutable implementation commit, distinct from the public update lease.
    pub fn source(&self) -> &str {
        self.source_head.as_deref().unwrap_or(&self.head)
    }

    /// Reconcile only the delivery controls; preserve all other resolved settings.
    pub fn configure(&self, config: &mut Config) -> Result<()> {
        match self.disposition {
            Some(Disposition::Land) => {
                ensure!(
                    config.graph.reviewers > 0 && config.graph.review_rounds > 0,
                    "delivery requires at least one reviewer and review round"
                );
                ensure!(
                    !config.verify.gate.is_empty()
                        && config.verify.gate.iter().all(|s| !s.trim().is_empty()),
                    "delivery requires nonempty verify.gate commands; configure the repository's documented gate in a machine/repository layer or recover-pr --config <complete-config>"
                );
                ensure!(
                    !config.verify.e2e.is_empty()
                        && config.verify.e2e.iter().all(|s| !s.trim().is_empty()),
                    "delivery requires nonempty verify.e2e commands; configure the repository's required real-machine checks before recover-pr --disposition land"
                );
                config.merge.mode = MergeMode::Pr;
                config.graph.land = true;
                config.graph.land_approval = true;
            }
            Some(Disposition::Review) => {
                config.merge.mode = MergeMode::None;
                config.graph.land = false;
            }
            None => anyhow::bail!(
                "recovery disposition is missing; select the public head again with recover-pr --disposition land or --disposition review (and --source-head <full-SHA> to preserve a reviewed fix)"
            ),
        }
        Ok(())
    }

    /// Prove the adopted fix contains the selected public implementation.
    pub async fn verify_source(&self, repo: &Path) -> Result<()> {
        if self.source_proof.is_some() {
            self.verify_source_under(repo, &crate::run::home()).await
        } else {
            self.verify_source_under(repo, Path::new("")).await
        }
    }

    async fn verify_source_under(&self, repo: &Path, home: &Path) -> Result<()> {
        let source = git::rev_parse(repo, &format!("{}^{{commit}}", self.source())).await?;
        ensure!(
            source == self.source(),
            "source-head must resolve to its full commit SHA"
        );
        if let Some(proof) = &self.source_proof {
            // Historical state is large; keep replay out of the caller's future storage.
            let actual = Box::pin(lineage::prove(self, repo, home, &proof.current_base)).await?;
            ensure!(
                &actual == proof.as_ref(),
                "saved source proof changed; select the source again"
            );
        } else {
            ensure!(
                git::is_ancestor(repo, &self.head, &source).await,
                "source-head does not preserve the selected public implementation by ancestry; supply --source-run <retained-run-id> for a recorded launcher rebase"
            );
            ensure!(
                self.source_run.is_none(),
                "source-run requires a saved source proof; select again"
            );
        }
        Ok(())
    }

    /// Select and persist evidence without changing the implementation or public lease.
    pub async fn prepare_source(
        &mut self,
        repo: &Path,
        home: &Path,
        current_base: &str,
    ) -> Result<()> {
        ensure!(
            self.source_proof.is_none(),
            "source proof is already selected; refusing to replace saved evidence"
        );
        if self.source_run.is_some() {
            self.source_proof = Some(Box::new(
                Box::pin(lineage::prove(self, repo, home, current_base)).await?,
            ));
            Ok(())
        } else {
            self.verify_source(repo).await
        }
    }

    /// Confirm initial-assignment task identity and immutable criteria.
    pub fn check_task(&self, task: &str, instruction: &str) -> Result<()> {
        self.check_task_assignment(task, instruction, 0)
    }

    /// Confirm the exact repository assignment as well as task and criteria.
    pub fn check_task_assignment(
        &self,
        task: &str,
        instruction: &str,
        assignment: usize,
    ) -> Result<()> {
        ensure!(
            self.branch == crate::run::task_pr_branch_name(task, assignment),
            "recovery head belongs to another task or repository assignment"
        );
        ensure!(
            self.instruction == instruction,
            "recovery criteria changed; select the public head again"
        );
        ensure!(
            [self.head.as_str(), self.source()]
                .iter()
                .all(|sha| sha.len() == 40 && sha.bytes().all(|b| b.is_ascii_hexdigit())),
            "recovery requires a full commit SHA"
        );
        Ok(())
    }

    /// Read-only forge validation plus fetch; no local branch is moved or pushed.
    pub async fn verify(&self, repo: &Path, remote: &str, base: &str, lease: &str) -> Result<()> {
        let pr_repo = land::slug_of_pr_url(&self.url).context("invalid recovery PR URL")?;
        for args in [
            vec!["remote", "get-url", "--all", remote],
            vec!["remote", "get-url", "--push", "--all", remote],
        ] {
            let urls = git::git(repo, &args).await?;
            ensure!(
                !urls.trim().is_empty(),
                "recovery remote has no repository URL"
            );
            for url in urls.lines() {
                let remote_repo =
                    remote_slug(url).context("cannot prove recovery remote repository identity")?;
                land::ensure_same_repo(&remote_repo, &pr_repo)?;
            }
        }
        self.verify_forge_with(Path::new("gh"), repo, base, lease)
            .await?;
        let fetched = git::fetch(repo, remote, &self.branch).await?;
        ensure!(
            fetched.ok(),
            "fetch selected public head failed: {}",
            fetched.stderr
        );
        let fetched_head =
            git::rev_parse(repo, &format!("refs/remotes/{remote}/{}", self.branch)).await?;
        ensure!(
            fetched_head == lease,
            "public head moved; select and approve its new head before recovery"
        );
        ensure!(
            git::remote_head(repo, remote, &self.branch)
                .await?
                .as_deref()
                == Some(lease),
            "public head lease changed during recovery"
        );
        Ok(())
    }

    async fn verify_forge_with(
        &self,
        program: &Path,
        repo: &Path,
        base: &str,
        lease: &str,
    ) -> Result<()> {
        let found = land::find_open_pr_with(program, repo, &self.branch, base).await?;
        ensure!(
            matches!(found, land::OpenPr::One { ref url, .. } if url == &self.url),
            "selected PR is not the unique open task PR in this repository"
        );
        let view = land::gh_with(
            program,
            repo,
            &[
                "pr".into(),
                "view".into(),
                self.url.clone(),
                "--json".into(),
                "headRefName,headRefOid,baseRefName,state,isCrossRepository".into(),
            ],
        )
        .await?;
        ensure!(view.ok, "could not verify selected PR: {}", view.combined());
        validate_view(&view.stdout, &self.branch, base, lease)
    }
}

// Require a recognizable forge URL rather than guessing through local paths or SSH aliases.
fn remote_slug(url: &str) -> Option<String> {
    let url = url
        .trim()
        .trim_end_matches('/')
        .strip_suffix(".git")
        .unwrap_or(url.trim().trim_end_matches('/'));
    let (host, path) = if let Some(rest) = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))
        .or_else(|| url.strip_prefix("ssh://"))
    {
        let (authority, path) = rest.split_once('/')?;
        (authority.rsplit('@').next()?, path)
    } else {
        let (authority, path) = url.split_once(':')?;
        let (_, host) = authority.split_once('@')?;
        (host, path)
    };
    let mut parts = path.split('/');
    let owner = parts.next()?;
    let repo = parts.next()?;
    if host.is_empty() || owner.is_empty() || repo.is_empty() || parts.next().is_some() {
        return None;
    }
    Some(format!("{host}/{owner}/{repo}"))
}

fn validate_view(raw: &str, branch: &str, base: &str, lease: &str) -> Result<()> {
    #[derive(Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct View {
        head_ref_name: String,
        head_ref_oid: String,
        base_ref_name: String,
        state: String,
        is_cross_repository: bool,
    }
    let view: View = serde_json::from_str(raw).context("selected public head metadata")?;
    ensure!(
        view.state == "OPEN"
            && !view.is_cross_repository
            && view.head_ref_name == branch
            && view.base_ref_name == base,
        "selected PR ownership or base changed"
    );
    ensure!(
        view.head_ref_oid == lease,
        "selected public head moved; refusing recovery"
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn cancelled_closed_owner_retires_only_after_exact_selection_and_stopped_driver() {
        use crate::{
            ask::{Answer, Question, Questions},
            queue::{Queue, Source, Task, TaskStatus},
            run::{LandApproval, MergeOutcome, Origin, PrRecord, RunState, RunStatus},
            task_decision::Decision,
            task_inquiry::{Inquiry, Outbox},
        };
        let home = tempfile::tempdir().unwrap();
        let repo = tempfile::tempdir().unwrap();
        git::git(repo.path(), &["init"]).await.unwrap();
        git::git(
            repo.path(),
            &[
                "-c",
                "user.name=fixture",
                "-c",
                "user.email=fixture@example.test",
                "commit",
                "--allow-empty",
                "-m",
                "source",
            ],
        )
        .await
        .unwrap();
        let sha = git::rev_parse(repo.path(), "HEAD").await.unwrap();
        let queue = Queue::at(home.path().join("queue"));
        let mut task = Task::new(
            "recover".into(),
            "criteria".into(),
            repo.path().into(),
            Source::Human,
        );
        queue.put(&mut task).unwrap();
        let mut state = RunState::new(
            repo.path().into(),
            "main".into(),
            sha.clone(),
            task.instruction.clone(),
            Config::default(),
        );
        state.origin = Some(Origin::queue(&task.id));
        state.status = RunStatus::Blocked;
        state.driver_exited = true;
        state.config.graph.land = true;
        state.merge = Some(MergeOutcome {
            mode: MergeMode::Pr,
            ok: false,
            empty: false,
            detail: "held".into(),
        });
        let old_pr = "https://github.com/example/repo/pull/1";
        state.pr = Some(PrRecord {
            url: old_pr.into(),
            number: 1,
            state: "open".into(),
            checks: "green".into(),
            round: 1,
            rounds: 1,
            red_at_merge: vec![],
        });
        let mut question = Question::new(
            state.id.clone(),
            land::APPROVAL_NODE.into(),
            "land".into(),
            "merge?".into(),
            "approval".into(),
            vec!["merge".into()],
        );
        question.merge_target = Some(crate::merge_decision::Target {
            pr: old_pr.into(),
            head: sha.clone(),
            language: "en".into(),
        });
        question.answer(Answer::Choice("merge".into())).unwrap();
        let questions = Questions::at(home.path().join("questions"));
        questions.put(&mut question).unwrap();
        state.land_approval = Some(LandApproval {
            question: question.id.clone(),
            head: sha.clone(),
        });
        state.save_under(home.path()).unwrap();
        task.start(state.id.clone());
        task.hold_machine(Some(format!("Existing PR belongs to run {};", state.id)));
        task.fresh_start = true;
        let selected = Selection {
            url: "https://github.com/example/repo/pull/2".into(),
            branch: task.publication_branch(),
            head: sha,
            source_head: None,
            source_run: None,
            source_proof: None,
            disposition: Some(Disposition::Land),
            instruction: task.instruction.clone(),
            approved_at: jiff::Timestamp::now(),
        };
        task.pr_recovery = Some(selected.clone());
        let replacement_config = home.path().join("replacement.toml");
        std::fs::write(&replacement_config, "[merge]\nremote = 'replacement'\nbase = 'trunk'\n[verify]\ngate = ['gate']\ne2e = ['test']\n").unwrap();
        task.overrides = Some(crate::queue::RunOverrides {
            config: Some(replacement_config),
            ..Default::default()
        });
        queue.put(&mut task).unwrap();
        let outbox = Outbox::at(home.path());
        let mut decision = Decision::awaiting("merge?".into());
        decision.accept("decision: merge").unwrap();
        decision.source_answer_at = question.answered_at;
        outbox
            .enqueue(Inquiry {
                schema: 1,
                id: question.id.clone(),
                task: task.id.clone(),
                run: Some(state.id.clone()),
                repo: task.repo.clone(),
                source: land::APPROVAL_NODE.into(),
                occurrence: None,
                text: "approval".into(),
                display: "approval".into(),
                key: format!("question:{}", question.id),
                evidence: None,
                created_at: question.asked_at,
                delivered_to: None,
                decision: Some(decision),
                delivery_error: None,
                archived: false,
            })
            .unwrap();
        let retire = async |lifecycle| {
            retire_closed_with(
                &queue,
                home.path(),
                &task.id,
                &state.id,
                &question.id,
                async |task, old, selection| {
                    if matches!(lifecycle, Ok(land::PrLifecycle::Closed)) {
                        let (remote, base) = replacement_target(task, selection).await?;
                        assert_eq!((remote.as_str(), base.as_str()), ("replacement", "trunk"));
                        assert_ne!(base, old.base_branch);
                    }
                    lifecycle
                },
            )
            .await
        };
        assert!(retire(Ok(land::PrLifecycle::Closed)).await.is_err());
        outbox
            .update_decision(&question.id, |d| {
                d.settle_legacy("owner cancelled obsolete approval")
            })
            .unwrap();
        for (lifecycle, diagnostic) in [
            (Ok(land::PrLifecycle::Open), "still open"),
            (Ok(land::PrLifecycle::Merged), "was merged"),
            (
                Err(anyhow::anyhow!("unknown")),
                "cannot verify old PR lifecycle",
            ),
        ] {
            let error = retire(lifecycle).await.unwrap_err();
            assert!(error.to_string().contains(diagnostic), "{error:#}");
        }
        let mut other = outbox.get(&question.id).unwrap();
        other.id = "other-decision".into();
        other.key = "question:other-decision".into();
        other.decision = Some(Decision::awaiting("another decision".into()));
        outbox.enqueue(other).unwrap();
        let error = retire(Ok(land::PrLifecycle::Closed)).await.unwrap_err();
        assert!(error.to_string().contains("other-decision"), "{error:#}");
        outbox
            .update_decision("other-decision", |d| d.settle("no effect needed"))
            .unwrap();
        let mut legacy = Question::new(
            state.id.clone(),
            "ask".into(),
            "operator".into(),
            "another question".into(),
            "still pending".into(),
            vec![],
        );
        questions.put(&mut legacy).unwrap();
        let error = retire(Ok(land::PrLifecycle::Closed)).await.unwrap_err();
        assert!(error.to_string().contains(&legacy.id), "{error:#}");
        legacy.abandon("no effect needed");
        questions.put(&mut legacy).unwrap();
        let migration = home.path().join("notifications/task-chat-migration-v1");
        std::fs::create_dir_all(&migration).unwrap();
        let journal = migration.join("state.json");
        std::fs::write(
            &journal,
            serde_json::to_vec(&serde_json::json!({
                "schema": 1, "pending": [&legacy.id], "sources": [&legacy.id]
            }))
            .unwrap(),
        )
        .unwrap();
        let error = retire(Ok(land::PrLifecycle::Closed)).await.unwrap_err();
        assert!(error.to_string().contains(&legacy.id), "{error:#}");
        std::fs::write(
            &journal,
            serde_json::to_vec(&serde_json::json!({
                "schema": 1, "pending": [], "sources": [&legacy.id]
            }))
            .unwrap(),
        )
        .unwrap();
        let held = crate::driver::maintenance(home.path(), &state.id).unwrap();
        assert!(retire(Ok(land::PrLifecycle::Closed)).await.is_err());
        drop(held);
        assert_eq!(
            RunState::load_under(&state.id, home.path()).unwrap().status,
            RunStatus::Blocked
        );
        let owner = crate::daemon::public_resume_owner(home.path(), &task.runs, &task.repo)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(owner.id, state.id);
        retire(Ok(land::PrLifecycle::Closed)).await.unwrap();
        let retired = RunState::load_under(&state.id, home.path()).unwrap();
        assert_eq!(retired.status, RunStatus::Superseded);
        assert_eq!(retired.pr.as_ref().unwrap().state, "closed");
        assert!(!crate::handover::landing_checkpoint(&retired));
        assert!(
            crate::daemon::public_resume_owner(home.path(), &task.runs, &task.repo)
                .await
                .unwrap()
                .is_none()
        );
        assert_eq!(
            questions
                .read_history(&question.id)
                .unwrap()
                .resolution()
                .as_deref(),
            Some("merge")
        );
        assert!(
            questions
                .get_for_effects(&question.id)
                .unwrap()
                .resolution()
                .is_none()
        );
        let queued = queue.get(&task.id).unwrap();
        assert_eq!(queued.status, TaskStatus::Queued);
        assert!(queued.fresh_start);
        assert_eq!(queued.pr_recovery.as_ref(), Some(&selected));
        assert_eq!(queued.attempts, task.attempts);
        retire(Ok(land::PrLifecycle::Closed)).await.unwrap();
        assert_eq!(
            RunState::load_under(&state.id, home.path())
                .unwrap()
                .closed_pr_retirement,
            retired.closed_pr_retirement
        );
    }

    #[test]
    fn recovery_uses_resolved_layers_and_preserves_unrelated_overrides() {
        let dir = tempfile::tempdir().unwrap();
        let machine = dir.path().join("machine.toml");
        let repo = dir.path().join("repository.toml");
        std::fs::write(&machine, "[verify]\ngate = ['documented gate']\ne2e = ['real checks']\n[graph]\nland = false\nland_approval = false\n").unwrap();
        std::fs::write(&repo, "[merge]\nmode = 'none'\nbase = 'trunk'\n").unwrap();
        let mut config = Config::load_layers(&[machine, repo]).unwrap();
        let overrides = crate::queue::RunOverrides {
            merge: Some("none".into()),
            reviewers: Some(2),
            ..Default::default()
        };
        overrides.apply(&mut config);
        let mut selection = Selection {
            url: "url".into(),
            branch: "magi/task-t".into(),
            head: "a".repeat(40),
            source_head: None,
            source_run: None,
            source_proof: None,
            disposition: Some(Disposition::Land),
            instruction: "criteria".into(),
            approved_at: jiff::Timestamp::now(),
        };
        selection.configure(&mut config).unwrap();
        assert_eq!(config.merge.mode, MergeMode::Pr);
        assert_eq!(config.graph.reviewers, 2);
        assert_eq!(config.merge.base.as_deref(), Some("trunk"));
        assert_eq!(config.verify.gate, ["documented gate"]);
        assert_eq!(config.verify.e2e, ["real checks"]);
        assert!(config.graph.land && config.graph.land_approval);
        let explicit = dir.path().join("explicit.toml");
        std::fs::write(&explicit, "[merge]\nbase = 'other'\n").unwrap();
        let (mut replacement, paths) = Config::discover(dir.path(), Some(&explicit)).unwrap();
        assert_eq!(paths, [explicit]);
        assert!(
            selection
                .configure(&mut replacement)
                .unwrap_err()
                .to_string()
                .contains("verify.gate")
        );
        replacement.verify.gate = vec![" ".into()];
        assert!(selection.configure(&mut replacement).is_err());
        selection.disposition = Some(Disposition::Review);
        selection.configure(&mut replacement).unwrap();
        assert_eq!(replacement.merge.mode, MergeMode::None);
        assert!(!replacement.graph.land);
    }

    #[test]
    fn selected_source_requires_the_same_fetch_and_push_repository() {
        for remote in [
            "https://example.test/team/project.git",
            "git@example.test:team/project.git",
            "ssh://git@example.test/team/project.git",
        ] {
            assert_eq!(
                remote_slug(remote).as_deref(),
                Some("example.test/team/project")
            );
        }
        assert!(remote_slug("/tmp/another.git").is_none());
        assert!(
            land::ensure_same_repo(
                &remote_slug("git@example.test:team/other.git").unwrap(),
                "example.test/team/project"
            )
            .is_err()
        );
        assert!(
            land::ensure_same_repo(
                &remote_slug("git@other.test:team/project.git").unwrap(),
                "example.test/team/project"
            )
            .is_err()
        );
    }

    #[test]
    fn selected_head_refuses_moved_or_foreign_public_heads() {
        let raw = r#"{"headRefName":"magi/task-t","headRefOid":"aaa","baseRefName":"main","state":"OPEN","isCrossRepository":false}"#;
        assert!(validate_view(raw, "magi/task-t", "main", "aaa").is_ok());
        assert!(validate_view(raw, "magi/task-t", "main", "bbb").is_err());
        assert!(validate_view(raw, "magi/task-other", "main", "aaa").is_err());
        assert!(validate_view(raw, "magi/task-t", "other", "aaa").is_err());
        assert!(
            validate_view(&raw.replace("false", "true"), "magi/task-t", "main", "aaa").is_err()
        );
        assert!(
            validate_view(&raw.replace("OPEN", "CLOSED"), "magi/task-t", "main", "aaa").is_err()
        );
    }

    #[test]
    fn selected_head_is_bound_to_authored_criteria_and_task() {
        let selected = Selection {
            url: "url".into(),
            branch: "magi/task-t".into(),
            head: "a".repeat(40),
            source_head: None,
            source_run: None,
            source_proof: None,
            disposition: Some(Disposition::Review),
            instruction: "approved".into(),
            approved_at: jiff::Timestamp::now(),
        };
        assert!(selected.check_task("t", "approved").is_ok());
        assert!(
            selected
                .check_task("t", "prose mentioning another candidate")
                .is_err()
        );
        assert!(selected.check_task("other", "approved").is_err());
        assert!(selected.check_task_assignment("t", "approved", 2).is_err());
        let mut reassigned = selected;
        reassigned.branch = "magi/task-t-assignment-2".into();
        assert!(reassigned.check_task_assignment("t", "approved", 2).is_ok());
        assert!(
            reassigned
                .check_task_assignment("t", "approved", 1)
                .is_err()
        );
        assert!(reassigned.check_task("t", "approved").is_err());
    }

    fn fake_recovery_gh(
        dir: &Path,
        name: &str,
        list: (&str, &str, i32),
        view: (&str, &str, i32),
    ) -> std::path::PathBuf {
        let list_out = dir.join(format!("{name}-list.stdout"));
        let list_err = dir.join(format!("{name}-list.stderr"));
        let view_out = dir.join(format!("{name}-view.stdout"));
        let view_err = dir.join(format!("{name}-view.stderr"));
        std::fs::write(&list_out, list.0).unwrap();
        std::fs::write(&list_err, list.1).unwrap();
        std::fs::write(&view_out, view.0).unwrap();
        std::fs::write(&view_err, view.1).unwrap();
        #[cfg(windows)]
        {
            let script = dir.join(format!("{name}.cmd"));
            let mut body = String::from("@echo off\r\n");
            body.push_str("if \"%~1 %~2\"==\"pr list\" (\r\n");
            if !list.0.is_empty() {
                body.push_str(&format!("  type \"{}\"\r\n", list_out.display()));
            }
            if !list.1.is_empty() {
                body.push_str(&format!("  type \"{}\" 1>&2\r\n", list_err.display()));
            }
            body.push_str(&format!("  exit /b {}\r\n)\r\n", list.2));
            body.push_str("if \"%~1 %~2\"==\"pr view\" (\r\n");
            if !view.0.is_empty() {
                body.push_str(&format!("  type \"{}\"\r\n", view_out.display()));
            }
            if !view.1.is_empty() {
                body.push_str(&format!("  type \"{}\" 1>&2\r\n", view_err.display()));
            }
            body.push_str(&format!("  exit /b {}\r\n)\r\n", view.2));
            body.push_str("exit /b 1\r\n");
            std::fs::write(&script, body).unwrap();
            script
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
            let script = dir.join(name);
            let emit = |out: &Path, err: &Path, has_out: bool, has_err: bool, code: i32| {
                let mut s = String::new();
                if has_out {
                    s.push_str(&format!("cat {}; ", quote(out)));
                }
                if has_err {
                    s.push_str(&format!("cat {} >&2; ", quote(err)));
                }
                s.push_str(&format!("exit {code}"));
                s
            };
            let body = format!(
                "#!/bin/sh\ncase \"$1 $2\" in\n  'pr list') {} ;;\n  'pr view') {} ;;\n  *) exit 1 ;;\nesac\n",
                emit(
                    &list_out,
                    &list_err,
                    !list.0.is_empty(),
                    !list.1.is_empty(),
                    list.2
                ),
                emit(
                    &view_out,
                    &view_err,
                    !view.0.is_empty(),
                    !view.1.is_empty(),
                    view.2
                ),
            );
            let status = std::process::Command::new("sh")
                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
                .arg(&script)
                .arg(&body)
                .status()
                .unwrap();
            assert!(status.success());
            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
            script
        }
    }

    #[tokio::test]
    async fn verify_forge_separates_json_stdout_from_stderr_hints_and_keeps_strict_guards() {
        let tmp = tempfile::tempdir().unwrap();
        let sha = "a".repeat(40);
        let selected = Selection {
            url: "https://github.com/example/repo/pull/1".into(),
            branch: "magi/task-t".into(),
            head: sha.clone(),
            source_head: None,
            source_run: None,
            source_proof: None,
            disposition: Some(Disposition::Land),
            instruction: "approved".into(),
            approved_at: jiff::Timestamp::now(),
        };
        let hint = "To listen to events, run: gh pr view --web\n";
        let list_json = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: recovered","baseRefName":"main","isCrossRepository":false}]"#;
        let view_json = format!(
            r#"{{"headRefName":"magi/task-t","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":false}}"#
        );

        // Appending the stderr hint to stdout (pre-fix bug) still fails strictly.
        let concatenated = format!("{view_json}\n{hint}");
        let strict_err = validate_view(&concatenated, &selected.branch, "main", &sha).unwrap_err();
        assert!(
            format!("{strict_err:#}").contains("trailing characters"),
            "{strict_err:#}"
        );

        // Valid JSON stdout + nonempty stderr hint on both pr list and pr view succeeds.
        let ok_gh = fake_recovery_gh(
            tmp.path(),
            "ok",
            (&format!("{list_json}\n"), hint, 0),
            (&format!("{view_json}\n"), hint, 0),
        );
        selected
            .verify_forge_with(&ok_gh, tmp.path(), "main", &sha)
            .await
            .unwrap();

        // Malformed stdout still fails strict parsing.
        let malformed_gh = fake_recovery_gh(
            tmp.path(),
            "malformed",
            (&format!("{list_json}\n"), "", 0),
            (&format!("{view_json}\ntrailing text\n"), "", 0),
        );
        let err = selected
            .verify_forge_with(&malformed_gh, tmp.path(), "main", &sha)
            .await
            .unwrap_err();
        assert!(
            format!("{err:#}").contains("trailing characters"),
            "{err:#}"
        );

        // Empty stdout + nonempty stderr on exit 0 never falls back to stderr.
        let empty_gh = fake_recovery_gh(
            tmp.path(),
            "empty",
            (&format!("{list_json}\n"), "", 0),
            ("", hint, 0),
        );
        assert!(
            selected
                .verify_forge_with(&empty_gh, tmp.path(), "main", &sha)
                .await
                .is_err()
        );

        // Failed gh invocation with valid JSON stdout preserves stderr diagnostics.
        let failed_gh = fake_recovery_gh(
            tmp.path(),
            "failed",
            (&format!("{list_json}\n"), "", 0),
            (
                &format!("{view_json}\n"),
                "gh: authentication required\n",
                1,
            ),
        );
        let err = selected
            .verify_forge_with(&failed_gh, tmp.path(), "main", &sha)
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("authentication required"), "{err}");

        // Ownership and head guards remain strict when stderr hints are present.
        assert!(
            selected
                .verify_forge_with(&ok_gh, tmp.path(), "main", &"b".repeat(40))
                .await
                .unwrap_err()
                .to_string()
                .contains("moved")
        );
        let wrong_branch_gh = fake_recovery_gh(
            tmp.path(),
            "wrong-branch",
            (&format!("{list_json}\n"), hint, 0),
            (
                &format!(
                    r#"{{"headRefName":"magi/task-other","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":false}}"#
                ),
                hint,
                0,
            ),
        );
        assert!(
            selected
                .verify_forge_with(&wrong_branch_gh, tmp.path(), "main", &sha)
                .await
                .unwrap_err()
                .to_string()
                .contains("ownership or base changed")
        );
        let fork_gh = fake_recovery_gh(
            tmp.path(),
            "fork",
            (&format!("{list_json}\n"), hint, 0),
            (
                &format!(
                    r#"{{"headRefName":"magi/task-t","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":true}}"#
                ),
                hint,
                0,
            ),
        );
        assert!(
            selected
                .verify_forge_with(&fork_gh, tmp.path(), "main", &sha)
                .await
                .unwrap_err()
                .to_string()
                .contains("ownership or base changed")
        );
    }
}