Skip to main content

magi/pr_recovery/
lineage.rs

1//! Reproduce a retained launcher's rebase without moving any repository refs.
2
3use std::path::Path;
4
5use anyhow::{Context, Result, ensure};
6use serde::{Deserialize, Serialize};
7
8use super::Selection;
9use crate::{git, run::RunState};
10
11/// Exact replay correspondence retained with the operator's selection.
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct SourceProof {
14    /// Retained historical run supplying the launcher provenance.
15    pub run: String,
16    /// Exact public update lease approved by the operator.
17    pub public_head: String,
18    /// Complete adopted implementation, including subsequent review fixes.
19    pub source_head: String,
20    /// Shared base before replaying the selected public implementation.
21    pub old_base: String,
22    /// Immutable base recorded by the successful launcher base-sync.
23    pub new_base: String,
24    /// Fetched landing base against which this selection was approved.
25    pub current_base: String,
26    /// Original commit, rebased commit and reproduced tree, in replay order.
27    pub commits: Vec<(String, String, String)>,
28    /// All later reviewed changes are adopted, rather than just the replayed tip.
29    pub fixes: Vec<String>,
30}
31
32struct ReplayDir(std::path::PathBuf);
33
34impl ReplayDir {
35    fn new() -> Result<Self> {
36        let path =
37            std::env::temp_dir().join(format!("magi-source-replay-{:016x}", crate::rng::entropy()));
38        let builder = std::fs::DirBuilder::new();
39        #[cfg(unix)]
40        let builder = {
41            use std::os::unix::fs::DirBuilderExt;
42            let mut private = builder;
43            private.mode(0o700);
44            private
45        };
46        builder
47            .create(&path)
48            .context("creating private source replay directory")?;
49        Ok(Self(path))
50    }
51}
52
53impl Drop for ReplayDir {
54    fn drop(&mut self) {
55        let _ = std::fs::remove_dir_all(&self.0);
56    }
57}
58
59async fn linear(repo: &Path, base: &str, head: &str) -> Result<Vec<String>> {
60    ensure!(
61        git::ancestry(repo, base, head).await?,
62        "{base} is not an ancestor of {head}"
63    );
64    let raw = git::git(
65        repo,
66        &[
67            "rev-list",
68            "--reverse",
69            "--parents",
70            &format!("{base}..{head}"),
71        ],
72    )
73    .await?;
74    let mut previous = base.to_owned();
75    let mut commits = Vec::new();
76    for line in raw.lines() {
77        let words: Vec<_> = line.split_whitespace().collect();
78        ensure!(
79            words.len() == 2 && words[1] == previous,
80            "unsupported non-linear source history at {line}; inspect the retained run before reconstructing"
81        );
82        let tree = git::rev_parse(repo, &format!("{}^{{tree}}", words[0])).await?;
83        let parent_tree = git::rev_parse(repo, &format!("{previous}^{{tree}}")).await?;
84        ensure!(tree != parent_tree, "unsupported empty commit {}", words[0]);
85        previous = words[0].to_owned();
86        commits.push(previous.clone());
87    }
88    Ok(commits)
89}
90
91pub(super) async fn prove(
92    selected: &Selection,
93    repo: &Path,
94    home: &Path,
95    current_base: &str,
96) -> Result<SourceProof> {
97    let id = selected
98        .source_run
99        .as_deref()
100        .context("missing --source-run")?;
101    ensure!(
102        crate::run::is_run_id(id),
103        "source-run requires its full run id"
104    );
105    let run = RunState::load_under(id, home).with_context(|| {
106        format!("missing or unreadable source-run {id}; restore retained run provenance")
107    })?;
108    let common = |path: &Path| {
109        let path = path.to_owned();
110        async move {
111            git::git(
112                &path,
113                &["rev-parse", "--path-format=absolute", "--git-common-dir"],
114            )
115            .await
116        }
117    };
118    ensure!(
119        common(repo).await? == common(&run.repo).await?,
120        "source-run repository differs from recovery repository"
121    );
122    let task = run
123        .origin
124        .as_ref()
125        .and_then(|origin| origin.task.as_deref())
126        .context("source-run has no owning task")?;
127    ensure!(
128        run.id == id
129            && selected.branch == crate::run::task_pr_branch_name(task, run.task_assignment),
130        "source-run belongs to another task or repository assignment"
131    );
132    let original = run.pr_recovery.as_ref().context(
133        "source-run lacks its original public-head selection; ancestry cannot be inferred",
134    )?;
135    ensure!(
136        original.url == selected.url
137            && original.branch == selected.branch
138            && original.head == selected.head
139            && original.source() == selected.head,
140        "source-run PR/public lease or original implementation does not match the selection"
141    );
142    let sync = run
143        .base_sync
144        .as_ref()
145        .context("source-run lacks base-sync provenance")?;
146    ensure!(
147        sync.attempts > 0 && sync.conflict.is_none() && sync.already_in.is_none(),
148        "source-run has no successful base-sync; inspect its conflict/provenance"
149    );
150    ensure!(
151        git::ancestry(repo, &sync.tip, current_base).await?,
152        "recorded rebase base {} is outside current landing base {current_base}",
153        sync.tip
154    );
155    let source = git::rev_parse(repo, &format!("{}^{{commit}}", selected.source())).await?;
156    ensure!(
157        source == selected.source(),
158        "source-head must be a full SHA"
159    );
160    ensure!(
161        run.reviews.last().is_some_and(|r| r.head == source),
162        "source {source} is not the source-run's final recorded review head; inspect reviews and retain the exact reviewed source"
163    );
164    let mut retained = false;
165    for candidate in &run.candidates {
166        if git::commit_of(repo, &candidate.branch).await.as_deref() == Some(&source)
167            && run.events.iter().any(|e| {
168                e.node == "land"
169                    && e.message
170                        == format!(
171                            "rebased {} onto {}/{}",
172                            candidate.branch, run.config.merge.remote, run.base_branch
173                        )
174            })
175        {
176            retained = true;
177        }
178    }
179    ensure!(
180        retained,
181        "source {source} lacks a retained candidate ref and successful launcher rebase event in run {id}"
182    );
183    let old_base = git::merge_base(repo, &selected.head, &sync.tip).await?;
184    let originals = linear(repo, &old_base, &selected.head).await?;
185    let rebased = linear(repo, &sync.tip, &source).await?;
186    ensure!(
187        !originals.is_empty() && rebased.len() >= originals.len(),
188        "source {source} lacks the complete public implementation {} (base {old_base}, onto {})",
189        selected.head,
190        sync.tip
191    );
192
193    // A private bare object database isolates replay from the retained repository.
194    // No branch, checkout, index, sequencer or historical run record is modified.
195    let temp = ReplayDir::new()?;
196    let objects = temp.0.join("replay.git");
197    git::git(
198        repo,
199        &[
200            "clone",
201            "--bare",
202            "--shared",
203            "--quiet",
204            "--",
205            &repo.to_string_lossy(),
206            &objects.to_string_lossy(),
207        ],
208    )
209    .await?;
210    let mut parent = old_base.clone();
211    let mut onto = sync.tip.clone();
212    let mut commits = Vec::new();
213    for (old, new) in originals.iter().zip(&rebased) {
214        let replay = git::git_raw(
215            &objects,
216            &[
217                "merge-tree",
218                "--write-tree",
219                &format!("--merge-base={parent}"),
220                &onto,
221                old,
222            ],
223        )
224        .await?;
225        ensure!(
226            replay.ok(),
227            "cannot reproduce {old} -> {new} onto {onto}: {}; {}; restore provenance or reconstruct and review explicitly",
228            replay.stdout,
229            replay.stderr
230        );
231        let tree = replay
232            .stdout
233            .lines()
234            .next()
235            .context("replay returned no tree")?
236            .to_owned();
237        let expected = git::rev_parse(repo, &format!("{new}^{{tree}}")).await?;
238        if tree != expected {
239            let paths = git::git(&objects, &["diff", "--name-status", &tree, &expected]).await?;
240            anyhow::bail!(
241                "modified implementation {old} -> {new} (base {old_base}, onto {}): tree {tree} != {expected}; differing paths:\n{paths}",
242                sync.tip
243            );
244        }
245        commits.push((old.clone(), new.clone(), tree));
246        parent = old.clone();
247        onto = new.clone();
248    }
249    Ok(SourceProof {
250        run: id.to_owned(),
251        public_head: selected.head.clone(),
252        source_head: source,
253        old_base,
254        new_base: sync.tip.clone(),
255        current_base: current_base.to_owned(),
256        fixes: rebased[originals.len()..].to_vec(),
257        commits,
258    })
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::{config::Config, pr_recovery::Disposition, run::Origin};
265    use serde_json::json;
266
267    async fn commit(repo: &Path, name: &str, contents: &str) -> String {
268        std::fs::write(repo.join(name), contents).unwrap();
269        git::git(repo, &["add", "."]).await.unwrap();
270        git::git(repo, &["commit", "-qm", name]).await.unwrap();
271        git::rev_parse(repo, "HEAD").await.unwrap()
272    }
273
274    async fn fixture() -> (tempfile::TempDir, Selection, RunState, String) {
275        let temp = tempfile::tempdir().unwrap();
276        let repo = temp.path().join("repo");
277        std::fs::create_dir(&repo).unwrap();
278        git::git(&repo, &["init", "-q", "-b", "main"])
279            .await
280            .unwrap();
281        git::git(&repo, &["config", "user.name", "Test"])
282            .await
283            .unwrap();
284        git::git(&repo, &["config", "user.email", "test@example.invalid"])
285            .await
286            .unwrap();
287        let base = commit(&repo, "shared", "old\n\n\n\n\n\n\n\n\n\noriginal\n").await;
288        git::git(&repo, &["checkout", "-qb", "public"])
289            .await
290            .unwrap();
291        for i in 0..4 {
292            commit(
293                &repo,
294                &format!("implementation-{i}"),
295                &format!("selected {i}\n"),
296            )
297            .await;
298        }
299        let public = commit(
300            &repo,
301            "shared",
302            "old\n\n\n\n\n\n\n\n\n\nmeasured implementation\n",
303        )
304        .await;
305        git::git(&repo, &["checkout", "-q", "main"]).await.unwrap();
306        commit(&repo, "new-main-only", "keep new main\n").await;
307        let new_base = commit(&repo, "shared", "new main\n\n\n\n\n\n\n\n\n\noriginal\n").await;
308        git::git(&repo, &["checkout", "-qb", "retained", &public])
309            .await
310            .unwrap();
311        git::git(&repo, &["rebase", "--onto", &new_base, &base])
312            .await
313            .unwrap();
314        let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
315        let source = commit(&repo, "review-fix", "keep complete reviewed fix\n").await;
316        let mut selected = Selection {
317            url: "https://example.test/team/project/pull/1".into(),
318            branch: "magi/task-t".into(),
319            head: public,
320            source_head: Some(source.clone()),
321            source_run: None,
322            source_proof: None,
323            disposition: Some(Disposition::Land),
324            instruction: "preserve implementation".into(),
325            approved_at: jiff::Timestamp::now(),
326        };
327        let mut state = RunState::new(
328            repo,
329            "main".into(),
330            new_base.clone(),
331            selected.instruction.clone(),
332            Config::default(),
333        );
334        state.origin = Some(Origin::queue("t"));
335        let mut original = selected.clone();
336        original.source_head = None;
337        original.disposition = None;
338        state.pr_recovery = Some(original);
339        state.base_sync = Some(crate::run::BaseSync {
340            tip: new_base.clone(),
341            behind: 0,
342            attempts: 1,
343            conflict: None,
344            already_in: None,
345        });
346        state.candidates.push(serde_json::from_value(json!({
347            "index":0,"label":"A","agent":"existing branch","branch":"retained","worktree":"unused"
348        })).unwrap());
349        state.reviews = [rebased, source]
350            .into_iter()
351            .enumerate()
352            .map(|(i, head)| {
353                serde_json::from_value(json!({"round":i+1,"head":head,"reviews":[]})).unwrap()
354            })
355            .collect();
356        state.event("land", "rebased retained onto origin/main");
357        selected.source_run = Some(state.id.clone());
358        state.save_under(temp.path()).unwrap();
359        (temp, selected, state, new_base)
360    }
361
362    #[tokio::test]
363    async fn actual_rebase_preserves_all_five_commits_main_and_later_review_fixes() {
364        let (temp, mut selected, state, base) = fixture().await;
365        assert!(!git::is_ancestor(&state.repo, &selected.head, selected.source()).await);
366        let proof = prove(&selected, &state.repo, temp.path(), &base)
367            .await
368            .unwrap();
369        assert_eq!(proof.commits.len(), 5);
370        assert_eq!(proof.fixes, [selected.source()]);
371        for i in 0..4 {
372            assert_eq!(
373                git::git(
374                    &state.repo,
375                    &["show", &format!("{}:implementation-{i}", selected.source())]
376                )
377                .await
378                .unwrap(),
379                format!("selected {i}")
380            );
381        }
382        assert_eq!(
383            git::git(
384                &state.repo,
385                &["show", &format!("{}:shared", selected.source())]
386            )
387            .await
388            .unwrap(),
389            "new main\n\n\n\n\n\n\n\n\n\nmeasured implementation"
390        );
391        assert_eq!(
392            git::git(
393                &state.repo,
394                &["show", &format!("{}:review-fix", selected.source())]
395            )
396            .await
397            .unwrap(),
398            "keep complete reviewed fix"
399        );
400        assert_eq!(
401            git::git(
402                &state.repo,
403                &["show", &format!("{}:new-main-only", selected.source())]
404            )
405            .await
406            .unwrap(),
407            "keep new main"
408        );
409        selected.source_proof = Some(Box::new(proof.clone()));
410        let saved = serde_json::to_string(&selected).unwrap();
411        let restored: Selection = serde_json::from_str(&saved).unwrap();
412        assert_eq!(
413            restored.source_proof.as_deref(),
414            Some(
415                &prove(&restored, &state.repo, temp.path(), &base)
416                    .await
417                    .unwrap()
418            )
419        );
420        assert!(git::status_porcelain(&state.repo).await.unwrap().is_empty());
421    }
422
423    #[tokio::test]
424    async fn missing_launcher_records_foreign_identity_and_wrong_base_are_rejected() {
425        let (temp, selected, state, base) = fixture().await;
426        assert!(
427            prove(&selected, &state.repo, temp.path(), &selected.head)
428                .await
429                .unwrap_err()
430                .to_string()
431                .contains("outside current")
432        );
433        for missing in [
434            "original-selection",
435            "rebase-event",
436            "retained-ref",
437            "review-head",
438            "task",
439            "conflict",
440        ] {
441            let mut damaged = state.clone();
442            match missing {
443                "original-selection" => damaged.pr_recovery = None,
444                "rebase-event" => damaged.events.clear(),
445                "retained-ref" => damaged.candidates.clear(),
446                "review-head" => damaged.reviews.last_mut().unwrap().head = selected.head.clone(),
447                "task" => damaged.origin = Some(Origin::queue("other")),
448                _ => damaged.base_sync.as_mut().unwrap().conflict = Some("conflicted".into()),
449            }
450            damaged.save_under(temp.path()).unwrap();
451            assert!(
452                prove(&selected, &state.repo, temp.path(), &base)
453                    .await
454                    .is_err(),
455                "{missing}"
456            );
457        }
458    }
459
460    #[tokio::test]
461    async fn saved_proof_is_recomputed_and_never_silently_replaced() {
462        let (temp, mut selected, mut state, base) = fixture().await;
463        selected
464            .prepare_source(&state.repo, temp.path(), &base)
465            .await
466            .unwrap();
467        selected
468            .verify_source_under(&state.repo, temp.path())
469            .await
470            .unwrap();
471        let proof = selected.source_proof.clone();
472        assert!(
473            selected
474                .prepare_source(&state.repo, temp.path(), &base)
475                .await
476                .is_err()
477        );
478        assert_eq!(selected.source_proof, proof);
479        selected.source_proof.as_mut().unwrap().commits[0].2 = "0".repeat(40);
480        assert!(
481            selected
482                .verify_source_under(&state.repo, temp.path())
483                .await
484                .unwrap_err()
485                .to_string()
486                .contains("proof changed")
487        );
488        selected.source_proof = proof;
489        state.base_sync = None;
490        state.save_under(temp.path()).unwrap();
491        assert!(
492            selected
493                .verify_source_under(&state.repo, temp.path())
494                .await
495                .unwrap_err()
496                .to_string()
497                .contains("base-sync")
498        );
499    }
500
501    #[tokio::test]
502    async fn unrelated_modified_missing_and_moved_public_evidence_fail_closed() {
503        let (temp, mut selected, mut state, base) = fixture().await;
504        let home = temp.path();
505        let public = selected.head.clone();
506        selected.head = base.clone();
507        assert!(
508            prove(&selected, &state.repo, home, &base)
509                .await
510                .unwrap_err()
511                .to_string()
512                .contains("lease")
513        );
514        selected.head = public;
515        let sync = state.base_sync.take();
516        state.save_under(home).unwrap();
517        assert!(
518            prove(&selected, &state.repo, home, &base)
519                .await
520                .unwrap_err()
521                .to_string()
522                .contains("base-sync")
523        );
524        state.base_sync = sync;
525        state.save_under(home).unwrap();
526        let mut legacy = serde_json::to_value(&selected).unwrap();
527        legacy.as_object_mut().unwrap().remove("source_proof");
528        legacy.as_object_mut().unwrap().remove("source_run");
529        let legacy: Selection = serde_json::from_value(legacy).unwrap();
530        assert!(
531            legacy
532                .verify_source(&state.repo)
533                .await
534                .unwrap_err()
535                .to_string()
536                .contains("--source-run")
537        );
538        // Make the final review metadata name a genuinely modified rebase result.
539        git::git(&state.repo, &["checkout", "-q", "retained~1"])
540            .await
541            .unwrap();
542        std::fs::write(
543            state.repo.join("implementation-0"),
544            "replaced implementation\n",
545        )
546        .unwrap();
547        git::git(&state.repo, &["add", "."]).await.unwrap();
548        git::git(&state.repo, &["commit", "--amend", "--no-edit", "-q"])
549            .await
550            .unwrap();
551        let modified = commit(&state.repo, "review-fix", "later review\n").await;
552        git::git(&state.repo, &["branch", "-f", "retained", &modified])
553            .await
554            .unwrap();
555        selected.source_head = Some(modified.clone());
556        state.reviews.last_mut().unwrap().head = modified;
557        state.save_under(home).unwrap();
558        let error = prove(&selected, &state.repo, home, &base)
559            .await
560            .unwrap_err()
561            .to_string();
562        assert!(
563            error.contains("modified implementation") && error.contains("implementation-0"),
564            "{error}"
565        );
566        git::git(&state.repo, &["checkout", "-q", "--orphan", "unrelated"])
567            .await
568            .unwrap();
569        git::git(&state.repo, &["rm", "-rf", "."]).await.unwrap();
570        let unrelated = commit(&state.repo, "other", "unrelated\n").await;
571        selected.source_head = Some(unrelated.clone());
572        state.reviews.last_mut().unwrap().head = unrelated.clone();
573        git::git(&state.repo, &["branch", "-f", "retained", &unrelated])
574            .await
575            .unwrap();
576        state.save_under(home).unwrap();
577        assert!(prove(&selected, &state.repo, home, &base).await.is_err());
578        selected.source_run = Some("20000101-000000-abcd".into());
579        assert!(
580            prove(&selected, &state.repo, home, &base)
581                .await
582                .unwrap_err()
583                .to_string()
584                .contains("provenance")
585        );
586    }
587
588    /// Operator-supplied paths allow read-only validation of an actual retained history.
589    #[tokio::test]
590    #[ignore = "requires a local retained run and repository"]
591    async fn inspect_retained_rebase_history() {
592        let env = |name| std::env::var(name).unwrap();
593        let home = std::path::PathBuf::from(env("RECOVERY_HOME"));
594        let state = RunState::load_under(&env("RECOVERY_RUN"), &home).unwrap();
595        let mut selected = state.pr_recovery.clone().unwrap();
596        selected.source_run = Some(state.id.clone());
597        selected.source_head = Some(env("RECOVERY_SOURCE"));
598        let proof = prove(&selected, &state.repo, &home, &env("RECOVERY_BASE"))
599            .await
600            .unwrap();
601        assert_eq!(proof.commits.len(), 5);
602        assert_eq!(proof.fixes, [selected.source()]);
603        eprintln!("{}", serde_json::to_string_pretty(&proof).unwrap());
604    }
605}