magi-cli 0.281.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
//! Two-phase owner authorization and exact-run queueing for landing base-sync recovery.
//!
//! Each request persists:
//! 1. Phase 1 (`prepared`): immutable request, stop, scope, and task snapshot before any state mutation.
//! 2. Phase 2a (`authorized`): unconsumed single-attempt authorization saved in `run.json`.
//! 3. Phase 2b (`applied`): atomic exact-run queue pin and durable request marker on the owning `Task`.
//!
//! Interrupted acceptances reconcile using the recorded snapshot without replaying or double-granting.
//! Uncertain or corrupt receipts refuse without inventing a second grant.
use std::path::{Path, PathBuf};

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

use crate::{
    git,
    land_sync_recovery::{
        Authorization, GRANT_ATTEMPTS, GhPrObserver, MAX_GRANTS, PrObserver, Scope, Stop,
    },
    queue::{OperatorResume, Queue, Task, TaskStatus},
    run::{Liveness, RunState},
};

/// Error returned when admission refused before writing any durable state or receipt.
#[derive(Debug, thiserror::Error)]
#[error("{0:#}")]
pub struct BeforeWrite(pub anyhow::Error);

fn before_write<T>(result: Result<T>) -> Result<T> {
    result.map_err(|error| {
        if error.is::<BeforeWrite>() {
            error
        } else {
            anyhow::Error::new(BeforeWrite(error))
        }
    })
}

/// Verify that `state` is still `task`'s latest execution run.
pub(crate) fn check_latest_execution_run(task: &Task, state: &RunState) -> Result<()> {
    match task.execution_runs().last() {
        Some(latest) if latest == &state.id => Ok(()),
        Some(latest) => bail!(
            "run {} is not task {}'s latest execution run (latest is {latest}); target the latest retained run instead",
            state.id,
            task.id,
        ),
        None => bail!(
            "run {} is not task {}'s latest execution run (task has no execution runs); target a task whose latest execution run is {}",
            state.id,
            task.id,
            state.id,
        ),
    }
}

/// Verify that `task` is neither currently running nor already done.
pub(crate) fn check_task_not_running_or_done(task: &Task) -> Result<()> {
    match task.status {
        TaskStatus::Running => bail!(
            "task {} is currently running; wait for the active attempt to stop so the task is no longer running",
            task.id,
        ),
        TaskStatus::Done => bail!(
            "task {} is already done; this control requires a task that is not done",
            task.id,
        ),
        _ => Ok(()),
    }
}

/// Verify task ownership and queue eligibility, reporting the exact failing condition.
pub(crate) fn check_task_ownership(
    task: &Task,
    state: &RunState,
    allow_review_branch: bool,
) -> Result<()> {
    check_latest_execution_run(task, state)?;
    ensure!(
        task.assignment_accepts(state),
        "run {} (assignment {}) is not accepted by task {}'s current repository assignment (assignment {}); target a run belonging to the current assignment, in the same repository and created after the last reassignment",
        state.id,
        state.task_assignment,
        task.id,
        task.reassignments.len(),
    );
    check_task_not_running_or_done(task)?;
    ensure!(
        !task.fresh_start,
        "task {} is marked fresh_start for a new competition; clear fresh_start or let the new competition run instead of targeting run {}",
        task.id,
        state.id,
    );
    if !allow_review_branch && let Some(branch) = task.review_branch.as_deref() {
        bail!(
            "task {} has a saved review_branch ({branch}) from a hold; clear the saved review_branch hold before targeting run {}",
            task.id,
            state.id,
        );
    }
    if let Some(selection) = &task.pr_recovery {
        bail!(
            "task {} has an active pr_recovery selection ({} on branch {}); finish or clear pr_recovery before targeting run {}",
            task.id,
            selection.url,
            selection.branch,
            state.id,
        );
    }
    Ok(())
}

fn ensure_review_head(task: &Task, local: &str, other: &str, source: &str) -> Result<()> {
    if let Some(branch) = &task.review_branch {
        ensure!(
            local.eq_ignore_ascii_case(other),
            "task {} has a saved review_branch ({branch}) from a hold; \
             retained worktree HEAD ({local}) must match {source} ({other}); \
             recover-land-sync requires the retained worktree HEAD, --head, and open PR head to match",
            task.id,
        );
    }
    Ok(())
}

