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                || (self.land_sync_recovery.stops.is_empty()
319                    && self.land_sync_recovery.authorizations.is_empty()
320                    && legacy_exhausted_diagnostic(self))
321        }
322    }
323
324    /// Whether any landing sync recovery authorization is still unconsumed.
325    pub fn has_unconsumed_land_sync_authorization(&self) -> bool {
326        self.land_sync_recovery
327            .authorizations
328            .iter()
329            .any(|a| !a.consumed && a.invalidated.is_none())
330    }
331
332    /// Whether the active landing exhaustion stop has a matching unconsumed authorization.
333    pub fn land_sync_recovery_pending(&self) -> bool {
334        self.land_sync_exhausted()
335            && self
336                .land_sync_recovery
337                .authorizations
338                .last()
339                .is_some_and(|a| {
340                    !a.consumed
341                        && a.invalidated.is_none()
342                        && a.run == self.id
343                        && a.granted_attempts == GRANT_ATTEMPTS
344                        && a.scope.grant_index == self.land_sync_recovery.extra_attempts
345                        && self.land_sync_recovery.stop.as_ref() == Some(&a.stop)
346                })
347    }
348
349    /// A grant was saved but its synchronization attempt has not been charged.
350    /// A refused grant no longer contributes to the effective attempt budget.
351    pub(crate) fn land_sync_unstarted_grant(&self) -> bool {
352        self.status.resumable()
353            && self
354                .land_sync_recovery
355                .authorizations
356                .last()
357                .is_some_and(|a| {
358                    a.consumed
359                        && a.invalidated.is_none()
360                        && a.archived_verification.is_some()
361                        && self.land_sync_attempts == a.stop.attempts
362                        && self.land_sync_recovery.extra_attempts
363                            == a.scope.grant_index.saturating_add(GRANT_ATTEMPTS)
364                })
365    }
366
367    /// Single-line actionable guidance for CLI, notices, and reports.
368    pub fn land_sync_next_action(&self) -> String {
369        let attempts = self.land_sync_attempts;
370        let limit = self.land_sync_budget();
371        let grants = self.land_sync_recovery.extra_attempts;
372        let head = self
373            .land_sync_recovery
374            .stop
375            .as_ref()
376            .map(|s| s.head.as_str())
377            .or(self.pr_pushed_head.as_deref())
378            .unwrap_or("<full-head-sha>");
379        if let Some(reason) = self
380            .land_sync_recovery
381            .authorizations
382            .last()
383            .and_then(|a| a.invalidated.as_ref())
384            && !self.land_sync_recovery_pending()
385        {
386            if self.land_sync_grants_remaining() == 0 {
387                return format!(
388                    "Landing base-sync recovery approval invalidated: {reason}; lifetime grant limit reached ({grants}/{MAX_GRANTS})"
389                );
390            }
391            return format!(
392                "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)",
393                self.id
394            );
395        }
396        if self.land_sync_recovery_pending() || self.land_sync_unstarted_grant() {
397            return format!(
398                "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)"
399            );
400        }
401        if self.land_sync_grants_remaining() == 0 {
402            return format!(
403                "Lifetime landing base-sync recovery limit reached ({grants}/{MAX_GRANTS} grants used, {attempts}/{limit} attempts); inspect the retained branch and PR before manual intervention"
404            );
405        }
406        format!(
407            "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)",
408            self.id
409        )
410    }
411
412    /// Persist a stable structured stop snapshot on landing sync exhaustion.
413    pub(crate) fn record_land_sync_exhausted_stop(&mut self, head: &str, pr_head: &str, tip: &str) {
414        let Some(pr) = self.pr.as_ref() else {
415            return;
416        };
417        let limit = self.land_sync_budget();
418        if self.land_sync_recovery.stop.as_ref().is_some_and(|s| {
419            s.attempts == self.land_sync_attempts
420                && s.limit == limit
421                && s.head.eq_ignore_ascii_case(head)
422                && s.pr_head.eq_ignore_ascii_case(pr_head)
423                && s.pr_url == pr.url
424                && s.pr_number == pr.number
425                && s.detail == EXHAUSTED_DETAIL
426        }) {
427            return;
428        }
429        let at = exhausted_stop_timestamp(self);
430        let stop = Stop {
431            attempts: self.land_sync_attempts,
432            limit,
433            head: head.to_ascii_lowercase(),
434            pr_head: pr_head.to_ascii_lowercase(),
435            pr_url: pr.url.clone(),
436            pr_number: pr.number,
437            tip: tip.to_ascii_lowercase(),
438            detail: EXHAUSTED_DETAIL.to_owned(),
439            at,
440        };
441        if !self.land_sync_recovery.stops.contains(&stop) {
442            self.land_sync_recovery.stops.push(stop.clone());
443        }
444        self.land_sync_recovery.stop = Some(stop);
445    }
446
447    /// Atomically consume a validated pending authorization, add its bounded
448    /// extra attempt, archive prior verification evidence, and require fresh
449    /// head-bound E2E and gate before publication.
450    ///
451    /// Callers MUST save `RunState` immediately before running any Git mutation.
452    pub(crate) fn consume_land_sync_recovery(
453        &mut self,
454        head: &str,
455        pr_head: &str,
456    ) -> std::result::Result<(), String> {
457        if !self.land_sync_recovery_pending() {
458            return Err("no matching pending landing base-sync recovery authorization".into());
459        }
460        let now = Timestamp::now();
461        let granted = self
462            .land_sync_recovery
463            .authorizations
464            .last()
465            .map(|a| a.granted_attempts)
466            .unwrap_or(0);
467        let Some(next_extra) = self.land_sync_recovery.extra_attempts.checked_add(granted) else {
468            return Err("landing base-sync grant counter overflow".into());
469        };
470        if granted != GRANT_ATTEMPTS || next_extra > MAX_GRANTS {
471            if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
472                auth.refuse(format!(
473                    "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
474                    self.land_sync_recovery.extra_attempts
475                ));
476            }
477            return Err("lifetime landing base-sync recovery limit reached".into());
478        }
479        let head_mismatch = self
480            .land_sync_recovery
481            .authorizations
482            .last()
483            .is_some_and(|a| {
484                !a.stop.head.eq_ignore_ascii_case(head)
485                    || !a.stop.pr_head.eq_ignore_ascii_case(pr_head)
486            });
487        if head_mismatch {
488            if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
489                auth.refuse(format!(
490                    "retained/published HEAD changed from {}/{} to {head}/{pr_head}",
491                    auth.stop.head, auth.stop.pr_head
492                ));
493            }
494            return Err("retained or published HEAD changed before consumption".into());
495        }
496
497        // Detach and preserve all prior verification evidence so fresh gate and
498        // current-head E2E MUST run even if HEAD stays unchanged.
499        let gate = std::mem::take(&mut self.gate);
500        let gate_head = self.gate_head.take();
501        let gate_ran = std::mem::replace(&mut self.gate_ran, false);
502        let head_e2e = self.head_e2e.take();
503        let gate_repair_e2e = self.gate_repair_e2e.take();
504        self.pre_gate.clear();
505        self.pre_gate_commit = None;
506
507        let mut review_verified_heads = Vec::with_capacity(self.reviews.len());
508        for review in &mut self.reviews {
509            review_verified_heads.push((review.round, review.verified_head.take()));
510        }
511
512        if gate_ran || !gate.is_empty() || head_e2e.is_some() {
513            self.verification_history.push(VerificationEvidence {
514                superseded_by: None,
515                archived_at: Some(now),
516                fixes_spent: Some(self.gate_fixes.len()),
517                gate_head: gate_head.clone(),
518                gate_ran,
519                gate: gate.clone(),
520                e2e: head_e2e.clone(),
521            });
522        }
523        if let Some(repair_e2e) = &gate_repair_e2e {
524            self.verification_history.push(VerificationEvidence {
525                superseded_by: None,
526                archived_at: Some(now),
527                fixes_spent: Some(self.gate_fixes.len()),
528                gate_head: None,
529                gate_ran: false,
530                gate: Vec::new(),
531                e2e: Some(repair_e2e.clone()),
532            });
533        }
534
535        let archived = ArchivedVerification {
536            archived_at: now,
537            head: head.to_ascii_lowercase(),
538            gate_head,
539            gate_ran,
540            gate,
541            head_e2e,
542            gate_repair_e2e,
543            review_verified_heads,
544        };
545
546        let auth = self
547            .land_sync_recovery
548            .authorizations
549            .last_mut()
550            .expect("pending authorization exists");
551        auth.consumed = true;
552        auth.consumed_at = Some(now);
553        auth.archived_verification = Some(archived);
554
555        self.land_sync_recovery.extra_attempts = next_extra;
556        self.land_sync_recovery.stop = None;
557        Ok(())
558    }
559}
560
561/// Retry an observation failure without changing the accepted owner generation.
562pub(crate) fn queue_existing_authorization(queue: &Queue, task: &mut Task, run: &str) -> bool {
563    let Some(state) = latest_exhausted_run(queue, task) else {
564        return false;
565    };
566    if state.id != run || !(state.land_sync_recovery_pending() || state.land_sync_unstarted_grant())
567    {
568        return false;
569    }
570    let Some(auth) = state.land_sync_recovery.authorizations.last() else {
571        return false;
572    };
573    if task.id != auth.task
574        || !task.assignment_accepts(&state)
575        || task.instruction != auth.scope.instruction
576        || task.operator_decided_at != auth.decision
577        || auth
578            .generation
579            .is_some_and(|g| task.resumption.as_ref().map(|r| r.generation) != Some(g))
580        || !task.land_sync_recovery_requests.contains(&auth.request)
581        || task.fresh_start
582        || task.review_branch.is_some()
583        || task.pr_recovery.is_some()
584        || matches!(task.status, TaskStatus::Running | TaskStatus::Done)
585    {
586        return false;
587    }
588    task.status = TaskStatus::Queued;
589    task.hold_source = None;
590    task.hold_reason = None;
591    task.held_at = None;
592    true
593}
594
595/// Whether `task`'s latest run is held by landing base-sync exhaustion without
596/// an active pending recovery authorization.
597pub(crate) fn held_task(queue: &Queue, task: &Task) -> bool {
598    held_run(queue, task).is_some()
599}
600
601/// Load `task`'s latest run when it is blocked on landing base-sync exhaustion
602/// without an active pending recovery authorization.
603pub(crate) fn held_run(queue: &Queue, task: &Task) -> Option<RunState> {
604    latest_exhausted_run(queue, task).filter(|state| !state.land_sync_recovery_pending())
605}
606
607/// Load `task`'s latest run whenever it is currently in landing base-sync exhaustion
608/// (with or without a pending recovery authorization).
609pub(crate) fn latest_exhausted_run(queue: &Queue, task: &Task) -> Option<RunState> {
610    let home = queue.root().parent()?;
611    task.execution_runs()
612        .last()
613        .and_then(|id| RunState::load_under(id, home).ok())
614        .filter(|state| {
615            state.land_sync_exhausted()
616                || state.has_unconsumed_land_sync_authorization()
617                || state.land_sync_unstarted_grant()
618        })
619}
620
621/// Revalidate all ownership, task, HEAD, open-PR, and base-lineage invariants
622/// for a pending landing sync recovery authorization.
623///
624/// Used both at daemon dispatch time (`task_override = Some(task)`) and after
625/// acquiring the execution lease inside `land_with` (`task_override = None`,
626/// `observed_override = Some(&observed_pr)`).
627#[derive(Debug)]
628pub(crate) struct ValidationFailure {
629    pub reason: String,
630    pub observation_failed: bool,
631}
632
633impl ValidationFailure {
634    fn observation(reason: String) -> Self {
635        Self {
636            reason,
637            observation_failed: true,
638        }
639    }
640}
641
642impl From<String> for ValidationFailure {
643    fn from(reason: String) -> Self {
644        Self {
645            reason,
646            observation_failed: false,
647        }
648    }
649}
650
651impl From<&str> for ValidationFailure {
652    fn from(reason: &str) -> Self {
653        reason.to_owned().into()
654    }
655}
656
657pub(crate) async fn validate_pending_authorization<O: PrObserver>(
658    home: &Path,
659    state: &RunState,
660    task_override: Option<&Task>,
661    observed_override: Option<&ObservedPr>,
662    observer: &O,
663) -> std::result::Result<(String, String), ValidationFailure> {
664    let unstarted = state.land_sync_unstarted_grant();
665    if !state.land_sync_recovery_pending() && !unstarted {
666        return Err("landing base-sync stop or pending authorization state changed".into());
667    }
668    if let Err(error) = crate::pr_head::ensure_owner(state) {
669        return Err(format!("run ownership check failed: {error:#}").into());
670    }
671    let auth = state
672        .land_sync_recovery
673        .authorizations
674        .last()
675        .ok_or_else(|| "missing pending landing base-sync authorization".to_owned())?;
676    if auth.invalidated.is_some() {
677        return Err("landing base-sync recovery authorization was invalidated".into());
678    }
679    if auth.granted_attempts != GRANT_ATTEMPTS
680        || (!unstarted && state.land_sync_grants_remaining() < auth.granted_attempts)
681    {
682        return Err(format!(
683            "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
684            state.land_sync_recovery.extra_attempts
685        )
686        .into());
687    }
688
689    if !auth.task.is_empty() {
690        let loaded_task;
691        let task = match task_override {
692            Some(task) => task,
693            None => {
694                loaded_task = Queue::at(home.join("queue")).get(&auth.task).map_err(|e| {
695                    ValidationFailure::observation(format!(
696                        "owning task {} unreadable: {e:#}",
697                        auth.task
698                    ))
699                })?;
700                &loaded_task
701            }
702        };
703        if task.id != auth.task {
704            return Err("authorization targets a different task".into());
705        }
706        if state
707            .origin
708            .as_ref()
709            .and_then(|o| o.task.as_deref())
710            .is_some_and(|owner| owner != task.id)
711        {
712            return Err("run belongs to another task".into());
713        }
714        if task.execution_runs().last().map(String::as_str) != Some(state.id.as_str()) {
715            return Err("run is no longer the task's latest execution".into());
716        }
717        if !task.assignment_accepts(state) || task.reassignments.len() != auth.scope.assignment {
718            return Err("task repository assignment changed since authorization".into());
719        }
720        if task.status == TaskStatus::Done
721            || task.fresh_start
722            || task.review_branch.is_some()
723            || task.pr_recovery.is_some()
724        {
725            return Err("task queue state changed since authorization".into());
726        }
727        if task.instruction != auth.scope.instruction
728            || !crate::daemon::compatible_run_instruction(state, task)
729        {
730            return Err("task instruction changed since authorization".into());
731        }
732        if task.operator_decided_at != auth.decision {
733            return Err("a newer owner decision superseded this recovery authorization".into());
734        }
735        if let Some(generation) = auth.generation
736            && task.resumption.as_ref().map(|r| r.generation) != Some(generation)
737        {
738            return Err("task resumption generation changed since authorization".into());
739        }
740        if task_override.is_some()
741            && !task
742                .resume_override
743                .as_ref()
744                .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
745            && !(task.resume_override.is_none()
746                && task.land_sync_recovery_requests.contains(&auth.request))
747        {
748            return Err("task exact-run pin is missing or targets another run".into());
749        }
750    }
751
752    let winner = state
753        .winner()
754        .ok_or_else(|| "run has no retained winner".to_owned())?;
755    let clean = git::is_clean(&winner.worktree).await.map_err(|e| {
756        ValidationFailure::observation(format!(
757            "could not inspect retained worktree cleanliness: {e:#}"
758        ))
759    })?;
760    if !clean {
761        return Err("retained worktree has uncommitted changes".into());
762    }
763    let scratch = home.join("runs").join(&state.id).join("rebase");
764    let rebase_in_progress = git::checked_rebase_in_progress(&scratch)
765        .await
766        .map_err(|e| {
767            ValidationFailure::observation(format!("could not inspect scratch rebase state: {e:#}"))
768        })?;
769    if rebase_in_progress {
770        return Err("landing rebase is already in progress in scratch worktree".into());
771    }
772    let local_head = git::rev_parse(&winner.worktree, "HEAD")
773        .await
774        .map_err(|e| {
775            ValidationFailure::observation(format!("could not read retained worktree HEAD: {e:#}"))
776        })?;
777    let branch_head = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
778        .await
779        .map_err(|e| {
780            ValidationFailure::observation(format!("could not read winner branch ref: {e:#}"))
781        })?;
782    if local_head != branch_head {
783        return Err("retained worktree HEAD does not match the winner branch ref".into());
784    }
785    if !local_head.eq_ignore_ascii_case(&auth.stop.head) {
786        return Err(format!(
787            "retained HEAD changed from {} to {local_head}",
788            auth.stop.head
789        )
790        .into());
791    }
792    if !state
793        .pr_pushed_head
794        .as_deref()
795        .is_some_and(|h| h.eq_ignore_ascii_case(&local_head))
796    {
797        return Err("saved pr_pushed_head no longer matches the retained HEAD".into());
798    }
799    if !auth.stop.pr_head.eq_ignore_ascii_case(&local_head)
800        || !auth.scope.pr_head.eq_ignore_ascii_case(&local_head)
801    {
802        return Err("authorized PR head does not match the retained HEAD".into());
803    }
804    if !state.pr.as_ref().is_some_and(|pr| {
805        pr.state == "open" && pr.url == auth.scope.pr_url && pr.number == auth.scope.pr_number
806    }) {
807        return Err("recorded pull request metadata changed since authorization".into());
808    }
809
810    let fetched_pr;
811    let observed = match observed_override {
812        Some(observed) => observed,
813        None => {
814            fetched_pr = observer
815                .observe_pr(&state.repo, &auth.scope.pr_url)
816                .await
817                .map_err(|e| {
818                    ValidationFailure::observation(format!(
819                        "could not verify open pull request state: {e:#}"
820                    ))
821                })?;
822            &fetched_pr
823        }
824    };
825    if !observed.open {
826        return Err("pull request is no longer open".into());
827    }
828    if observed.url != auth.scope.pr_url || observed.number != auth.scope.pr_number {
829        return Err("observed pull request does not match authorized pull request".into());
830    }
831    if observed.head.len() != 40 || !observed.head.bytes().all(|b| b.is_ascii_hexdigit()) {
832        return Err(ValidationFailure::observation(
833            "observed pull request head is unreadable".into(),
834        ));
835    }
836    if !observed.head.eq_ignore_ascii_case(&local_head) {
837        return Err(format!(
838            "published PR head changed from {} to {}",
839            auth.scope.pr_head, observed.head
840        )
841        .into());
842    }
843    if observed
844        .base_branch
845        .as_deref()
846        .is_some_and(|b| !b.is_empty() && b != state.base_branch)
847    {
848        return Err("pull request base branch changed since authorization".into());
849    }
850
851    let fetched = git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch)
852        .await
853        .map_err(|e| {
854            ValidationFailure::observation(format!(
855                "could not fetch base branch for revalidation: {e:#}"
856            ))
857        })?;
858    if !fetched.ok() {
859        return Err(ValidationFailure::observation(format!(
860            "could not fetch base branch for revalidation: {}",
861            fetched.stderr
862        )));
863    }
864    let onto = format!("{}/{}", state.config.merge.remote, state.base_branch);
865    let current_tip = git::rev_parse(&state.repo, &onto).await.map_err(|e| {
866        ValidationFailure::observation(format!("could not resolve fetched base tip: {e:#}"))
867    })?;
868    let descends_scope = git::ancestry(&state.repo, &auth.scope.tip, &current_tip)
869        .await
870        .map_err(|e| {
871            ValidationFailure::observation(format!(
872                "could not verify base tip lineage against authorized tip: {e:#}"
873            ))
874        })?;
875    if !descends_scope {
876        return Err(format!(
877            "fetched base tip {current_tip} does not fast-forward from authorized tip {}",
878            auth.scope.tip
879        )
880        .into());
881    }
882    let descends_stop = git::ancestry(&state.repo, &auth.stop.tip, &current_tip)
883        .await
884        .map_err(|e| {
885            ValidationFailure::observation(format!(
886                "could not verify base tip lineage against stopped tip: {e:#}"
887            ))
888        })?;
889    if !descends_stop {
890        return Err(format!(
891            "fetched base tip {current_tip} does not fast-forward from stopped tip {}",
892            auth.stop.tip
893        )
894        .into());
895    }
896
897    Ok((local_head, observed.head.clone()))
898}
899
900/// Result of dispatch-time revalidation for a landing base-sync exhaustion stop.
901pub(crate) enum DispatchDecision {
902    /// Proceed with ordinary execution or validated landing sync recovery.
903    Proceed,
904    /// Hold the task without spending an attempt or starting a replacement run.
905    Hold {
906        reason: String,
907        state: Box<RunState>,
908    },
909}
910
911/// Dispatch-time gate using `gh pr view` to revalidate pending recovery approvals.
912pub(crate) async fn dispatch_check(queue: &Queue, home: &Path, task: &Task) -> DispatchDecision {
913    dispatch_check_with(queue, home, task, &GhPrObserver).await
914}
915
916/// Injectable dispatch-time gate for unit and integration testing.
917pub(crate) async fn dispatch_check_with<O: PrObserver>(
918    queue: &Queue,
919    home: &Path,
920    task: &Task,
921    observer: &O,
922) -> DispatchDecision {
923    let Some(state) = latest_exhausted_run(queue, task) else {
924        return DispatchDecision::Proceed;
925    };
926    // Explicit exact-run resume may observe an externally closed PR without
927    // authorizing any branch synchronization.
928    if task
929        .resume_override
930        .as_ref()
931        .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
932        && let Some(pr) = &state.pr
933        && let Ok(observed) = observer.observe_pr(&state.repo, &pr.url).await
934        && !observed.open
935        && observed.url == pr.url
936        && observed.number == pr.number
937    {
938        return DispatchDecision::Proceed;
939    }
940    if !state.has_unconsumed_land_sync_authorization() && !state.land_sync_unstarted_grant() {
941        return DispatchDecision::Hold {
942            reason: format!(
943                "Landing base synchronization remains stopped. {} Ordinary resume or release grants no additional synchronization budget and starts no replacement competition.",
944                state.land_sync_next_action()
945            ),
946            state: Box::new(state),
947        };
948    }
949    match validate_pending_authorization(home, &state, Some(task), None, observer).await {
950        Ok(_) => DispatchDecision::Proceed,
951        Err(failure) => {
952            let reason = failure.reason;
953            let mut updated = state;
954            if !failure.observation_failed
955                && let Ok(_owner) = crate::pr_head::owner_lock(home, &updated.id)
956                && let Ok(mut reloaded) = RunState::load_under(&updated.id, home)
957                && let Ok(claimed) =
958                    crate::daemon::is_working_on_other(home, &reloaded.id, Timestamp::now())
959                && reloaded.liveness_under(home, claimed) == crate::run::Liveness::Dead
960                && let Ok(_exec) = crate::driver::maintenance(home, &reloaded.id)
961                && (reloaded.land_sync_recovery_pending() || reloaded.land_sync_unstarted_grant())
962                && let Some(auth) = reloaded.land_sync_recovery.authorizations.last_mut()
963                && auth.invalidated.is_none()
964                && updated
965                    .land_sync_recovery
966                    .authorizations
967                    .last()
968                    .is_some_and(|prior| prior.request == auth.request)
969            {
970                auth.refuse(&reason);
971                reloaded.event(
972                    "land-sync-recovery",
973                    format!("dispatch revalidation refused: {reason}"),
974                );
975                let _ = reloaded.save_under(home);
976                updated = reloaded;
977            }
978            DispatchDecision::Hold {
979                reason: format!(
980                    "Landing base-sync recovery refused at dispatch: {reason}. {}",
981                    updated.land_sync_next_action()
982                ),
983                state: Box::new(updated),
984            }
985        }
986    }
987}
988
989impl Task {
990    /// Anchor a landing base-sync exhaustion hold stably across driver passes.
991    pub(crate) fn land_sync_notice(&mut self, state: &RunState) {
992        if !state.land_sync_exhausted() {
993            return;
994        }
995        let stop = state.land_sync_recovery.stop.as_ref();
996        self.held_at = Some(stop.map_or_else(|| exhausted_stop_timestamp(state), |s| s.at));
997        self.notice_cause("land-sync-exhausted", Some(&state.id), None);
998        if let Some(cause) = &mut self.hold_notice_cause {
999            cause.target = Some(match stop {
1000                Some(s) => format!("{}:{}:{}:{}", s.head, s.attempts, s.limit, s.at),
1001                None => format!(
1002                    "legacy:{}:{}:{}",
1003                    state.pr_pushed_head.as_deref().unwrap_or("unknown"),
1004                    state.land_sync_attempts,
1005                    state.land_sync_budget()
1006                ),
1007            });
1008        }
1009    }
1010}