Skip to main content

magi/
pr_recovery.rs

1//! Explicit recovery of a task's public implementation, independent of historical candidates.
2
3use std::path::Path;
4
5use anyhow::{Context, Result, ensure};
6use serde::{Deserialize, Serialize};
7
8use crate::{
9    config::{Config, MergeMode},
10    git, land,
11};
12
13/// Explicit purpose of an existing-PR recovery; never inferred from task prose.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
15#[serde(rename_all = "snake_case")]
16pub enum Disposition {
17    /// Validate, publish to the selected PR and request fresh owner-approved landing.
18    Land,
19    /// Finish after local review, without public delivery.
20    Review,
21}
22
23/// Inputs of the single configuration load used to start a recovery.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ConfigEvidence {
26    /// Ordered configuration inputs; remote cache paths include the immutable source commit.
27    pub layers: Vec<std::path::PathBuf>,
28    /// Task options applied after loading the layers.
29    pub overrides: Option<crate::queue::RunOverrides>,
30    /// Daemon merge override, only when this task inherits daemon options.
31    pub daemon_merge: Option<String>,
32}
33
34/// Durable operator selection. Only the recovery command creates this record.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct Selection {
37    /// Existing pull request in this repository.
38    pub url: String,
39    /// Task-scoped public branch.
40    pub branch: String,
41    /// Initial public publication lease, independent of the implementation source.
42    pub head: String,
43    /// Full immutable source commit; older selections used the public lease.
44    #[serde(default)]
45    pub source_head: Option<String>,
46    /// Historical run explicitly selected to prove a launcher rebase.
47    #[serde(default)]
48    pub source_run: Option<String>,
49    /// Immutable proof, recomputed before starting or resuming work.
50    #[serde(default)]
51    pub source_proof: Option<Box<SourceProof>>,
52    /// Missing on old records: requires an explicit new selection before work.
53    #[serde(default)]
54    pub disposition: Option<Disposition>,
55    /// Criteria the operator approved, retained without rewriting them.
56    pub instruction: String,
57    /// Approval generation: a later selection does not resume an earlier run.
58    pub approved_at: jiff::Timestamp,
59}
60
61mod lineage;
62pub use lineage::SourceProof;
63
64const RETAIN_SOURCES: &str = "retain-recovery-sources";
65
66/// Preserve every historical run's source artifacts before releasing a recovery task.
67/// A sidecar survives stale run-state saves and applies even to older run schemas.
68pub fn retain_sources(task: &crate::queue::Task, home: &Path) -> Result<()> {
69    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
70        ensure!(
71            crate::run::is_run_id(id),
72            "invalid historical run id; refusing source retention"
73        );
74        let dir = home.join("runs").join(id);
75        ensure!(
76            dir.is_dir(),
77            "historical run {id} is missing; cannot retain its sources"
78        );
79        std::fs::write(dir.join(RETAIN_SOURCES), &task.id)
80            .with_context(|| format!("retaining sources of historical run {id}"))?;
81    }
82    Ok(())
83}
84
85/// Return the retention reason rather than silently treating fold as successful.
86pub(crate) fn source_retention_reason(home: &Path, state: &crate::run::RunState) -> Option<String> {
87    if explicit_sources_retained(home, &state.id) {
88        return Some("explicitly retained recovery source".into());
89    }
90    // A confirmed merge admits fold preflight even while the queue is held.
91    // fold_run must still prove each deletion target under its ownership and
92    // output locks. Ready/Failed/Superseded and PR creation alone do not qualify.
93    if state.status == crate::run::RunStatus::Merged
94        && state.merge.as_ref().is_some_and(|merged| merged.ok)
95    {
96        return None;
97    }
98    crate::queue::Queue::at(home.join("queue"))
99        .list()
100        .iter()
101        // Queue completion does not prove that every historical candidate
102        // landed. In particular, Superseded and Failed-without-tally runs
103        // may still own independent implementations. Keep those sources
104        // until recovery transfers them or confirmed-merge preflight captures
105        // durable source evidence; Done is not deletion authority.
106        .find(|task| task.runs.contains(&state.id))
107        .map(|task| {
108            format!(
109                "source of task {}; inspect recovery lineage before folding",
110                task.id
111            )
112        })
113}
114
115pub(crate) fn explicit_sources_retained(home: &Path, id: &str) -> bool {
116    home.join("runs")
117        .join(id)
118        .join(RETAIN_SOURCES)
119        .try_exists()
120        .unwrap_or(true)
121}
122
123impl Selection {
124    /// Immutable implementation commit, distinct from the public update lease.
125    pub fn source(&self) -> &str {
126        self.source_head.as_deref().unwrap_or(&self.head)
127    }
128
129    /// Reconcile only the delivery controls; preserve all other resolved settings.
130    pub fn configure(&self, config: &mut Config) -> Result<()> {
131        match self.disposition {
132            Some(Disposition::Land) => {
133                ensure!(
134                    config.graph.reviewers > 0 && config.graph.review_rounds > 0,
135                    "delivery requires at least one reviewer and review round"
136                );
137                ensure!(
138                    !config.verify.gate.is_empty()
139                        && config.verify.gate.iter().all(|s| !s.trim().is_empty()),
140                    "delivery requires nonempty verify.gate commands; configure the repository's documented gate in a machine/repository layer or recover-pr --config <complete-config>"
141                );
142                ensure!(
143                    !config.verify.e2e.is_empty()
144                        && config.verify.e2e.iter().all(|s| !s.trim().is_empty()),
145                    "delivery requires nonempty verify.e2e commands; configure the repository's required real-machine checks before recover-pr --disposition land"
146                );
147                config.merge.mode = MergeMode::Pr;
148                config.graph.land = true;
149                config.graph.land_approval = true;
150            }
151            Some(Disposition::Review) => {
152                config.merge.mode = MergeMode::None;
153                config.graph.land = false;
154            }
155            None => anyhow::bail!(
156                "recovery disposition is missing; select the public head again with recover-pr --disposition land or --disposition review (and --source-head <full-SHA> to preserve a reviewed fix)"
157            ),
158        }
159        Ok(())
160    }
161
162    /// Prove the adopted fix contains the selected public implementation.
163    pub async fn verify_source(&self, repo: &Path) -> Result<()> {
164        if self.source_proof.is_some() {
165            self.verify_source_under(repo, &crate::run::home()).await
166        } else {
167            self.verify_source_under(repo, Path::new("")).await
168        }
169    }
170
171    async fn verify_source_under(&self, repo: &Path, home: &Path) -> Result<()> {
172        let source = git::rev_parse(repo, &format!("{}^{{commit}}", self.source())).await?;
173        ensure!(
174            source == self.source(),
175            "source-head must resolve to its full commit SHA"
176        );
177        if let Some(proof) = &self.source_proof {
178            // Historical state is large; keep replay out of the caller's future storage.
179            let actual = Box::pin(lineage::prove(self, repo, home, &proof.current_base)).await?;
180            ensure!(
181                &actual == proof.as_ref(),
182                "saved source proof changed; select the source again"
183            );
184        } else {
185            ensure!(
186                git::is_ancestor(repo, &self.head, &source).await,
187                "source-head does not preserve the selected public implementation by ancestry; supply --source-run <retained-run-id> for a recorded launcher rebase"
188            );
189            ensure!(
190                self.source_run.is_none(),
191                "source-run requires a saved source proof; select again"
192            );
193        }
194        Ok(())
195    }
196
197    /// Select and persist evidence without changing the implementation or public lease.
198    pub async fn prepare_source(
199        &mut self,
200        repo: &Path,
201        home: &Path,
202        current_base: &str,
203    ) -> Result<()> {
204        ensure!(
205            self.source_proof.is_none(),
206            "source proof is already selected; refusing to replace saved evidence"
207        );
208        if self.source_run.is_some() {
209            self.source_proof = Some(Box::new(
210                Box::pin(lineage::prove(self, repo, home, current_base)).await?,
211            ));
212            Ok(())
213        } else {
214            self.verify_source(repo).await
215        }
216    }
217
218    /// Confirm task identity and immutable criteria before starting work.
219    pub fn check_task(&self, task: &str, instruction: &str) -> Result<()> {
220        ensure!(
221            self.branch == format!("magi/task-{task}"),
222            "recovery head belongs to another task"
223        );
224        ensure!(
225            self.instruction == instruction,
226            "recovery criteria changed; select the public head again"
227        );
228        ensure!(
229            [self.head.as_str(), self.source()]
230                .iter()
231                .all(|sha| sha.len() == 40 && sha.bytes().all(|b| b.is_ascii_hexdigit())),
232            "recovery requires a full commit SHA"
233        );
234        Ok(())
235    }
236
237    /// Read-only forge validation plus fetch; no local branch is moved or pushed.
238    pub async fn verify(&self, repo: &Path, remote: &str, base: &str, lease: &str) -> Result<()> {
239        let pr_repo = land::slug_of_pr_url(&self.url).context("invalid recovery PR URL")?;
240        for args in [
241            vec!["remote", "get-url", "--all", remote],
242            vec!["remote", "get-url", "--push", "--all", remote],
243        ] {
244            let urls = git::git(repo, &args).await?;
245            ensure!(
246                !urls.trim().is_empty(),
247                "recovery remote has no repository URL"
248            );
249            for url in urls.lines() {
250                let remote_repo =
251                    remote_slug(url).context("cannot prove recovery remote repository identity")?;
252                land::ensure_same_repo(&remote_repo, &pr_repo)?;
253            }
254        }
255        let found = land::find_open_pr(repo, &self.branch, base).await?;
256        ensure!(
257            matches!(found, land::OpenPr::One { ref url, .. } if url == &self.url),
258            "selected PR is not the unique open task PR in this repository"
259        );
260        let (ok, raw) = land::gh(
261            repo,
262            &[
263                "pr".into(),
264                "view".into(),
265                self.url.clone(),
266                "--json".into(),
267                "headRefName,headRefOid,baseRefName,state,isCrossRepository".into(),
268            ],
269        )
270        .await?;
271        ensure!(ok, "could not verify selected PR: {raw}");
272        validate_view(&raw, &self.branch, base, lease)?;
273        let fetched = git::fetch(repo, remote, &self.branch).await?;
274        ensure!(
275            fetched.ok(),
276            "fetch selected public head failed: {}",
277            fetched.stderr
278        );
279        let fetched_head =
280            git::rev_parse(repo, &format!("refs/remotes/{remote}/{}", self.branch)).await?;
281        ensure!(
282            fetched_head == lease,
283            "public head moved; select and approve its new head before recovery"
284        );
285        ensure!(
286            git::remote_head(repo, remote, &self.branch)
287                .await?
288                .as_deref()
289                == Some(lease),
290            "public head lease changed during recovery"
291        );
292        Ok(())
293    }
294}
295
296// Require a recognizable forge URL rather than guessing through local paths or SSH aliases.
297fn remote_slug(url: &str) -> Option<String> {
298    let url = url
299        .trim()
300        .trim_end_matches('/')
301        .strip_suffix(".git")
302        .unwrap_or(url.trim().trim_end_matches('/'));
303    let (host, path) = if let Some(rest) = url
304        .strip_prefix("https://")
305        .or_else(|| url.strip_prefix("http://"))
306        .or_else(|| url.strip_prefix("ssh://"))
307    {
308        let (authority, path) = rest.split_once('/')?;
309        (authority.rsplit('@').next()?, path)
310    } else {
311        let (authority, path) = url.split_once(':')?;
312        let (_, host) = authority.split_once('@')?;
313        (host, path)
314    };
315    let mut parts = path.split('/');
316    let owner = parts.next()?;
317    let repo = parts.next()?;
318    if host.is_empty() || owner.is_empty() || repo.is_empty() || parts.next().is_some() {
319        return None;
320    }
321    Some(format!("{host}/{owner}/{repo}"))
322}
323
324fn validate_view(raw: &str, branch: &str, base: &str, lease: &str) -> Result<()> {
325    #[derive(Deserialize)]
326    #[serde(rename_all = "camelCase")]
327    struct View {
328        head_ref_name: String,
329        head_ref_oid: String,
330        base_ref_name: String,
331        state: String,
332        is_cross_repository: bool,
333    }
334    let view: View = serde_json::from_str(raw).context("selected public head metadata")?;
335    ensure!(
336        view.state == "OPEN"
337            && !view.is_cross_repository
338            && view.head_ref_name == branch
339            && view.base_ref_name == base,
340        "selected PR ownership or base changed"
341    );
342    ensure!(
343        view.head_ref_oid == lease,
344        "selected public head moved; refusing recovery"
345    );
346    Ok(())
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn recovery_uses_resolved_layers_and_preserves_unrelated_overrides() {
355        let dir = tempfile::tempdir().unwrap();
356        let machine = dir.path().join("machine.toml");
357        let repo = dir.path().join("repository.toml");
358        std::fs::write(&machine, "[verify]\ngate = ['documented gate']\ne2e = ['real checks']\n[graph]\nland = false\nland_approval = false\n").unwrap();
359        std::fs::write(&repo, "[merge]\nmode = 'none'\nbase = 'trunk'\n").unwrap();
360        let mut config = Config::load_layers(&[machine, repo]).unwrap();
361        let overrides = crate::queue::RunOverrides {
362            merge: Some("none".into()),
363            reviewers: Some(2),
364            ..Default::default()
365        };
366        overrides.apply(&mut config);
367        let mut selection = Selection {
368            url: "url".into(),
369            branch: "magi/task-t".into(),
370            head: "a".repeat(40),
371            source_head: None,
372            source_run: None,
373            source_proof: None,
374            disposition: Some(Disposition::Land),
375            instruction: "criteria".into(),
376            approved_at: jiff::Timestamp::now(),
377        };
378        selection.configure(&mut config).unwrap();
379        assert_eq!(config.merge.mode, MergeMode::Pr);
380        assert_eq!(config.graph.reviewers, 2);
381        assert_eq!(config.merge.base.as_deref(), Some("trunk"));
382        assert_eq!(config.verify.gate, ["documented gate"]);
383        assert_eq!(config.verify.e2e, ["real checks"]);
384        assert!(config.graph.land && config.graph.land_approval);
385        let explicit = dir.path().join("explicit.toml");
386        std::fs::write(&explicit, "[merge]\nbase = 'other'\n").unwrap();
387        let (mut replacement, paths) = Config::discover(dir.path(), Some(&explicit)).unwrap();
388        assert_eq!(paths, [explicit]);
389        assert!(
390            selection
391                .configure(&mut replacement)
392                .unwrap_err()
393                .to_string()
394                .contains("verify.gate")
395        );
396        replacement.verify.gate = vec![" ".into()];
397        assert!(selection.configure(&mut replacement).is_err());
398        selection.disposition = Some(Disposition::Review);
399        selection.configure(&mut replacement).unwrap();
400        assert_eq!(replacement.merge.mode, MergeMode::None);
401        assert!(!replacement.graph.land);
402    }
403
404    #[test]
405    fn selected_source_requires_the_same_fetch_and_push_repository() {
406        for remote in [
407            "https://example.test/team/project.git",
408            "git@example.test:team/project.git",
409            "ssh://git@example.test/team/project.git",
410        ] {
411            assert_eq!(
412                remote_slug(remote).as_deref(),
413                Some("example.test/team/project")
414            );
415        }
416        assert!(remote_slug("/tmp/another.git").is_none());
417        assert!(
418            land::ensure_same_repo(
419                &remote_slug("git@example.test:team/other.git").unwrap(),
420                "example.test/team/project"
421            )
422            .is_err()
423        );
424        assert!(
425            land::ensure_same_repo(
426                &remote_slug("git@other.test:team/project.git").unwrap(),
427                "example.test/team/project"
428            )
429            .is_err()
430        );
431    }
432
433    #[test]
434    fn selected_head_refuses_moved_or_foreign_public_heads() {
435        let raw = r#"{"headRefName":"magi/task-t","headRefOid":"aaa","baseRefName":"main","state":"OPEN","isCrossRepository":false}"#;
436        assert!(validate_view(raw, "magi/task-t", "main", "aaa").is_ok());
437        assert!(validate_view(raw, "magi/task-t", "main", "bbb").is_err());
438        assert!(validate_view(raw, "magi/task-other", "main", "aaa").is_err());
439        assert!(validate_view(raw, "magi/task-t", "other", "aaa").is_err());
440        assert!(
441            validate_view(&raw.replace("false", "true"), "magi/task-t", "main", "aaa").is_err()
442        );
443        assert!(
444            validate_view(&raw.replace("OPEN", "CLOSED"), "magi/task-t", "main", "aaa").is_err()
445        );
446    }
447
448    #[test]
449    fn selected_head_is_bound_to_authored_criteria_and_task() {
450        let selected = Selection {
451            url: "url".into(),
452            branch: "magi/task-t".into(),
453            head: "a".repeat(40),
454            source_head: None,
455            source_run: None,
456            source_proof: None,
457            disposition: Some(Disposition::Review),
458            instruction: "approved".into(),
459            approved_at: jiff::Timestamp::now(),
460        };
461        assert!(selected.check_task("t", "approved").is_ok());
462        assert!(
463            selected
464                .check_task("t", "prose mentioning another candidate")
465                .is_err()
466        );
467        assert!(selected.check_task("other", "approved").is_err());
468    }
469}