/// Validated landing base-sync recovery request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Request {
    /// Full retained run ID.
    pub run: String,
    /// Full 40-character retained worktree HEAD; the public head is bound separately.
    pub head: String,
    /// Actor namespace (`"cli"` or chat talk ID).
    pub actor: String,
    /// Durable idempotency key; reuse only with identical arguments after interruption.
    pub request: String,
}

/// Result of a landing base-sync recovery admission request.
#[derive(Debug, Clone)]
pub struct Outcome {
    /// Owning task record after admission or idempotent reconciliation.
    pub task: Task,
    /// `true` when this exact request had already been applied.
    pub repeated: bool,
    /// `true` when an interrupted prior acceptance was reconciled to completion.
    pub reconciled: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Phase {
    Prepared,
    Authorized,
    Applied,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Binding {
    task: serde_json::Value,
    stop: Stop,
    scope: Scope,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Receipt {
    request: Request,
    phase: Phase,
    binding: Binding,
    queued: Task,
    created_at: Timestamp,
    #[serde(default)]
    applied_at: Option<Timestamp>,
}

fn save_receipt(path: &Path, receipt: &Receipt) -> Result<()> {
    let tmp = path.with_extension("tmp");
    std::fs::write(&tmp, serde_json::to_vec_pretty(receipt)?)?;
    std::fs::rename(tmp, path)?;
    Ok(())
}

/// Receipt directory path for a given actor under `home`.
pub fn receipt_path(home: &Path, actor: &str, request: &str) -> PathBuf {
    home.join("land-sync-recovery-controls")
        .join(actor)
        .join(format!("{request}.json"))
}

/// Authorize one bounded landing base-sync recovery attempt using `gh pr view`.
pub async fn recover(queue: &Queue, home: &Path, request: Request) -> Result<Outcome> {
    recover_with(queue, home, request, &GhPrObserver).await
}

/// Authorize one bounded landing base-sync recovery attempt with an injectable PR observer.
pub async fn recover_with<O: PrObserver>(
    queue: &Queue,
    home: &Path,
    mut request: Request,
    observer: &O,
) -> Result<Outcome> {
    before_write((|| -> Result<()> {
        ensure!(
            crate::run::is_run_id(&request.run),
            "landing sync recovery needs a full run id"
        );
        ensure!(
            crate::ask::valid_asset_name(&request.actor)
                && crate::ask::valid_asset_name(&request.request),
            "recovery actor and request must be safe filenames of at most 64 bytes"
        );
        ensure!(
            request.head.len() == 40 && request.head.bytes().all(|c| c.is_ascii_hexdigit()),
            "landing sync recovery needs a full 40-character HEAD SHA"
        );
        Ok(())
    })())?;
    request.head = request.head.to_ascii_lowercase();

    let dir = home
        .join("land-sync-recovery-controls")
        .join(&request.actor);
    before_write(std::fs::create_dir_all(&dir).map_err(Into::into))?;
    let lock = before_write(
        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .open(dir.join(format!("{}.lock", request.request)))
            .map_err(Into::into),
    )?;
    let _lock = before_write(crate::pr_head::OwnerLock::acquire(lock).map_err(Into::into))?;

    let path = dir.join(format!("{}.json", request.request));
    let key = format!("{}/{}", request.actor, request.request);

    let prior_receipt: Option<Receipt> = if path.exists() {
        let bytes = std::fs::read(&path).with_context(|| {
            format!(
                "uncertain landing sync recovery receipt: could not read {}; inspect before retrying",
                path.display()
            )
        })?;
        let parsed: Receipt = serde_json::from_slice(&bytes).with_context(|| {
            format!(
                "uncertain landing sync recovery receipt: corrupt JSON in {}; inspect before retrying",
                path.display()
            )
        })?;
        Some(parsed)
    } else {
        None
    };

    if let Some(prior) = &prior_receipt {
        if prior.request != request {
            return Err(anyhow::Error::new(BeforeWrite(anyhow!(
                "request ID already binds a different operation"
            ))));
        }
        if prior.phase == Phase::Applied {
            let current = queue
                .get(&prior.queued.id)
                .unwrap_or_else(|_| prior.queued.clone());
            return Ok(Outcome {
                task: current,
                repeated: true,
                reconciled: false,
            });
        }
        // Check whether Phase 2b already committed to the queue before a crash.
        let task = queue.get(&prior.queued.id).with_context(|| {
            format!(
                "uncertain landing sync recovery receipt: owning task {} unreadable",
                prior.queued.id
            )
        })?;
        if task.land_sync_recovery_requests.contains(&key) {
            let mut completed = prior.clone();
            completed.phase = Phase::Applied;
            completed.applied_at = Some(Timestamp::now());
            save_receipt(&path, &completed)?;
            return Ok(Outcome {
                task,
                repeated: true,
                reconciled: true,
            });
        }
    }

    let is_fresh = prior_receipt.is_none();
    let wrap_err = |err: anyhow::Error| -> anyhow::Error {
        if is_fresh {
            anyhow::Error::new(BeforeWrite(err))
        } else {
            err
        }
    };

    crate::task_reassign::ensure_current(queue, &request.run).map_err(&wrap_err)?;
    let mut owners = queue
        .list()
        .into_iter()
        .filter(|t| t.execution_runs().last() == Some(&request.run));
    let listed = owners
        .next()
        .context("run has no eligible latest task owner")
        .map_err(&wrap_err)?;
    if owners.next().is_some() {
        return Err(wrap_err(anyhow!("run has ambiguous task ownership")));
    }
    if let Some(prior) = &prior_receipt
        && prior.queued.id != listed.id
    {
        return Err(anyhow!(
            "uncertain landing sync recovery receipt: receipt targets task {} but current owner is {}",
            prior.queued.id,
            listed.id
        ));
    }

    let _claim = queue
        .claim(&listed.id)
        .context("task is claimed by a running daemon or another control")
        .map_err(&wrap_err)?;
    let task = queue.get(&listed.id).map_err(&wrap_err)?;
    if let Some(prior) = &prior_receipt
        && task.land_sync_recovery_requests.contains(&key)
    {
        let mut completed = prior.clone();
        completed.phase = Phase::Applied;
        completed.applied_at = Some(Timestamp::now());
        save_receipt(&path, &completed)?;
        return Ok(Outcome {
            task,
            repeated: true,
            reconciled: true,
        });
    }

    let _owner = crate::pr_head::owner_lock(home, &request.run).map_err(&wrap_err)?;
    let mut state = RunState::load_under(&request.run, home).map_err(&wrap_err)?;
    crate::pr_head::ensure_owner(&state).map_err(&wrap_err)?;

    let check_ownership = (|| -> Result<()> {
        check_task_ownership(&task, &state, true)?;
        ensure!(
            state
                .origin
                .as_ref()
                .and_then(|o| o.task.as_deref())
                .is_none_or(|owner| owner == task.id),
            "run belongs to another task"
        );
        ensure!(
            crate::daemon::compatible_run_instruction(&state, &task),
            "task instruction does not match the retained run"
        );
        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
        ensure!(
            state.liveness_under(home, claimed) == Liveness::Dead,
            "run is live or its ownership is unknown"
        );
        Ok(())
    })();
    check_ownership.map_err(&wrap_err)?;
    let _execution = crate::driver::maintenance(home, &state.id).map_err(&wrap_err)?;

    let existing_auth = state
        .land_sync_recovery
        .authorizations
        .iter()
        .find(|a| a.request == key)
        .cloned();

    match (&prior_receipt, &existing_auth) {
        (None, Some(_)) => {
            return Err(anyhow!(
                "uncertain landing sync recovery state: authorization for request `{key}` already exists in run state without a receipt; inspect before retrying"
            ));
        }
        (Some(prior), None) if prior.phase == Phase::Authorized => {
            return Err(anyhow!(
                "uncertain landing sync recovery receipt: receipt recorded authorization phase but run state has no matching authorization for `{key}`; inspect before retrying"
            ));
        }
        (Some(_), Some(auth)) => {
            ensure!(
                !auth.consumed && auth.invalidated.is_none() && state.land_sync_recovery_pending(),
                "landing sync recovery request was already consumed or invalidated; it cannot queue again"
            );
        }
        _ => {}
    }

    let check_eligibility = (|| -> Result<()> {
        ensure!(
            state.status.resumable()
                && state.released_to.is_none()
                && state.retired_to.is_none()
                && state.pr_taken_over_by.is_none(),
            "run ownership is final"
        );
        ensure!(
            !state.base_sync_blocked(),
            "run has a pre-publication base-sync stop; use recover-base, not recover-land-sync"
        );
        ensure!(
            state.land_sync_exhausted(),
            "run has no eligible landing base-sync exhaustion stop"
        );
        ensure!(
            state.land_sync_grants_remaining() >= GRANT_ATTEMPTS,
            "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
            state.land_sync_recovery.extra_attempts
        );
        if existing_auth.is_none() {
            ensure!(
                !state.has_unconsumed_land_sync_authorization(),
                "this landing base-sync stop already has a pending authorization; resume the existing request"
            );
        }
        Ok(())
    })();
    check_eligibility.map_err(&wrap_err)?;

    let winner = state
        .winner()
        .cloned()
        .context("run has no retained winner")
        .map_err(&wrap_err)?;
    let clean = git::is_clean(&winner.worktree).await.map_err(&wrap_err)?;
    if !clean {
        return Err(wrap_err(anyhow!(
            "retained worktree has uncommitted changes"
        )));
    }
    let scratch = home.join("runs").join(&state.id).join("rebase");
    let in_progress = git::checked_rebase_in_progress(&scratch)
        .await
        .map_err(&wrap_err)?;
    if in_progress {
        return Err(wrap_err(anyhow!(
            "landing rebase is already in progress in scratch worktree"
        )));
    }
    let local_head = git::rev_parse(&winner.worktree, "HEAD")
        .await
        .map_err(&wrap_err)?;
    let branch_head = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
        .await
        .map_err(&wrap_err)?;
    if local_head != branch_head {
        return Err(wrap_err(anyhow!(
            "retained worktree does not match the winner branch"
        )));
    }
    ensure_review_head(&task, &local_head, &request.head, "--head").map_err(&wrap_err)?;
    if !local_head.eq_ignore_ascii_case(&request.head) {
        return Err(wrap_err(anyhow!(
            "retained HEAD changed since the owner request (expected {}, actual {})",
            request.head,
            local_head
        )));
    }
    let pushed_head = state
        .pr_pushed_head
        .as_deref()
        .context("run has no recorded published PR head")
        .map_err(&wrap_err)?;
    ensure_review_head(
        &task,
        &local_head,
        pushed_head,
        "recorded published PR head",
    )
    .map_err(&wrap_err)?;
    crate::land_sync_recovery::validate_heads(
        &state,
        state.land_sync_recovery.stop.as_ref(),
        &local_head,
        pushed_head,
    )
    .await
    .map_err(&wrap_err)?;
    let pr_record = state
        .pr
        .as_ref()
        .context("run has no recorded pull request")
        .map_err(&wrap_err)?;
    if pr_record.state != "open" {
        return Err(wrap_err(anyhow!("recorded pull request is not open")));
    }

    let observed_pr = observer
        .observe_pr(&state.repo, &pr_record.url)
        .await
        .map_err(&wrap_err)?;
    let check_pr = (|| -> Result<()> {
        ensure!(observed_pr.open, "pull request is no longer open");
        ensure!(
            observed_pr.url == pr_record.url && observed_pr.number == pr_record.number,
            "observed pull request does not match the run's recorded pull request"
        );
        ensure!(
            observed_pr.head.len() == 40 && observed_pr.head.bytes().all(|b| b.is_ascii_hexdigit()),
            "observed pull request head is unreadable"
        );
        ensure_review_head(&task, &local_head, &observed_pr.head, "open PR head")?;
        ensure!(
            observed_pr.head.eq_ignore_ascii_case(pushed_head),
            "published PR head ({}) does not match recorded published HEAD ({pushed_head})",
            observed_pr.head
        );
        if let Some(base) = &observed_pr.base_branch
            && !base.is_empty()
        {
            ensure!(
                base == &state.base_branch,
                "pull request base branch changed (expected {}, observed {base})",
                state.base_branch
            );
        }
        Ok(())
    })();
    check_pr.map_err(&wrap_err)?;

    let fetched = git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch)
        .await
        .map_err(&wrap_err)?;
    if !fetched.ok() {
        return Err(wrap_err(anyhow!(
            "cannot authorize landing sync recovery without a fetched base: {}",
            fetched.stderr
        )));
    }
    let approved_tip = git::rev_parse(
        &state.repo,
        &format!("{}/{}", state.config.merge.remote, state.base_branch),
    )
    .await
    .map_err(&wrap_err)?;

    if let Some(stop) = &state.land_sync_recovery.stop {
        if !stop.head.eq_ignore_ascii_case(&local_head)
            || !stop.pr_head.eq_ignore_ascii_case(&observed_pr.head)
        {
            return Err(wrap_err(anyhow!(
                "retained or published HEAD differs from the recorded stop"
            )));
        }
        let descends = git::ancestry(&state.repo, &stop.tip, &approved_tip)
            .await
            .map_err(&wrap_err)?;
        if !descends {
            return Err(wrap_err(anyhow!(
                "fetched base tip {approved_tip} does not fast-forward from stopped base tip {}",
                stop.tip
            )));
        }
    } else {
        let prior_base = state
            .base_sync
            .as_ref()
            .map(|s| s.tip.as_str())
            .filter(|s| !s.is_empty())
            .unwrap_or(&state.base_commit);
        if !prior_base.is_empty() {
            let descends = git::ancestry(&state.repo, prior_base, &approved_tip)
                .await
                .map_err(&wrap_err)?;
            if !descends {
                return Err(wrap_err(anyhow!(
                    "fetched base tip {approved_tip} does not fast-forward from prior base commit {prior_base}"
                )));
            }
        }
        let stopped_tip = prior_receipt
            .as_ref()
            .map_or(approved_tip.as_str(), |prior| {
                prior.binding.stop.tip.as_str()
            });
        state.record_land_sync_exhausted_stop(&local_head, &observed_pr.head, stopped_tip);
    }

    let stop = state
        .land_sync_recovery
        .stop
        .clone()
        .context("landing sync stop missing after recording")
        .map_err(&wrap_err)?;
    let scope = Scope {
        tip: approved_tip.to_ascii_lowercase(),
        instruction: task.instruction.clone(),
        assignment: task.reassignments.len(),
        pr_head: observed_pr.head.to_ascii_lowercase(),
        pr_url: observed_pr.url.clone(),
        pr_number: observed_pr.number,
        grant_index: state.land_sync_recovery.extra_attempts,
    };
    let task_snapshot = serde_json::to_value(&task)
        .map_err(anyhow::Error::from)
        .map_err(&wrap_err)?;
    let binding = Binding {
        task: task_snapshot,
        stop: stop.clone(),
        scope: scope.clone(),
    };

    let reconciled = prior_receipt.is_some();
    let mut receipt = if let Some(prior) = prior_receipt {
        if let Some(auth) = &existing_auth {
            ensure!(
                auth.stop == prior.binding.stop && auth.scope == prior.binding.scope,
                "interrupted landing sync recovery authorization does not match receipt binding"
            );
        }
        let descends =
            git::ancestry(&state.repo, &prior.binding.scope.tip, &binding.scope.tip).await?;
        let mut original_scope = binding.scope.clone();
        original_scope.tip.clone_from(&prior.binding.scope.tip);
        ensure!(
            descends
                && prior.binding.task == binding.task
                && prior.binding.stop == binding.stop
                && prior.binding.scope == original_scope,
            "interrupted landing sync recovery request is stale: task, stop, HEAD, PR, instruction, or base lineage changed"
        );
        prior
    } else {
        let mut queued = task.clone();
        if !crate::repair_budget::queue_resumption(queue, &mut queued, &state.id)
            .map_err(&wrap_err)?
        {
            queued.release_operator("land-sync-recovery", None);
        }
        if queued.review_branch.is_some() {
            queued.review_branch = None;
            queued.review_instruction = None;
        }
        queued.resume_override = Some(OperatorResume {
            question_id: String::new(),
            at: Timestamp::now(),
            conductor_rehold: None,
            forced: true,
            pinned_run: Some(state.id.clone()),
        });
        queued.land_sync_recovery_requests.push(key.clone());
        let prepared = Receipt {
            request: request.clone(),
            phase: Phase::Prepared,
            binding,
            queued,
            created_at: Timestamp::now(),
            applied_at: None,
        };
        save_receipt(&path, &prepared)?;
        prepared
    };

    // Phase 2a: persist the unconsumed authorization on RunState before queue commit.
    if existing_auth.is_none() {
        let auth = Authorization {
            request: key.clone(),
            task: task.id.clone(),
            run: state.id.clone(),
            stop: receipt.binding.stop.clone(),
            scope: receipt.binding.scope.clone(),
            decision: receipt.queued.operator_decided_at,
            generation: receipt.queued.resumption.as_ref().map(|r| r.generation),
            granted_attempts: GRANT_ATTEMPTS,
            at: Timestamp::now(),
            consumed: false,
            consumed_at: None,
            invalidated: None,
            archived_verification: None,
        };
        state.land_sync_recovery.authorizations.push(auth);
        state.event(
            "land-sync-recovery",
            format!(
                "owner authorized {GRANT_ATTEMPTS} bounded landing base-sync attempt ({}/{MAX_GRANTS} grants); fresh E2E and gate required before publication",
                state.land_sync_recovery.extra_attempts + GRANT_ATTEMPTS
            ),
        );
        state.save_under(home)?;
    }
    if receipt.phase == Phase::Prepared {
        receipt.phase = Phase::Authorized;
        save_receipt(&path, &receipt)?;
    }

    // Phase 2b: atomically commit the exact-run queue pin and durable request marker.
    queue.commit_land_sync_recovery(&mut receipt.queued, &receipt.binding.task)?;
    receipt.phase = Phase::Applied;
    receipt.applied_at = Some(Timestamp::now());
    save_receipt(&path, &receipt)?;

    Ok(Outcome {
        task: queue.get(&task.id)?,
        repeated: false,
        reconciled,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        config::{Config, MergeMode},
        land_sync_recovery::{DispatchDecision, ObservedPr},
        pr_recovery::Selection,
        queue::{Reassignment, Source},
        run::{GateRepairE2e, MergeOutcome, PrRecord, RunStatus},
    };

    fn sample_pair() -> (Task, RunState) {
        let repo = PathBuf::from(".");
        let state = RunState::new(
            repo.clone(),
            "main".into(),
            "a".repeat(40),
            "ship recovery".into(),
            Config::default(),
        );
        let mut task = Task::new("sample".into(), "ship recovery".into(), repo, Source::Human);
        task.link_run(&state.id);
        task.hold_machine(Some("stopped".into()));
        (task, state)
    }

    #[test]
    fn check_task_ownership_reports_each_failed_condition() {
        let (base_task, state) = sample_pair();
        assert!(check_task_ownership(&base_task, &state, false).is_ok());

        // 1a. No execution runs on task.
        let mut no_runs = base_task.clone();
        no_runs.runs.clear();
        let err = check_task_ownership(&no_runs, &state, false).unwrap_err();
        assert!(
            err.to_string().contains("task has no execution runs"),
            "{err:#}"
        );

        // 1b. Another run is the latest execution run.
        let mut newer_run = base_task.clone();
        newer_run.link_run("20261206-999999-ffff");
        let err = check_task_ownership(&newer_run, &state, false).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("latest execution run"), "{msg}");
        assert!(msg.contains("20261206-999999-ffff"), "{msg}");

        // 2. Repository assignment mismatch (`!assignment_accepts`).
        let mut reassigned = base_task.clone();
        reassigned.reassignments.push(Reassignment {
            from: PathBuf::from("."),
            to: PathBuf::from("."),
            actor: "cli".into(),
            at: Timestamp::now(),
            run_boundary: 0,
        });
        let err = check_task_ownership(&reassigned, &state, false).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("repository assignment"), "{msg}");
        assert!(msg.contains("assignment 0"), "{msg}");
        assert!(msg.contains("assignment 1"), "{msg}");
        assert!(msg.contains("same repository"), "{msg}");
        assert!(msg.contains("created after the last reassignment"), "{msg}");

        // 3a. Running status.
        let mut running = base_task.clone();
        running.status = TaskStatus::Running;
        let err = check_task_ownership(&running, &state, false).unwrap_err();
        assert!(err.to_string().contains("currently running"), "{err:#}");

        // 3b. Done status.
        let mut done = base_task.clone();
        done.status = TaskStatus::Done;
        let err = check_task_ownership(&done, &state, false).unwrap_err();
        assert!(err.to_string().contains("already done"), "{err:#}");

        // 4. fresh_start set.
        let mut fresh = base_task.clone();
        fresh.fresh_start = true;
        let err = check_task_ownership(&fresh, &state, false).unwrap_err();
        assert!(err.to_string().contains("fresh_start"), "{err:#}");

        // 5. review_branch refused when `allow_review_branch == false`, allowed when `true`.
        let mut reviewed = base_task.clone();
        reviewed.review_branch = Some("magi/e6c5/A".into());
        let err = check_task_ownership(&reviewed, &state, false).unwrap_err();
        assert!(
            err.to_string().contains("review_branch (magi/e6c5/A)"),
            "{err:#}"
        );
        assert!(check_task_ownership(&reviewed, &state, true).is_ok());

        // 6. pr_recovery active.
        let mut pr_rec = base_task.clone();
        pr_rec.pr_recovery = Some(Selection {
            url: "https://github.com/example/repo/pull/42".into(),
            branch: "task-head".into(),
            head: "b".repeat(40),
            source_head: None,
            source_run: None,
            source_proof: None,
            disposition: None,
            instruction: pr_rec.instruction.clone(),
            approved_at: Timestamp::now(),
        });
        let err = check_task_ownership(&pr_rec, &state, true).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("pr_recovery"), "{msg}");
        assert!(
            msg.contains("https://github.com/example/repo/pull/42"),
            "{msg}"
        );
    }

