Skip to main content

magi/
land_sync_recovery.rs

1//! Explicit, bounded same-run recovery for exhausted landing base synchronization.
2//!
3//! Landing base synchronization (`land.rs::rebase_landing_worktree`) uses its own
4//! `land_sync_attempts` counter against `config.graph.land_rounds`, separate from
5//! pre-publication `base_sync_recovery`. Recovery grants at most one extra landing
6//! sync attempt per explicit owner approval, capped over the run's lifetime, without
7//! resetting `land_sync_attempts` or bypassing fresh head-bound verification or merge
8//! approval.
9use std::path::Path;
10
11use anyhow::Result;
12use jiff::Timestamp;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16    git,
17    queue::{Queue, Task, TaskStatus},
18    run::{
19        CommandOutcome, GateRepairE2e, MergeRepairPhase, RunState, RunStatus, VerificationEvidence,
20    },
21};
22
23/// Single-attempt allowance granted per explicit owner recovery approval.
24pub const GRANT_ATTEMPTS: usize = 1;
25
26/// Maximum lifetime extra landing base-sync attempts granted to one run.
27pub const MAX_GRANTS: usize = 4;
28
29/// Canonical diagnostic written when landing base synchronization exhausts its budget.
30pub const EXHAUSTED_DETAIL: &str = "landing base synchronization budget exhausted";
31
32/// Immutable snapshot of a landing base-sync exhaustion stop.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Stop {
35    /// Cumulative `land_sync_attempts` when stopped.
36    pub attempts: usize,
37    /// Effective landing base-sync limit (`land_rounds + extra_attempts`) when stopped.
38    pub limit: usize,
39    /// Retained winner worktree and branch HEAD at the stop.
40    pub head: String,
41    /// Published PR HEAD observed and recorded at the stop.
42    pub pr_head: String,
43    /// Existing pull request URL.
44    pub pr_url: String,
45    /// Existing pull request number.
46    pub pr_number: u64,
47    /// Fetched base tip observed at the stop (or verified at legacy admission).
48    pub tip: String,
49    /// Canonical diagnostic detail.
50    pub detail: String,
51    /// Stable timestamp of the stop.
52    pub at: Timestamp,
53}
54
55/// Admission bindings revalidated at dispatch and execution time.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Scope {
58    /// Fetched base tip observed at owner authorization; ordinary fast-forward is allowed.
59    pub tip: String,
60    /// Owning task instruction at authorization time.
61    pub instruction: String,
62    /// Owning task assignment count (`reassignments.len()`) at authorization time.
63    pub assignment: usize,
64    /// Open PR HEAD observed at authorization time.
65    pub pr_head: String,
66    /// Pull request URL at authorization time.
67    pub pr_url: String,
68    /// Pull request number at authorization time.
69    pub pr_number: u64,
70    /// Monotonic count of prior consumed grants (`extra_attempts`) at admission.
71    pub grant_index: usize,
72}
73
74/// Prior verification evidence detached and preserved before running recovered landing sync.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct ArchivedVerification {
77    /// When the prior verification evidence was archived.
78    pub archived_at: Timestamp,
79    /// Head that previously held the archived verification evidence.
80    pub head: String,
81    /// Previous `gate_head`.
82    pub gate_head: Option<String>,
83    /// Previous `gate_ran`.
84    pub gate_ran: bool,
85    /// Previous gate command outcomes.
86    pub gate: Vec<CommandOutcome>,
87    /// Previous current-head E2E record.
88    pub head_e2e: Option<GateRepairE2e>,
89    /// Previous post-repair E2E record.
90    pub gate_repair_e2e: Option<GateRepairE2e>,
91    /// Previous `(round, verified_head)` pairs detached from review rounds.
92    #[serde(default)]
93    pub review_verified_heads: Vec<(usize, Option<String>)>,
94}
95
96/// One explicit owner recovery authorization, consumed durably before any Git mutation.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Authorization {
99    /// Durable request key (`<actor>/<request>`).
100    pub request: String,
101    /// Owning task id.
102    pub task: String,
103    /// Exact saved run id authorized to recover.
104    pub run: String,
105    /// Immutable stop snapshot authorized by this request.
106    pub stop: Stop,
107    /// Verified admission scope rechecked on dispatch and execution.
108    pub scope: Scope,
109    /// Owner decision timestamp committed on the owning task.
110    #[serde(default)]
111    pub decision: Option<Timestamp>,
112    /// Queue resumption generation committed on the owning task, if any.
113    #[serde(default)]
114    pub generation: Option<u64>,
115    /// Extra landing sync attempts granted upon consumption (always `GRANT_ATTEMPTS`).
116    pub granted_attempts: usize,
117    /// When this authorization was recorded.
118    pub at: Timestamp,
119    /// Persisted `true` before any Git mutation or budget increment.
120    pub consumed: bool,
121    /// When consumed or refused.
122    #[serde(default)]
123    pub consumed_at: Option<Timestamp>,
124    /// Refusal reason when invalidated before execution; `consumed` is also set `true`.
125    #[serde(default)]
126    pub invalidated: Option<String>,
127    /// Prior verification evidence archived when this authorization was consumed.
128    #[serde(default)]
129    pub archived_verification: Option<ArchivedVerification>,
130}
131
132impl Authorization {
133    /// Consume a refused approval without granting recovery, retaining the reason.
134    pub(crate) fn refuse(&mut self, reason: impl Into<String>) {
135        self.invalidated = Some(reason.into());
136        self.consumed = true;
137        if self.consumed_at.is_none() {
138            self.consumed_at = Some(Timestamp::now());
139        }
140    }
141}
142
143/// Persistent landing base-sync exhaustion stop and authorization history.
144#[derive(Debug, Clone, Default, Serialize, Deserialize)]
145pub struct Recovery {
146    /// Total extra landing sync attempts granted by consumed authorizations.
147    #[serde(default)]
148    pub extra_attempts: usize,
149    /// Append-only history of landing sync exhaustion stops.
150    #[serde(default)]
151    pub stops: Vec<Stop>,
152    /// Active exhaustion stop awaiting explicit owner recovery, if any.
153    #[serde(default)]
154    pub stop: Option<Stop>,
155    /// Append-only history of explicit owner recovery authorizations.
156    #[serde(default)]
157    pub authorizations: Vec<Authorization>,
158}
159
160/// Minimal live pull request metadata verified at admission, dispatch, and execution.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct ObservedPr {
163    /// Pull request URL.
164    pub url: String,
165    /// Pull request number.
166    pub number: u64,
167    /// Whether the pull request is currently open.
168    pub open: bool,
169    /// Current pull request head SHA reported by the forge.
170    pub head: String,
171    /// Pull request base branch reported by the forge, when readable.
172    pub base_branch: Option<String>,
173}
174
175/// Injectable forge observer for pull request head and lifecycle verification.
176pub trait PrObserver {
177    /// Observe the current pull request state and head SHA.
178    fn observe_pr(
179        &self,
180        repo: &Path,
181        pr_url: &str,
182    ) -> impl std::future::Future<Output = Result<ObservedPr>> + Send;
183}
184
185/// Production forge observer backed by `gh pr view`.
186#[derive(Debug, Default, Clone, Copy)]
187pub struct GhPrObserver;
188
189impl PrObserver for GhPrObserver {
190    async fn observe_pr(&self, repo: &Path, pr_url: &str) -> Result<ObservedPr> {
191        crate::land::observe_pr_summary(repo, pr_url).await
192    }
193}
194
195fn matches_exhausted_detail(detail: &str) -> bool {
196    let trimmed = detail.trim();
197    trimmed == EXHAUSTED_DETAIL
198        || trimmed == format!("could not synchronize landing base: {EXHAUSTED_DETAIL}")
199}
200
201fn matches_exhausted_event(message: &str) -> bool {
202    let trimmed = message.trim();
203    trimmed == format!("stopped: could not synchronize landing base: {EXHAUSTED_DETAIL}")
204        || trimmed == format!("stopped: {EXHAUSTED_DETAIL}")
205        || trimmed == format!("gave up: {EXHAUSTED_DETAIL}")
206        || trimmed == format!("gave up: could not synchronize landing base: {EXHAUSTED_DETAIL}")
207}
208
209fn legacy_exhausted_diagnostic(state: &RunState) -> bool {
210    if let Some(last_land) = state.events.iter().rev().find(|e| e.node == "land") {
211        matches_exhausted_event(&last_land.message)
212    } else {
213        state
214            .merge
215            .as_ref()
216            .is_some_and(|m| !m.ok && matches_exhausted_detail(&m.detail))
217    }
218}
219
220fn exhausted_stop_timestamp(state: &RunState) -> Timestamp {
221    state
222        .events
223        .iter()
224        .rev()
225        .find(|e| e.node == "land" && matches_exhausted_event(&e.message))
226        .map_or(state.updated_at, |e| e.at)
227}
228
229impl RunState {
230    /// Effective landing base-sync attempt limit including consumed recovery grants.
231    pub fn land_sync_budget(&self) -> usize {
232        self.config
233            .graph
234            .land_rounds
235            .saturating_add(self.land_sync_recovery.extra_attempts)
236            .saturating_sub(
237                self.land_sync_recovery
238                    .authorizations
239                    .iter()
240                    .filter(|a| a.invalidated.is_some() && a.archived_verification.is_some())
241                    .count(),
242            )
243    }
244
245    /// Remaining lifetime recovery grants available for this run.
246    pub fn land_sync_grants_remaining(&self) -> usize {
247        MAX_GRANTS.saturating_sub(self.land_sync_recovery.extra_attempts)
248    }
249
250    /// Centralized predicate recognizing both structured and legacy landing
251    /// base-sync exhaustion stops.
252    pub fn land_sync_exhausted(&self) -> bool {
253        if self.status != RunStatus::Blocked {
254            return false;
255        }
256        if self.released_to.is_some()
257            || self.retired_to.is_some()
258            || self.pr_taken_over_by.is_some()
259        {
260            return false;
261        }
262        if !crate::handover::landing_checkpoint(self)
263            || self.base_sync_blocked()
264            || self.pr_publication_pending
265        {
266            return false;
267        }
268        if self.merge_decision.is_some()
269            || self.resource_block.is_some()
270            || self.sequencer_stop.is_some()
271            || self.land_rebase_from.is_some()
272            || self.land_sync_target.is_some()
273        {
274            return false;
275        }
276        if self.merge_repairs.last().is_some_and(|r| {
277            matches!(
278                r.phase,
279                MergeRepairPhase::Requested
280                    | MergeRepairPhase::Fixing
281                    | MergeRepairPhase::Reviewing
282            )
283        }) || self
284            .repair_grants
285            .last()
286            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
287            || self
288                .rebase_fixes
289                .iter()
290                .any(|r| r.stop.is_none() && !r.finished)
291        {
292            return false;
293        }
294        if !self.land_sync_pending
295            || self.land_sync_attempts == 0
296            || self.land_sync_attempts < self.land_sync_budget()
297        {
298            return false;
299        }
300        if let Some(stop) = &self.land_sync_recovery.stop {
301            stop.detail == EXHAUSTED_DETAIL
302                && stop.attempts == self.land_sync_attempts
303                && stop.limit == self.land_sync_budget()
304                && self
305                    .pr
306                    .as_ref()
307                    .is_some_and(|pr| pr.url == stop.pr_url && pr.number == stop.pr_number)
308                && self.land_sync_recovery.stops.contains(stop)
309        } else {
310            self.land_sync_recovery
311                .authorizations
312                .last()
313                .is_some_and(|a| {
314                    a.invalidated.is_some()
315                        && a.archived_verification.is_some()
316                        && a.stop.attempts == self.land_sync_attempts
317                })
318                || legacy_exhausted_diagnostic(self)
319        }
320    }
321
322    /// Whether any landing sync recovery authorization is still unconsumed.
323    pub fn has_unconsumed_land_sync_authorization(&self) -> bool {
324        self.land_sync_recovery
325            .authorizations
326            .iter()
327            .any(|a| !a.consumed && a.invalidated.is_none())
328    }
329
330    /// Whether the active landing exhaustion stop has a matching unconsumed authorization.
331    pub fn land_sync_recovery_pending(&self) -> bool {
332        self.land_sync_exhausted()
333            && self
334                .land_sync_recovery
335                .authorizations
336                .last()
337                .is_some_and(|a| {
338                    !a.consumed
339                        && a.invalidated.is_none()
340                        && a.run == self.id
341                        && a.granted_attempts == GRANT_ATTEMPTS
342                        && a.scope.grant_index == self.land_sync_recovery.extra_attempts
343                        && self.land_sync_recovery.stop.as_ref() == Some(&a.stop)
344                })
345    }
346
347    /// A grant was saved but its synchronization attempt has not been charged.
348    /// A refused grant no longer contributes to the effective attempt budget.
349    pub(crate) fn land_sync_unstarted_grant(&self) -> bool {
350        self.status.resumable()
351            && self
352                .land_sync_recovery
353                .authorizations
354                .last()
355                .is_some_and(|a| {
356                    a.consumed
357                        && a.invalidated.is_none()
358                        && a.archived_verification.is_some()
359                        && self.land_sync_attempts == a.stop.attempts
360                        && self.land_sync_recovery.extra_attempts
361                            == a.scope.grant_index.saturating_add(GRANT_ATTEMPTS)
362                })
363    }
364
365    /// Single-line actionable guidance for CLI, notices, and reports.
366    pub fn land_sync_next_action(&self) -> String {
367        let attempts = self.land_sync_attempts;
368        let limit = self.land_sync_budget();
369        let grants = self.land_sync_recovery.extra_attempts;
370        let head = self
371            .land_sync_recovery
372            .stop
373            .as_ref()
374            .map(|s| s.head.as_str())
375            .or(self.pr_pushed_head.as_deref())
376            .unwrap_or("<full-head-sha>");
377        if let Some(reason) = self
378            .land_sync_recovery
379            .authorizations
380            .last()
381            .and_then(|a| a.invalidated.as_ref())
382            && !self.land_sync_recovery_pending()
383        {
384            if self.land_sync_grants_remaining() == 0 {
385                return format!(
386                    "Landing base-sync recovery approval invalidated: {reason}; lifetime grant limit reached ({grants}/{MAX_GRANTS})"
387                );
388            }
389            return format!(
390                "Landing base-sync recovery approval invalidated: {reason}. Authorize a new bounded attempt with `magi task control recover-land-sync {} --request <unique-id> --head {head}` ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} grants used)",
391                self.id
392            );
393        }
394        if self.land_sync_recovery_pending() || self.land_sync_unstarted_grant() {
395            return format!(
396                "Landing base-sync recovery approval recorded; resume the retained run to spend {GRANT_ATTEMPTS} approved synchronization attempt ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} recovery grants used)"
397            );
398        }
399        if self.land_sync_grants_remaining() == 0 {
400            return format!(
401                "Lifetime landing base-sync recovery limit reached ({grants}/{MAX_GRANTS} grants used, {attempts}/{limit} attempts); inspect the retained branch and PR before manual intervention"
402            );
403        }
404        format!(
405            "Authorize {GRANT_ATTEMPTS} bounded landing base-sync attempt with `magi task control recover-land-sync {} --request <unique-id> --head {head}` ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} recovery grants used)",
406            self.id
407        )
408    }
409
410    /// Persist a stable structured stop snapshot on landing sync exhaustion.
411    pub(crate) fn record_land_sync_exhausted_stop(&mut self, head: &str, pr_head: &str, tip: &str) {
412        let Some(pr) = self.pr.as_ref() else {
413            return;
414        };
415        let limit = self.land_sync_budget();
416        if self.land_sync_recovery.stop.as_ref().is_some_and(|s| {
417            s.attempts == self.land_sync_attempts
418                && s.limit == limit
419                && s.head.eq_ignore_ascii_case(head)
420                && s.pr_head.eq_ignore_ascii_case(pr_head)
421                && s.pr_url == pr.url
422                && s.pr_number == pr.number
423                && s.detail == EXHAUSTED_DETAIL
424        }) {
425            return;
426        }
427        let at = exhausted_stop_timestamp(self);
428        let stop = Stop {
429            attempts: self.land_sync_attempts,
430            limit,
431            head: head.to_ascii_lowercase(),
432            pr_head: pr_head.to_ascii_lowercase(),
433            pr_url: pr.url.clone(),
434            pr_number: pr.number,
435            tip: tip.to_ascii_lowercase(),
436            detail: EXHAUSTED_DETAIL.to_owned(),
437            at,
438        };
439        if !self.land_sync_recovery.stops.contains(&stop) {
440            self.land_sync_recovery.stops.push(stop.clone());
441        }
442        self.land_sync_recovery.stop = Some(stop);
443    }
444
445    /// Atomically consume a validated pending authorization, add its bounded
446    /// extra attempt, archive prior verification evidence, and require fresh
447    /// head-bound E2E and gate before publication.
448    ///
449    /// Callers MUST save `RunState` immediately before running any Git mutation.
450    pub(crate) fn consume_land_sync_recovery(
451        &mut self,
452        head: &str,
453        pr_head: &str,
454    ) -> std::result::Result<(), String> {
455        if !self.land_sync_recovery_pending() {
456            return Err("no matching pending landing base-sync recovery authorization".into());
457        }
458        let now = Timestamp::now();
459        let granted = self
460            .land_sync_recovery
461            .authorizations
462            .last()
463            .map(|a| a.granted_attempts)
464            .unwrap_or(0);
465        let Some(next_extra) = self.land_sync_recovery.extra_attempts.checked_add(granted) else {
466            return Err("landing base-sync grant counter overflow".into());
467        };
468        if granted != GRANT_ATTEMPTS || next_extra > MAX_GRANTS {
469            if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
470                auth.refuse(format!(
471                    "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
472                    self.land_sync_recovery.extra_attempts
473                ));
474            }
475            return Err("lifetime landing base-sync recovery limit reached".into());
476        }
477        let head_mismatch = self
478            .land_sync_recovery
479            .authorizations
480            .last()
481            .is_some_and(|a| {
482                !a.stop.head.eq_ignore_ascii_case(head)
483                    || !a.stop.pr_head.eq_ignore_ascii_case(pr_head)
484            });
485        if head_mismatch {
486            if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
487                auth.refuse(format!(
488                    "retained/published HEAD changed from {}/{} to {head}/{pr_head}",
489                    auth.stop.head, auth.stop.pr_head
490                ));
491            }
492            return Err("retained or published HEAD changed before consumption".into());
493        }
494
495        // Detach and preserve all prior verification evidence so fresh gate and
496        // current-head E2E MUST run even if HEAD stays unchanged.
497        let gate = std::mem::take(&mut self.gate);
498        let gate_head = self.gate_head.take();
499        let gate_ran = std::mem::replace(&mut self.gate_ran, false);
500        let head_e2e = self.head_e2e.take();
501        let gate_repair_e2e = self.gate_repair_e2e.take();
502        self.pre_gate.clear();
503        self.pre_gate_commit = None;
504
505        let mut review_verified_heads = Vec::with_capacity(self.reviews.len());
506        for review in &mut self.reviews {
507            review_verified_heads.push((review.round, review.verified_head.take()));
508        }
509
510        if gate_ran || !gate.is_empty() || head_e2e.is_some() {
511            self.verification_history.push(VerificationEvidence {
512                superseded_by: None,
513                archived_at: Some(now),
514                fixes_spent: Some(self.gate_fixes.len()),
515                gate_head: gate_head.clone(),
516                gate_ran,
517                gate: gate.clone(),
518                e2e: head_e2e.clone(),
519            });
520        }
521        if let Some(repair_e2e) = &gate_repair_e2e {
522            self.verification_history.push(VerificationEvidence {
523                superseded_by: None,
524                archived_at: Some(now),
525                fixes_spent: Some(self.gate_fixes.len()),
526                gate_head: None,
527                gate_ran: false,
528                gate: Vec::new(),
529                e2e: Some(repair_e2e.clone()),
530            });
531        }
532
533        let archived = ArchivedVerification {
534            archived_at: now,
535            head: head.to_ascii_lowercase(),
536            gate_head,
537            gate_ran,
538            gate,
539            head_e2e,
540            gate_repair_e2e,
541            review_verified_heads,
542        };
543
544        let auth = self
545            .land_sync_recovery
546            .authorizations
547            .last_mut()
548            .expect("pending authorization exists");
549        auth.consumed = true;
550        auth.consumed_at = Some(now);
551        auth.archived_verification = Some(archived);
552
553        self.land_sync_recovery.extra_attempts = next_extra;
554        self.land_sync_recovery.stop = None;
555        Ok(())
556    }
557}
558
559/// Retry an observation failure without changing the accepted owner generation.
560pub(crate) fn queue_existing_authorization(queue: &Queue, task: &mut Task, run: &str) -> bool {
561    let Some(state) = latest_exhausted_run(queue, task) else {
562        return false;
563    };
564    if state.id != run || !(state.land_sync_recovery_pending() || state.land_sync_unstarted_grant())
565    {
566        return false;
567    }
568    let Some(auth) = state.land_sync_recovery.authorizations.last() else {
569        return false;
570    };
571    if task.id != auth.task
572        || !task.assignment_accepts(&state)
573        || task.instruction != auth.scope.instruction
574        || task.operator_decided_at != auth.decision
575        || auth
576            .generation
577            .is_some_and(|g| task.resumption.as_ref().map(|r| r.generation) != Some(g))
578        || !task.land_sync_recovery_requests.contains(&auth.request)
579        || task.fresh_start
580        || task.review_branch.is_some()
581        || task.pr_recovery.is_some()
582        || matches!(task.status, TaskStatus::Running | TaskStatus::Done)
583    {
584        return false;
585    }
586    task.status = TaskStatus::Queued;
587    task.hold_source = None;
588    task.hold_reason = None;
589    task.held_at = None;
590    true
591}
592
593/// Whether `task`'s latest run is held by landing base-sync exhaustion without
594/// an active pending recovery authorization.
595pub(crate) fn held_task(queue: &Queue, task: &Task) -> bool {
596    held_run(queue, task).is_some()
597}
598
599/// Load `task`'s latest run when it is blocked on landing base-sync exhaustion
600/// without an active pending recovery authorization.
601pub(crate) fn held_run(queue: &Queue, task: &Task) -> Option<RunState> {
602    latest_exhausted_run(queue, task).filter(|state| !state.land_sync_recovery_pending())
603}
604
605/// Load `task`'s latest run whenever it is currently in landing base-sync exhaustion
606/// (with or without a pending recovery authorization).
607pub(crate) fn latest_exhausted_run(queue: &Queue, task: &Task) -> Option<RunState> {
608    let home = queue.root().parent()?;
609    task.execution_runs()
610        .last()
611        .and_then(|id| RunState::load_under(id, home).ok())
612        .filter(|state| {
613            state.land_sync_exhausted()
614                || state.has_unconsumed_land_sync_authorization()
615                || state.land_sync_unstarted_grant()
616        })
617}
618
619/// Revalidate all ownership, task, HEAD, open-PR, and base-lineage invariants
620/// for a pending landing sync recovery authorization.
621///
622/// Used both at daemon dispatch time (`task_override = Some(task)`) and after
623/// acquiring the execution lease inside `land_with` (`task_override = None`,
624/// `observed_override = Some(&observed_pr)`).
625#[derive(Debug)]
626pub(crate) struct ValidationFailure {
627    pub reason: String,
628    pub observation_failed: bool,
629}
630
631impl ValidationFailure {
632    fn observation(reason: String) -> Self {
633        Self {
634            reason,
635            observation_failed: true,
636        }
637    }
638}
639
640impl From<String> for ValidationFailure {
641    fn from(reason: String) -> Self {
642        Self {
643            reason,
644            observation_failed: false,
645        }
646    }
647}
648
649impl From<&str> for ValidationFailure {
650    fn from(reason: &str) -> Self {
651        reason.to_owned().into()
652    }
653}
654
655pub(crate) async fn validate_pending_authorization<O: PrObserver>(
656    home: &Path,
657    state: &RunState,
658    task_override: Option<&Task>,
659    observed_override: Option<&ObservedPr>,
660    observer: &O,
661) -> std::result::Result<(String, String), ValidationFailure> {
662    let unstarted = state.land_sync_unstarted_grant();
663    if !state.land_sync_recovery_pending() && !unstarted {
664        return Err("landing base-sync stop or pending authorization state changed".into());
665    }
666    if let Err(error) = crate::pr_head::ensure_owner(state) {
667        return Err(format!("run ownership check failed: {error:#}").into());
668    }
669    let auth = state
670        .land_sync_recovery
671        .authorizations
672        .last()
673        .ok_or_else(|| "missing pending landing base-sync authorization".to_owned())?;
674    if auth.invalidated.is_some() {
675        return Err("landing base-sync recovery authorization was invalidated".into());
676    }
677    if auth.granted_attempts != GRANT_ATTEMPTS
678        || (!unstarted && state.land_sync_grants_remaining() < auth.granted_attempts)
679    {
680        return Err(format!(
681            "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
682            state.land_sync_recovery.extra_attempts
683        )
684        .into());
685    }
686
687    if !auth.task.is_empty() {
688        let loaded_task;
689        let task = match task_override {
690            Some(task) => task,
691            None => {
692                loaded_task = Queue::at(home.join("queue")).get(&auth.task).map_err(|e| {
693                    ValidationFailure::observation(format!(
694                        "owning task {} unreadable: {e:#}",
695                        auth.task
696                    ))
697                })?;
698                &loaded_task
699            }
700        };
701        if task.id != auth.task {
702            return Err("authorization targets a different task".into());
703        }
704        if state
705            .origin
706            .as_ref()
707            .and_then(|o| o.task.as_deref())
708            .is_some_and(|owner| owner != task.id)
709        {
710            return Err("run belongs to another task".into());
711        }
712        if task.execution_runs().last().map(String::as_str) != Some(state.id.as_str()) {
713            return Err("run is no longer the task's latest execution".into());
714        }
715        if !task.assignment_accepts(state) || task.reassignments.len() != auth.scope.assignment {
716            return Err("task repository assignment changed since authorization".into());
717        }
718        if task.status == TaskStatus::Done
719            || task.fresh_start
720            || task.review_branch.is_some()
721            || task.pr_recovery.is_some()
722        {
723            return Err("task queue state changed since authorization".into());
724        }
725        if task.instruction != auth.scope.instruction
726            || !crate::daemon::compatible_run_instruction(state, task)
727        {
728            return Err("task instruction changed since authorization".into());
729        }
730        if task.operator_decided_at != auth.decision {
731            return Err("a newer owner decision superseded this recovery authorization".into());
732        }
733        if let Some(generation) = auth.generation
734            && task.resumption.as_ref().map(|r| r.generation) != Some(generation)
735        {
736            return Err("task resumption generation changed since authorization".into());
737        }
738        if task_override.is_some()
739            && !task
740                .resume_override
741                .as_ref()
742                .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
743            && !(task.resume_override.is_none()
744                && task.land_sync_recovery_requests.contains(&auth.request))
745        {
746            return Err("task exact-run pin is missing or targets another run".into());
747        }
748    }
749
750    let winner = state
751        .winner()
752        .ok_or_else(|| "run has no retained winner".to_owned())?;
753    let clean = git::is_clean(&winner.worktree).await.map_err(|e| {
754        ValidationFailure::observation(format!(
755            "could not inspect retained worktree cleanliness: {e:#}"
756        ))
757    })?;
758    if !clean {
759        return Err("retained worktree has uncommitted changes".into());
760    }
761    let scratch = home.join("runs").join(&state.id).join("rebase");
762    let rebase_in_progress = git::checked_rebase_in_progress(&scratch)
763        .await
764        .map_err(|e| {
765            ValidationFailure::observation(format!("could not inspect scratch rebase state: {e:#}"))
766        })?;
767    if rebase_in_progress {
768        return Err("landing rebase is already in progress in scratch worktree".into());
769    }
770    let local_head = git::rev_parse(&winner.worktree, "HEAD")
771        .await
772        .map_err(|e| {
773            ValidationFailure::observation(format!("could not read retained worktree HEAD: {e:#}"))
774        })?;
775    let branch_head = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
776        .await
777        .map_err(|e| {
778            ValidationFailure::observation(format!("could not read winner branch ref: {e:#}"))
779        })?;
780    if local_head != branch_head {
781        return Err("retained worktree HEAD does not match the winner branch ref".into());
782    }
783    if !local_head.eq_ignore_ascii_case(&auth.stop.head) {
784        return Err(format!(
785            "retained HEAD changed from {} to {local_head}",
786            auth.stop.head
787        )
788        .into());
789    }
790    if !state
791        .pr_pushed_head
792        .as_deref()
793        .is_some_and(|h| h.eq_ignore_ascii_case(&local_head))
794    {
795        return Err("saved pr_pushed_head no longer matches the retained HEAD".into());
796    }
797    if !auth.stop.pr_head.eq_ignore_ascii_case(&local_head)
798        || !auth.scope.pr_head.eq_ignore_ascii_case(&local_head)
799    {
800        return Err("authorized PR head does not match the retained HEAD".into());
801    }
802    if !state.pr.as_ref().is_some_and(|pr| {
803        pr.state == "open" && pr.url == auth.scope.pr_url && pr.number == auth.scope.pr_number
804    }) {
805        return Err("recorded pull request metadata changed since authorization".into());
806    }
807
808    let fetched_pr;
809    let observed = match observed_override {
810        Some(observed) => observed,
811        None => {
812            fetched_pr = observer
813                .observe_pr(&state.repo, &auth.scope.pr_url)
814                .await
815                .map_err(|e| {
816                    ValidationFailure::observation(format!(
817                        "could not verify open pull request state: {e:#}"
818                    ))
819                })?;
820            &fetched_pr
821        }
822    };
823    if !observed.open {
824        return Err("pull request is no longer open".into());
825    }
826    if observed.url != auth.scope.pr_url || observed.number != auth.scope.pr_number {
827        return Err("observed pull request does not match authorized pull request".into());
828    }
829    if observed.head.len() != 40 || !observed.head.bytes().all(|b| b.is_ascii_hexdigit()) {
830        return Err(ValidationFailure::observation(
831            "observed pull request head is unreadable".into(),
832        ));
833    }
834    if !observed.head.eq_ignore_ascii_case(&local_head) {
835        return Err(format!(
836            "published PR head changed from {} to {}",
837            auth.scope.pr_head, observed.head
838        )
839        .into());
840    }
841    if observed
842        .base_branch
843        .as_deref()
844        .is_some_and(|b| !b.is_empty() && b != state.base_branch)
845    {
846        return Err("pull request base branch changed since authorization".into());
847    }
848
849    let fetched = git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch)
850        .await
851        .map_err(|e| {
852            ValidationFailure::observation(format!(
853                "could not fetch base branch for revalidation: {e:#}"
854            ))
855        })?;
856    if !fetched.ok() {
857        return Err(ValidationFailure::observation(format!(
858            "could not fetch base branch for revalidation: {}",
859            fetched.stderr
860        )));
861    }
862    let onto = format!("{}/{}", state.config.merge.remote, state.base_branch);
863    let current_tip = git::rev_parse(&state.repo, &onto).await.map_err(|e| {
864        ValidationFailure::observation(format!("could not resolve fetched base tip: {e:#}"))
865    })?;
866    let descends_scope = git::ancestry(&state.repo, &auth.scope.tip, &current_tip)
867        .await
868        .map_err(|e| {
869            ValidationFailure::observation(format!(
870                "could not verify base tip lineage against authorized tip: {e:#}"
871            ))
872        })?;
873    if !descends_scope {
874        return Err(format!(
875            "fetched base tip {current_tip} does not fast-forward from authorized tip {}",
876            auth.scope.tip
877        )
878        .into());
879    }
880    let descends_stop = git::ancestry(&state.repo, &auth.stop.tip, &current_tip)
881        .await
882        .map_err(|e| {
883            ValidationFailure::observation(format!(
884                "could not verify base tip lineage against stopped tip: {e:#}"
885            ))
886        })?;
887    if !descends_stop {
888        return Err(format!(
889            "fetched base tip {current_tip} does not fast-forward from stopped tip {}",
890            auth.stop.tip
891        )
892        .into());
893    }
894
895    Ok((local_head, observed.head.clone()))
896}
897
898/// Result of dispatch-time revalidation for a landing base-sync exhaustion stop.
899pub(crate) enum DispatchDecision {
900    /// Proceed with ordinary execution or validated landing sync recovery.
901    Proceed,
902    /// Hold the task without spending an attempt or starting a replacement run.
903    Hold {
904        reason: String,
905        state: Box<RunState>,
906    },
907}
908
909/// Dispatch-time gate using `gh pr view` to revalidate pending recovery approvals.
910pub(crate) async fn dispatch_check(queue: &Queue, home: &Path, task: &Task) -> DispatchDecision {
911    dispatch_check_with(queue, home, task, &GhPrObserver).await
912}
913
914/// Injectable dispatch-time gate for unit and integration testing.
915pub(crate) async fn dispatch_check_with<O: PrObserver>(
916    queue: &Queue,
917    home: &Path,
918    task: &Task,
919    observer: &O,
920) -> DispatchDecision {
921    let Some(state) = latest_exhausted_run(queue, task) else {
922        return DispatchDecision::Proceed;
923    };
924    // Explicit exact-run resume may observe an externally closed PR without
925    // authorizing any branch synchronization.
926    if task
927        .resume_override
928        .as_ref()
929        .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
930        && let Some(pr) = &state.pr
931        && let Ok(observed) = observer.observe_pr(&state.repo, &pr.url).await
932        && !observed.open
933        && observed.url == pr.url
934        && observed.number == pr.number
935    {
936        return DispatchDecision::Proceed;
937    }
938    if !state.has_unconsumed_land_sync_authorization() && !state.land_sync_unstarted_grant() {
939        return DispatchDecision::Hold {
940            reason: format!(
941                "Landing base synchronization remains stopped. {} Ordinary resume or release grants no additional synchronization budget and starts no replacement competition.",
942                state.land_sync_next_action()
943            ),
944            state: Box::new(state),
945        };
946    }
947    match validate_pending_authorization(home, &state, Some(task), None, observer).await {
948        Ok(_) => DispatchDecision::Proceed,
949        Err(failure) => {
950            let reason = failure.reason;
951            let mut updated = state;
952            if !failure.observation_failed
953                && let Ok(_owner) = crate::pr_head::owner_lock(home, &updated.id)
954                && let Ok(mut reloaded) = RunState::load_under(&updated.id, home)
955                && let Ok(claimed) =
956                    crate::daemon::is_working_on_other(home, &reloaded.id, Timestamp::now())
957                && reloaded.liveness_under(home, claimed) == crate::run::Liveness::Dead
958                && let Ok(_exec) = crate::driver::maintenance(home, &reloaded.id)
959                && (reloaded.land_sync_recovery_pending() || reloaded.land_sync_unstarted_grant())
960                && let Some(auth) = reloaded.land_sync_recovery.authorizations.last_mut()
961                && auth.invalidated.is_none()
962                && updated
963                    .land_sync_recovery
964                    .authorizations
965                    .last()
966                    .is_some_and(|prior| prior.request == auth.request)
967            {
968                auth.refuse(&reason);
969                reloaded.event(
970                    "land-sync-recovery",
971                    format!("dispatch revalidation refused: {reason}"),
972                );
973                let _ = reloaded.save_under(home);
974                updated = reloaded;
975            }
976            DispatchDecision::Hold {
977                reason: format!(
978                    "Landing base-sync recovery refused at dispatch: {reason}. {}",
979                    updated.land_sync_next_action()
980                ),
981                state: Box::new(updated),
982            }
983        }
984    }
985}
986
987impl Task {
988    /// Anchor a landing base-sync exhaustion hold stably across driver passes.
989    pub(crate) fn land_sync_notice(&mut self, state: &RunState) {
990        if !state.land_sync_exhausted() {
991            return;
992        }
993        let stop = state.land_sync_recovery.stop.as_ref();
994        self.held_at = Some(stop.map_or_else(|| exhausted_stop_timestamp(state), |s| s.at));
995        self.notice_cause("land-sync-exhausted", Some(&state.id), None);
996        if let Some(cause) = &mut self.hold_notice_cause {
997            cause.target = Some(match stop {
998                Some(s) => format!("{}:{}:{}:{}", s.head, s.attempts, s.limit, s.at),
999                None => format!(
1000                    "legacy:{}:{}:{}",
1001                    state.pr_pushed_head.as_deref().unwrap_or("unknown"),
1002                    state.land_sync_attempts,
1003                    state.land_sync_budget()
1004                ),
1005            });
1006        }
1007    }
1008}