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                || run.pr_head.as_deref() == Some(selected.branch.as_str())),
131        "source-run belongs to another task or repository assignment"
132    );
133    let original = run.pr_recovery.as_ref().context(
134        "source-run lacks its original public-head selection; ancestry cannot be inferred",
135    )?;
136    ensure!(
137        original.url == selected.url
138            && original.branch == selected.branch
139            && original.head == selected.head
140            && original.source() == selected.head,
141        "source-run PR/public lease or original implementation does not match the selection"
142    );
143    let sync = run
144        .base_sync
145        .as_ref()
146        .context("source-run lacks base-sync provenance")?;
147    ensure!(
148        sync.attempts > 0 && sync.conflict.is_none() && sync.already_in.is_none(),
149        "source-run has no successful base-sync; inspect its conflict/provenance"
150    );
151    ensure!(
152        git::ancestry(repo, &sync.tip, current_base).await?,
153        "recorded rebase base {} is outside current landing base {current_base}",
154        sync.tip
155    );
156    let source = git::rev_parse(repo, &format!("{}^{{commit}}", selected.source())).await?;
157    ensure!(
158        source == selected.source(),
159        "source-head must be a full SHA"
160    );
161    ensure!(
162        run.reviews.last().is_some_and(|r| r.head == source),
163        "source {source} is not the source-run's final recorded review head; inspect reviews and retain the exact reviewed source"
164    );
165    let mut retained = false;
166    for candidate in &run.candidates {
167        if git::commit_of(repo, &candidate.branch).await.as_deref() == Some(&source)
168            && run.events.iter().any(|e| {
169                e.node == "land"
170                    && e.message
171                        == format!(
172                            "rebased {} onto {}/{}",
173                            candidate.branch, run.config.merge.remote, run.base_branch
174                        )
175            })
176        {
177            retained = true;
178        }
179    }
180    ensure!(
181        retained,
182        "source {source} lacks a retained candidate ref and successful launcher rebase event in run {id}"
183    );
184    let old_base = git::merge_base(repo, &selected.head, &sync.tip).await?;
185    let originals = linear(repo, &old_base, &selected.head).await?;
186    let rebased = linear(repo, &sync.tip, &source).await?;
187    ensure!(
188        !originals.is_empty() && rebased.len() >= originals.len(),
189        "source {source} lacks the complete public implementation {} (base {old_base}, onto {})",
190        selected.head,
191        sync.tip
192    );
193
194    // A private bare object database isolates replay from the retained repository.
195    // No branch, checkout, index, sequencer or historical run record is modified.
196    let temp = ReplayDir::new()?;
197    let objects = temp.0.join("replay.git");
198    git::git(
199        repo,
200        &[
201            "clone",
202            "--bare",
203            "--shared",
204            "--quiet",
205            "--",
206            &repo.to_string_lossy(),
207            &objects.to_string_lossy(),
208        ],
209    )
210    .await?;
211    let mut parent = old_base.clone();
212    let mut onto = sync.tip.clone();
213    let mut commits = Vec::new();
214    for (old, new) in originals.iter().zip(&rebased) {
215        let replay = git::git_raw(
216            &objects,
217            &[
218                "merge-tree",
219                "--write-tree",
220                &format!("--merge-base={parent}"),
221                &onto,
222                old,
223            ],
224        )
225        .await?;
226        ensure!(
227            replay.ok(),
228            "cannot reproduce {old} -> {new} onto {onto}: {}; {}; restore provenance or reconstruct and review explicitly",
229            replay.stdout,
230            replay.stderr
231        );
232        let tree = replay
233            .stdout
234            .lines()
235            .next()
236            .context("replay returned no tree")?
237            .to_owned();
238        let expected = git::rev_parse(repo, &format!("{new}^{{tree}}")).await?;
239        if tree != expected {
240            let paths = git::git(&objects, &["diff", "--name-status", &tree, &expected]).await?;
241            anyhow::bail!(
242                "modified implementation {old} -> {new} (base {old_base}, onto {}): tree {tree} != {expected}; differing paths:\n{paths}",
243                sync.tip
244            );
245        }
246        commits.push((old.clone(), new.clone(), tree));
247        parent = old.clone();
248        onto = new.clone();
249    }
250    Ok(SourceProof {
251        run: id.to_owned(),
252        public_head: selected.head.clone(),
253        source_head: source,
254        old_base,
255        new_base: sync.tip.clone(),
256        current_base: current_base.to_owned(),
257        fixes: rebased[originals.len()..].to_vec(),
258        commits,
259    })
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use crate::{config::Config, pr_recovery::Disposition, run::Origin};
266    use serde_json::json;
267
268    async fn commit(repo: &Path, name: &str, contents: &str) -> String {
269        std::fs::write(repo.join(name), contents).unwrap();
270        git::git(repo, &["add", "."]).await.unwrap();
271        git::git(repo, &["commit", "-qm", name]).await.unwrap();
272        git::rev_parse(repo, "HEAD").await.unwrap()
273    }
274
275    async fn fixture() -> (tempfile::TempDir, Selection, RunState, String) {
276        let temp = tempfile::tempdir().unwrap();
277        let repo = temp.path().join("repo");
278        std::fs::create_dir(&repo).unwrap();
279        git::git(&repo, &["init", "-q", "-b", "main"])
280            .await
281            .unwrap();
282        git::git(&repo, &["config", "user.name", "Test"])
283            .await
284            .unwrap();
285        git::git(&repo, &["config", "user.email", "test@example.invalid"])
286            .await
287            .unwrap();
288        let base = commit(&repo, "shared", "old\n\n\n\n\n\n\n\n\n\noriginal\n").await;
289        git::git(&repo, &["checkout", "-qb", "public"])
290            .await
291            .unwrap();
292        for i in 0..4 {
293            commit(
294                &repo,
295                &format!("implementation-{i}"),
296                &format!("selected {i}\n"),
297            )
298            .await;
299        }
300        let public = commit(
301            &repo,
302            "shared",
303            "old\n\n\n\n\n\n\n\n\n\nmeasured implementation\n",
304        )
305        .await;
306        git::git(&repo, &["checkout", "-q", "main"]).await.unwrap();
307        commit(&repo, "new-main-only", "keep new main\n").await;
308        let new_base = commit(&repo, "shared", "new main\n\n\n\n\n\n\n\n\n\noriginal\n").await;
309        git::git(&repo, &["checkout", "-qb", "retained", &public])
310            .await
311            .unwrap();
312        git::git(&repo, &["rebase", "--onto", &new_base, &base])
313            .await
314            .unwrap();
315        let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
316        let source = commit(&repo, "review-fix", "keep complete reviewed fix\n").await;
317        let mut selected = Selection {
318            url: "https://example.test/team/project/pull/1".into(),
319            branch: "magi/task-t".into(),
320            head: public,
321            source_head: Some(source.clone()),
322            source_run: None,
323            source_proof: None,
324            disposition: Some(Disposition::Land),
325            instruction: "preserve implementation".into(),
326            approved_at: jiff::Timestamp::now(),
327        };
328        let mut state = RunState::new(
329            repo,
330            "main".into(),
331            new_base.clone(),
332            selected.instruction.clone(),
333            Config::default(),
334        );
335        state.origin = Some(Origin::queue("t"));
336        let mut original = selected.clone();
337        original.source_head = None;
338        original.disposition = None;
339        state.pr_recovery = Some(original);
340        state.base_sync = Some(crate::run::BaseSync {
341            tip: new_base.clone(),
342            behind: 0,
343            attempts: 1,
344            conflict: None,
345            already_in: None,
346        });
347        state.candidates.push(serde_json::from_value(json!({
348            "index":0,"label":"A","agent":"existing branch","branch":"retained","worktree":"unused"
349        })).unwrap());
350        state.reviews = [rebased, source]
351            .into_iter()
352            .enumerate()
353            .map(|(i, head)| {
354                serde_json::from_value(json!({"round":i+1,"head":head,"reviews":[]})).unwrap()
355            })
356            .collect();
357        state.event("land", "rebased retained onto origin/main");
358        selected.source_run = Some(state.id.clone());
359        state.save_under(temp.path()).unwrap();
360        (temp, selected, state, new_base)
361    }
362
363    #[tokio::test]
364    async fn actual_rebase_preserves_all_five_commits_main_and_later_review_fixes() {
365        let (temp, mut selected, state, base) = fixture().await;
366        assert!(!git::is_ancestor(&state.repo, &selected.head, selected.source()).await);
367        let proof = prove(&selected, &state.repo, temp.path(), &base)
368            .await
369            .unwrap();
370        assert_eq!(proof.commits.len(), 5);
371        assert_eq!(proof.fixes, [selected.source()]);
372        for i in 0..4 {
373            assert_eq!(
374                git::git(
375                    &state.repo,
376                    &["show", &format!("{}:implementation-{i}", selected.source())]
377                )
378                .await
379                .unwrap(),
380                format!("selected {i}")
381            );
382        }
383        assert_eq!(
384            git::git(
385                &state.repo,
386                &["show", &format!("{}:shared", selected.source())]
387            )
388            .await
389            .unwrap(),
390            "new main\n\n\n\n\n\n\n\n\n\nmeasured implementation"
391        );
392        assert_eq!(
393            git::git(
394                &state.repo,
395                &["show", &format!("{}:review-fix", selected.source())]
396            )
397            .await
398            .unwrap(),
399            "keep complete reviewed fix"
400        );
401        assert_eq!(
402            git::git(
403                &state.repo,
404                &["show", &format!("{}:new-main-only", selected.source())]
405            )
406            .await
407            .unwrap(),
408            "keep new main"
409        );
410        selected.source_proof = Some(Box::new(proof.clone()));
411        let saved = serde_json::to_string(&selected).unwrap();
412        let restored: Selection = serde_json::from_str(&saved).unwrap();
413        assert_eq!(
414            restored.source_proof.as_deref(),
415            Some(
416                &prove(&restored, &state.repo, temp.path(), &base)
417                    .await
418                    .unwrap()
419            )
420        );
421        assert!(git::status_porcelain(&state.repo).await.unwrap().is_empty());
422    }
423
424    #[tokio::test]
425    async fn missing_launcher_records_foreign_identity_and_wrong_base_are_rejected() {
426        let (temp, selected, state, base) = fixture().await;
427        assert!(
428            prove(&selected, &state.repo, temp.path(), &selected.head)
429                .await
430                .unwrap_err()
431                .to_string()
432                .contains("outside current")
433        );
434        for missing in [
435            "original-selection",
436            "rebase-event",
437            "retained-ref",
438            "review-head",
439            "task",
440            "conflict",
441        ] {
442            let mut damaged = state.clone();
443            match missing {
444                "original-selection" => damaged.pr_recovery = None,
445                "rebase-event" => damaged.events.clear(),
446                "retained-ref" => damaged.candidates.clear(),
447                "review-head" => damaged.reviews.last_mut().unwrap().head = selected.head.clone(),
448                "task" => damaged.origin = Some(Origin::queue("other")),
449                _ => damaged.base_sync.as_mut().unwrap().conflict = Some("conflicted".into()),
450            }
451            damaged.save_under(temp.path()).unwrap();
452            assert!(
453                prove(&selected, &state.repo, temp.path(), &base)
454                    .await
455                    .is_err(),
456                "{missing}"
457            );
458        }
459    }
460
461    #[tokio::test]
462    async fn saved_proof_is_recomputed_and_never_silently_replaced() {
463        let (temp, mut selected, mut state, base) = fixture().await;
464        selected
465            .prepare_source(&state.repo, temp.path(), &base)
466            .await
467            .unwrap();
468        selected
469            .verify_source_under(&state.repo, temp.path())
470            .await
471            .unwrap();
472        let proof = selected.source_proof.clone();
473        assert!(
474            selected
475                .prepare_source(&state.repo, temp.path(), &base)
476                .await
477                .is_err()
478        );
479        assert_eq!(selected.source_proof, proof);
480        selected.source_proof.as_mut().unwrap().commits[0].2 = "0".repeat(40);
481        assert!(
482            selected
483                .verify_source_under(&state.repo, temp.path())
484                .await
485                .unwrap_err()
486                .to_string()
487                .contains("proof changed")
488        );
489        selected.source_proof = proof;
490        state.base_sync = None;
491        state.save_under(temp.path()).unwrap();
492        assert!(
493            selected
494                .verify_source_under(&state.repo, temp.path())
495                .await
496                .unwrap_err()
497                .to_string()
498                .contains("base-sync")
499        );
500    }
501
502    #[tokio::test]
503    async fn unrelated_modified_missing_and_moved_public_evidence_fail_closed() {
504        let (temp, mut selected, mut state, base) = fixture().await;
505        let home = temp.path();
506        let public = selected.head.clone();
507        selected.head = base.clone();
508        assert!(
509            prove(&selected, &state.repo, home, &base)
510                .await
511                .unwrap_err()
512                .to_string()
513                .contains("lease")
514        );
515        selected.head = public;
516        let sync = state.base_sync.take();
517        state.save_under(home).unwrap();
518        assert!(
519            prove(&selected, &state.repo, home, &base)
520                .await
521                .unwrap_err()
522                .to_string()
523                .contains("base-sync")
524        );
525        state.base_sync = sync;
526        state.save_under(home).unwrap();
527        let mut legacy = serde_json::to_value(&selected).unwrap();
528        legacy.as_object_mut().unwrap().remove("source_proof");
529        legacy.as_object_mut().unwrap().remove("source_run");
530        let legacy: Selection = serde_json::from_value(legacy).unwrap();
531        assert!(
532            legacy
533                .verify_source(&state.repo)
534                .await
535                .unwrap_err()
536                .to_string()
537                .contains("--source-run")
538        );
539        // Make the final review metadata name a genuinely modified rebase result.
540        git::git(&state.repo, &["checkout", "-q", "retained~1"])
541            .await
542            .unwrap();
543        std::fs::write(
544            state.repo.join("implementation-0"),
545            "replaced implementation\n",
546        )
547        .unwrap();
548        git::git(&state.repo, &["add", "."]).await.unwrap();
549        git::git(&state.repo, &["commit", "--amend", "--no-edit", "-q"])
550            .await
551            .unwrap();
552        let modified = commit(&state.repo, "review-fix", "later review\n").await;
553        git::git(&state.repo, &["branch", "-f", "retained", &modified])
554            .await
555            .unwrap();
556        selected.source_head = Some(modified.clone());
557        state.reviews.last_mut().unwrap().head = modified;
558        state.save_under(home).unwrap();
559        let error = prove(&selected, &state.repo, home, &base)
560            .await
561            .unwrap_err()
562            .to_string();
563        assert!(
564            error.contains("modified implementation") && error.contains("implementation-0"),
565            "{error}"
566        );
567        git::git(&state.repo, &["checkout", "-q", "--orphan", "unrelated"])
568            .await
569            .unwrap();
570        git::git(&state.repo, &["rm", "-rf", "."]).await.unwrap();
571        let unrelated = commit(&state.repo, "other", "unrelated\n").await;
572        selected.source_head = Some(unrelated.clone());
573        state.reviews.last_mut().unwrap().head = unrelated.clone();
574        git::git(&state.repo, &["branch", "-f", "retained", &unrelated])
575            .await
576            .unwrap();
577        state.save_under(home).unwrap();
578        assert!(prove(&selected, &state.repo, home, &base).await.is_err());
579        selected.source_run = Some("20000101-000000-abcd".into());
580        assert!(
581            prove(&selected, &state.repo, home, &base)
582                .await
583                .unwrap_err()
584                .to_string()
585                .contains("provenance")
586        );
587    }
588
589    /// Operator-supplied paths allow read-only validation of an actual retained history.
590    #[tokio::test]
591    #[ignore = "requires a local retained run and repository"]
592    async fn inspect_retained_rebase_history() {
593        let env = |name| std::env::var(name).unwrap();
594        let home = std::path::PathBuf::from(env("RECOVERY_HOME"));
595        let state = RunState::load_under(&env("RECOVERY_RUN"), &home).unwrap();
596        let mut selected = state.pr_recovery.clone().unwrap();
597        selected.source_run = Some(state.id.clone());
598        selected.source_head = Some(env("RECOVERY_SOURCE"));
599        let proof = prove(&selected, &state.repo, &home, &env("RECOVERY_BASE"))
600            .await
601            .unwrap();
602        assert_eq!(proof.commits.len(), 5);
603        assert_eq!(proof.fixes, [selected.source()]);
604        eprintln!("{}", serde_json::to_string_pretty(&proof).unwrap());
605    }
606}