    struct StaticObserver(ObservedPr);

    impl PrObserver for StaticObserver {
        async fn observe_pr(&self, _repo: &Path, _pr_url: &str) -> Result<ObservedPr> {
            Ok(self.0.clone())
        }
    }

    fn run_git(repo: &Path, args: &[&str]) -> String {
        let out = std::process::Command::new("git")
            .current_dir(repo)
            .args(args)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8(out.stdout).unwrap().trim().into()
    }

    #[tokio::test]
    async fn dispatch_check_proceeds_after_recover_clears_stale_review_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let repo = home.join("repo");
        std::fs::create_dir(&repo).unwrap();
        run_git(&repo, &["init", "-b", "main"]);
        run_git(&repo, &["config", "user.name", "fixture"]);
        run_git(&repo, &["config", "user.email", "fixture@example.invalid"]);
        std::fs::write(repo.join("base"), "base").unwrap();
        run_git(&repo, &["add", "."]);
        run_git(&repo, &["commit", "-m", "base"]);
        let base = run_git(&repo, &["rev-parse", "HEAD"]);

        let origin = home.join("origin.git");
        run_git(&repo, &["init", "--bare", origin.to_str().unwrap()]);
        run_git(
            &repo,
            &["remote", "add", "origin", origin.to_str().unwrap()],
        );
        run_git(&repo, &["push", "origin", "main"]);

