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