        run_git(&repo, &["checkout", "-b", "winner"]);
        std::fs::write(repo.join("feature"), "impl").unwrap();
        run_git(&repo, &["add", "."]);
        run_git(&repo, &["commit", "-m", "feat: impl"]);
        let head = run_git(&repo, &["rev-parse", "HEAD"]);
        run_git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"]);

        run_git(&repo, &["checkout", "main"]);
        std::fs::write(repo.join("upstream"), "upstream").unwrap();
        run_git(&repo, &["add", "."]);
        run_git(&repo, &["commit", "-m", "upstream"]);
        run_git(&repo, &["push", "origin", "main"]);
        run_git(&repo, &["checkout", "winner"]);

        let pr_url = "https://github.com/example/repo/pull/42";
        let mut config = Config::default();
        config.graph.land = true;
        config.graph.land_rounds = 4;
        config.graph.land_approval = true;

        let mut run = RunState::new(
            repo.clone(),
            "main".into(),
            base,
            "ship recovery".into(),
            config,
        );
        run.begin_pass();
        run.status = RunStatus::Blocked;
        run.driver_exited = true;
        run.candidates.push(
            serde_json::from_value(serde_json::json!({
                "index": 0,
                "label": "A",
                "agent": "fixture",
                "branch": "winner",
                "worktree": repo
            }))
            .unwrap(),
        );
        run.tally = Some(
            serde_json::from_value(serde_json::json!({
                "first_choice": {},
                "borda": {},
                "winner": "A",
                "unanimous_initial": true,
                "deliberated": false,
                "changed_votes": 0,
                "unanimous_final": true
            }))
            .unwrap(),
        );
        run.reviews.push(
            serde_json::from_value(serde_json::json!({
                "round": 1,
                "head": head,
                "expected": 2,
                "answered": 2,
                "reviews": [],
                "clean": true,
                "e2e": [{"command": "cargo test", "code": 0, "output_tail": "ok", "duration_ms": 10}],
                "verified_head": head,
                "verified_at": Timestamp::now(),
                "e2e_deferred": false
            }))
            .unwrap(),
        );
        run.head_e2e = Some(GateRepairE2e::new(head.clone(), true, Vec::new()));
        run.gate_ran = true;
        run.gate_head = Some(head.clone());
        run.pr_head = Some("task-head".into());
        run.pr_pushed_head = Some(head.clone());
        run.pr = Some(PrRecord {
            url: pr_url.to_owned(),
            number: 42,
            state: "open".to_owned(),
            checks: "green".to_owned(),
            round: 0,
            rounds: 4,
            red_at_merge: Vec::new(),
        });
        run.merge = Some(MergeOutcome {
            mode: MergeMode::Pr,
            ok: false,
            detail:
                "could not synchronize landing base: landing base synchronization budget exhausted"
                    .into(),
            empty: false,
        });
        run.land_sync_attempts = 4;
        run.land_sync_pending = true;
        run.event(
            "land",
            "stopped: could not synchronize landing base: landing base synchronization budget exhausted",
        );

        let queue = Queue::at(home.join("queue"));
        let mut task = Task::new(
            "landing sync".into(),
            run.instruction.clone(),
            repo,
            Source::Human,
        );
        task.link_run(&run.id);
        task.hold_for_handover(
            Some("magi/e6c5/A".into()),
            "landing base synchronization budget exhausted".into(),
        );
        queue.put(&mut task).unwrap();
        run.origin = Some(crate::run::Origin::queue(&task.id));
        run.save_under(home).unwrap();

        let observer = StaticObserver(ObservedPr {
            url: pr_url.to_owned(),
            number: 42,
            open: true,
            head: head.clone(),
            base_branch: Some("main".to_owned()),
        });

        let outcome = recover_with(
            &queue,
            home,
            Request {
                run: run.id.clone(),
                head,
                actor: "cli".into(),
                request: "req-dispatch".into(),
            },
            &observer,
        )
        .await
        .unwrap();
        assert!(outcome.task.review_branch.is_none());
        assert!(outcome.task.review_instruction.is_none());

        let decision =
            crate::land_sync_recovery::dispatch_check_with(&queue, home, &outcome.task, &observer)
                .await;
        assert!(
            matches!(decision, DispatchDecision::Proceed),
            "dispatch_check_with must proceed once stale review_branch is cleared"
        );
    }
}