use std::path::Path;
use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};
use crate::{
config::{Config, MergeMode},
git, land,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum Disposition {
Land,
Review,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigEvidence {
pub layers: Vec<std::path::PathBuf>,
pub overrides: Option<crate::queue::RunOverrides>,
pub daemon_merge: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Selection {
pub url: String,
pub branch: String,
pub head: String,
#[serde(default)]
pub source_head: Option<String>,
#[serde(default)]
pub source_run: Option<String>,
#[serde(default)]
pub source_proof: Option<Box<SourceProof>>,
#[serde(default)]
pub disposition: Option<Disposition>,
pub instruction: String,
pub approved_at: jiff::Timestamp,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClosedRetirement {
pub old_pr: String,
pub inquiry: String,
pub selection: Selection,
pub assignment: usize,
pub at: jiff::Timestamp,
}
pub async fn retire_closed(
queue: &crate::queue::Queue,
home: &Path,
task_id: &str,
run_id: &str,
inquiry_id: &str,
) -> Result<()> {
retire_closed_with(
queue,
home,
task_id,
run_id,
inquiry_id,
async |task, state, selected| {
let lifecycle = land::lifecycle(
&task.repo,
&state.pr.as_ref().context("missing old PR")?.url,
)
.await?;
if matches!(lifecycle, land::PrLifecycle::Closed) {
let (remote, base) = replacement_target(task, selected).await?;
selected
.verify(&task.repo, &remote, &base, &selected.head)
.await?;
}
Ok(lifecycle)
},
)
.await
}
async fn replacement_target(
task: &crate::queue::Task,
selected: &Selection,
) -> Result<(String, String)> {
let explicit = task.overrides.as_ref().and_then(|o| o.config.as_deref());
let (mut config, _) = Config::discover(&task.repo, explicit)?;
if let Some(overrides) = &task.overrides {
overrides.apply(&mut config);
}
selected.configure(&mut config)?;
let base = git::merge_base_branch(
&task.repo,
&config.merge.remote,
config.merge.base.as_deref(),
)
.await?;
Ok((config.merge.remote, base))
}
async fn retire_closed_with(
queue: &crate::queue::Queue,
home: &Path,
task_id: &str,
run_id: &str,
inquiry_id: &str,
observe: impl AsyncFnOnce(
&crate::queue::Task,
&crate::run::RunState,
&Selection,
) -> Result<land::PrLifecycle>,
) -> Result<()> {
use crate::{
ask::Questions,
queue::{HoldSource, TaskStatus},
run::{Liveness, RunState, RunStatus},
};
let id = queue.resolve_id(task_id)?;
let _claim = queue.claim(&id)?;
let task = queue.get(&id)?;
ensure!(
task.fresh_start && task.execution_runs().last().is_some_and(|r| r == run_id),
"retirement requires the latest execution and an already selected fresh start"
);
let selected = task
.pr_recovery
.clone()
.context("no saved replacement selection")?;
selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len())?;
ensure!(
selected.disposition == Some(Disposition::Land),
"replacement must be selected for delivery"
);
let outbox = crate::task_inquiry::Outbox::at(home);
let _effect = outbox.execution_claim(inquiry_id)?;
let inquiry = outbox.get(inquiry_id)?;
ensure!(crate::run::is_run_id(run_id), "full run id required");
let _owner = crate::pr_head::owner_lock(home, run_id)?;
let state = RunState::load_under(run_id, home)?;
ensure!(
state.liveness_under(
home,
crate::daemon::is_working_on_other(home, run_id, jiff::Timestamp::now())?
) == Liveness::Dead,
"obsolete execution is live or unknown"
);
let _execution = crate::driver::maintenance(home, run_id)?;
let mut state = RunState::load_under(run_id, home)?;
let repo = git::toplevel(&task.repo).await?.canonicalize()?;
ensure!(
state.id == run_id
&& state.origin.as_ref().and_then(|o| o.task.as_deref()) == Some(task.id.as_str())
&& state.task_assignment == task.reassignments.len()
&& git::toplevel(&state.repo).await?.canonicalize()? == repo
&& inquiry.task == task.id
&& inquiry.run.as_deref() == Some(run_id)
&& git::toplevel(&inquiry.repo).await?.canonicalize()? == repo,
"retirement ownership does not match task, run and repository assignment"
);
ensure!(
!state.released()
&& state.retired_to.is_none()
&& state.pr_taken_over_by.is_none()
&& !state.pr_publication_pending
&& state.land_armed_head.is_none()
&& !state.land_sync_pending
&& state.land_rebase_from.is_none()
&& state.land_sync_target.is_none()
&& state.sequencer_stop.is_none()
&& state.merge_repairs.is_empty()
&& state.merge_decision.is_none()
&& state.pr_merged_head.is_none(),
"execution has competing ownership or an unresolved publication or repair checkpoint"
);
let pr = state.pr.as_ref().context("missing old PR")?;
ensure!(
pr.url != selected.url
&& land::slug_of_pr_url(&pr.url) == land::slug_of_pr_url(&selected.url),
"replacement must be a different PR in the same repository"
);
let approval = state
.land_approval
.as_ref()
.context("missing old approval binding")?;
let questions = Questions::at(home.join("questions"));
let question = questions.read_history(&approval.question)?;
let decision = inquiry
.decision
.as_ref()
.context("missing native decision")?;
ensure!(
inquiry.id == inquiry_id
&& inquiry.key == format!("question:{}", approval.question)
&& question.id == approval.question
&& question.run == run_id
&& question.node == land::APPROVAL_NODE
&& question
.merge_target
.as_ref()
.is_some_and(|t| t.pr == pr.url && t.head == approval.head)
&& decision.status == crate::task_decision::Status::Resolved
&& decision.legacy_settled
&& decision.request.as_deref() == Some("decision: merge")
&& decision.error.is_none()
&& decision.source_answer_at.is_some()
&& decision.source_answer_at == question.answered_at
&& question.resolution().as_deref() == Some("merge")
&& !task.actions_applied.contains(&question.id)
&& !task.decision_effects.contains_key(inquiry_id)
&& !task.decision_effects.contains_key(&question.id),
"old approval lacks an explicit settled cancellation or has conflicting effect evidence"
);
for other in outbox
.list()
.context("reading the obsolete run's inquiries")?
{
ensure!(
other.id == inquiry_id
|| other.run.as_deref() != Some(run_id)
|| other
.decision
.as_ref()
.is_none_or(|d| { d.status == crate::task_decision::Status::Resolved }),
"inquiry {} of this run still has an unresolved decision; reconcile it first",
other.id
);
}
let pending = crate::task_chat::migration_pending(home)?;
let issues = crate::task_chat::migration_issues(home);
ensure!(
!issues.iter().any(|issue| issue.id == "migration"),
"inquiry migration needs reconciliation"
);
for id in crate::queue::record_ids(&home.join("questions"), "json")? {
let other = questions.read_history(&id)?;
if other.run != run_id || id == approval.question {
continue;
}
ensure!(
!other.status.open()
&& !questions.held_reply(&id)
&& !pending.contains(&id)
&& !issues.iter().any(|issue| issue.id == id),
"legacy question {id} of this run still needs reconciliation"
);
}
let expected_hold =
|reason: &str| reason.starts_with(&format!("Existing PR belongs to run {run_id};"));
ensure!(
task.status == TaskStatus::Queued
|| (task.status == TaskStatus::Held
&& task.hold_source == Some(HoldSource::Machine)
&& task.hold_reason.as_deref().is_some_and(expected_hold)),
"task is not queued or held for this exact obsolete public owner"
);
let receipt = ClosedRetirement {
old_pr: pr.url.clone(),
inquiry: inquiry_id.into(),
selection: selected.clone(),
assignment: task.reassignments.len(),
at: state
.closed_pr_retirement
.as_ref()
.map_or_else(jiff::Timestamp::now, |r| r.at),
};
if let Some(saved) = &state.closed_pr_retirement {
ensure!(
saved == &receipt && state.status == RunStatus::Superseded && pr.state == "closed",
"retirement receipt differs from this request"
);
} else {
ensure!(
crate::handover::landing_checkpoint(&state),
"old run is not a retained public owner"
);
}
match observe(&task, &state, &selected).await {
Ok(land::PrLifecycle::Closed) => {}
Ok(land::PrLifecycle::Merged) => anyhow::bail!(
"old PR {} was merged; use merged-PR correction rather than retirement",
pr.url
),
Ok(land::PrLifecycle::Open) => anyhow::bail!("old PR {} is still open", pr.url),
Err(error) => return Err(error.context("cannot verify old PR lifecycle or replacement")),
}
selected.verify_source_under(&task.repo, home).await?;
retain_sources(&task, home)?;
if state.closed_pr_retirement.is_none() {
state.pr.as_mut().unwrap().state = "closed".into();
state.status = RunStatus::Superseded;
state.closed_pr_retirement = Some(receipt);
state.event(
"recovery",
"explicitly retired cancelled closed PR delivery ownership",
);
state.save_under(home)?;
}
if task.status == TaskStatus::Held {
ensure!(
queue.modify(&task.id, |current| {
if current.status != task.status
|| current.held_at != task.held_at
|| current.hold_reason != task.hold_reason
|| current.hold_source != task.hold_source
|| current.pr_recovery != task.pr_recovery
|| current.operator_decided_at != task.operator_decided_at
|| current.runs != task.runs
|| current.reassignments.len() != task.reassignments.len()
|| !current.fresh_start
{
return false;
}
let attempts = current.attempts;
current.release();
current.attempts = attempts;
current.fresh_start = true;
true
})?,
"task changed during retirement; inspect its current hold before retrying"
);
}
Ok(())
}
mod lineage;
pub use lineage::SourceProof;
const RETAIN_SOURCES: &str = "retain-recovery-sources";
pub fn retain_sources(task: &crate::queue::Task, home: &Path) -> Result<()> {
for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
ensure!(
crate::run::is_run_id(id),
"invalid historical run id; refusing source retention"
);
let dir = home.join("runs").join(id);
ensure!(
dir.is_dir(),
"historical run {id} is missing; cannot retain its sources"
);
std::fs::write(dir.join(RETAIN_SOURCES), &task.id)
.with_context(|| format!("retaining sources of historical run {id}"))?;
}
Ok(())
}
pub(crate) fn source_retention_reason(home: &Path, state: &crate::run::RunState) -> Option<String> {
if explicit_sources_retained(home, &state.id) {
return Some("explicitly retained recovery source".into());
}
if state.status == crate::run::RunStatus::Merged
&& state.merge.as_ref().is_some_and(|merged| merged.ok)
{
return None;
}
crate::queue::Queue::at(home.join("queue"))
.list()
.iter()
.find(|task| task.runs.contains(&state.id))
.map(|task| {
format!(
"source of task {}; inspect recovery lineage before folding",
task.id
)
})
}
pub(crate) fn explicit_sources_retained(home: &Path, id: &str) -> bool {
home.join("runs")
.join(id)
.join(RETAIN_SOURCES)
.try_exists()
.unwrap_or(true)
}
impl Selection {
pub fn source(&self) -> &str {
self.source_head.as_deref().unwrap_or(&self.head)
}
pub fn configure(&self, config: &mut Config) -> Result<()> {
match self.disposition {
Some(Disposition::Land) => {
ensure!(
config.graph.reviewers > 0 && config.graph.review_rounds > 0,
"delivery requires at least one reviewer and review round"
);
ensure!(
!config.verify.gate.is_empty()
&& config.verify.gate.iter().all(|s| !s.trim().is_empty()),
"delivery requires nonempty verify.gate commands; configure the repository's documented gate in a machine/repository layer or recover-pr --config <complete-config>"
);
ensure!(
!config.verify.e2e.is_empty()
&& config.verify.e2e.iter().all(|s| !s.trim().is_empty()),
"delivery requires nonempty verify.e2e commands; configure the repository's required real-machine checks before recover-pr --disposition land"
);
config.merge.mode = MergeMode::Pr;
config.graph.land = true;
config.graph.land_approval = true;
}
Some(Disposition::Review) => {
config.merge.mode = MergeMode::None;
config.graph.land = false;
}
None => anyhow::bail!(
"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)"
),
}
Ok(())
}
pub async fn verify_source(&self, repo: &Path) -> Result<()> {
if self.source_proof.is_some() {
self.verify_source_under(repo, &crate::run::home()).await
} else {
self.verify_source_under(repo, Path::new("")).await
}
}
async fn verify_source_under(&self, repo: &Path, home: &Path) -> Result<()> {
let source = git::rev_parse(repo, &format!("{}^{{commit}}", self.source())).await?;
ensure!(
source == self.source(),
"source-head must resolve to its full commit SHA"
);
if let Some(proof) = &self.source_proof {
let actual = Box::pin(lineage::prove(self, repo, home, &proof.current_base)).await?;
ensure!(
&actual == proof.as_ref(),
"saved source proof changed; select the source again"
);
} else {
ensure!(
git::is_ancestor(repo, &self.head, &source).await,
"source-head does not preserve the selected public implementation by ancestry; supply --source-run <retained-run-id> for a recorded launcher rebase"
);
ensure!(
self.source_run.is_none(),
"source-run requires a saved source proof; select again"
);
}
Ok(())
}
pub async fn prepare_source(
&mut self,
repo: &Path,
home: &Path,
current_base: &str,
) -> Result<()> {
ensure!(
self.source_proof.is_none(),
"source proof is already selected; refusing to replace saved evidence"
);
if self.source_run.is_some() {
self.source_proof = Some(Box::new(
Box::pin(lineage::prove(self, repo, home, current_base)).await?,
));
Ok(())
} else {
self.verify_source(repo).await
}
}
pub fn check_task(&self, task: &str, instruction: &str) -> Result<()> {
self.check_task_assignment(task, instruction, 0)
}
pub fn check_task_assignment(
&self,
task: &str,
instruction: &str,
assignment: usize,
) -> Result<()> {
ensure!(
self.branch == crate::run::task_pr_branch_name(task, assignment),
"recovery head belongs to another task or repository assignment"
);
ensure!(
self.instruction == instruction,
"recovery criteria changed; select the public head again"
);
ensure!(
[self.head.as_str(), self.source()]
.iter()
.all(|sha| sha.len() == 40 && sha.bytes().all(|b| b.is_ascii_hexdigit())),
"recovery requires a full commit SHA"
);
Ok(())
}
pub async fn verify(&self, repo: &Path, remote: &str, base: &str, lease: &str) -> Result<()> {
let pr_repo = land::slug_of_pr_url(&self.url).context("invalid recovery PR URL")?;
for args in [
vec!["remote", "get-url", "--all", remote],
vec!["remote", "get-url", "--push", "--all", remote],
] {
let urls = git::git(repo, &args).await?;
ensure!(
!urls.trim().is_empty(),
"recovery remote has no repository URL"
);
for url in urls.lines() {
let remote_repo =
remote_slug(url).context("cannot prove recovery remote repository identity")?;
land::ensure_same_repo(&remote_repo, &pr_repo)?;
}
}
self.verify_forge_with(Path::new("gh"), repo, base, lease)
.await?;
let fetched = git::fetch(repo, remote, &self.branch).await?;
ensure!(
fetched.ok(),
"fetch selected public head failed: {}",
fetched.stderr
);
let fetched_head =
git::rev_parse(repo, &format!("refs/remotes/{remote}/{}", self.branch)).await?;
ensure!(
fetched_head == lease,
"public head moved; select and approve its new head before recovery"
);
ensure!(
git::remote_head(repo, remote, &self.branch)
.await?
.as_deref()
== Some(lease),
"public head lease changed during recovery"
);
Ok(())
}
async fn verify_forge_with(
&self,
program: &Path,
repo: &Path,
base: &str,
lease: &str,
) -> Result<()> {
let found = land::find_open_pr_with(program, repo, &self.branch, base).await?;
ensure!(
matches!(found, land::OpenPr::One { ref url, .. } if url == &self.url),
"selected PR is not the unique open task PR in this repository"
);
let view = land::gh_with(
program,
repo,
&[
"pr".into(),
"view".into(),
self.url.clone(),
"--json".into(),
"headRefName,headRefOid,baseRefName,state,isCrossRepository".into(),
],
)
.await?;
ensure!(view.ok, "could not verify selected PR: {}", view.combined());
validate_view(&view.stdout, &self.branch, base, lease)
}
}
fn remote_slug(url: &str) -> Option<String> {
let url = url
.trim()
.trim_end_matches('/')
.strip_suffix(".git")
.unwrap_or(url.trim().trim_end_matches('/'));
let (host, path) = if let Some(rest) = url
.strip_prefix("https://")
.or_else(|| url.strip_prefix("http://"))
.or_else(|| url.strip_prefix("ssh://"))
{
let (authority, path) = rest.split_once('/')?;
(authority.rsplit('@').next()?, path)
} else {
let (authority, path) = url.split_once(':')?;
let (_, host) = authority.split_once('@')?;
(host, path)
};
let mut parts = path.split('/');
let owner = parts.next()?;
let repo = parts.next()?;
if host.is_empty() || owner.is_empty() || repo.is_empty() || parts.next().is_some() {
return None;
}
Some(format!("{host}/{owner}/{repo}"))
}
fn validate_view(raw: &str, branch: &str, base: &str, lease: &str) -> Result<()> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct View {
head_ref_name: String,
head_ref_oid: String,
base_ref_name: String,
state: String,
is_cross_repository: bool,
}
let view: View = serde_json::from_str(raw).context("selected public head metadata")?;
ensure!(
view.state == "OPEN"
&& !view.is_cross_repository
&& view.head_ref_name == branch
&& view.base_ref_name == base,
"selected PR ownership or base changed"
);
ensure!(
view.head_ref_oid == lease,
"selected public head moved; refusing recovery"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn cancelled_closed_owner_retires_only_after_exact_selection_and_stopped_driver() {
use crate::{
ask::{Answer, Question, Questions},
queue::{Queue, Source, Task, TaskStatus},
run::{LandApproval, MergeOutcome, Origin, PrRecord, RunState, RunStatus},
task_decision::Decision,
task_inquiry::{Inquiry, Outbox},
};
let home = tempfile::tempdir().unwrap();
let repo = tempfile::tempdir().unwrap();
git::git(repo.path(), &["init"]).await.unwrap();
git::git(
repo.path(),
&[
"-c",
"user.name=fixture",
"-c",
"user.email=fixture@example.test",
"commit",
"--allow-empty",
"-m",
"source",
],
)
.await
.unwrap();
let sha = git::rev_parse(repo.path(), "HEAD").await.unwrap();
let queue = Queue::at(home.path().join("queue"));
let mut task = Task::new(
"recover".into(),
"criteria".into(),
repo.path().into(),
Source::Human,
);
queue.put(&mut task).unwrap();
let mut state = RunState::new(
repo.path().into(),
"main".into(),
sha.clone(),
task.instruction.clone(),
Config::default(),
);
state.origin = Some(Origin::queue(&task.id));
state.status = RunStatus::Blocked;
state.driver_exited = true;
state.config.graph.land = true;
state.merge = Some(MergeOutcome {
mode: MergeMode::Pr,
ok: false,
empty: false,
detail: "held".into(),
});
let old_pr = "https://github.com/example/repo/pull/1";
state.pr = Some(PrRecord {
url: old_pr.into(),
number: 1,
state: "open".into(),
checks: "green".into(),
round: 1,
rounds: 1,
red_at_merge: vec![],
});
let mut question = Question::new(
state.id.clone(),
land::APPROVAL_NODE.into(),
"land".into(),
"merge?".into(),
"approval".into(),
vec!["merge".into()],
);
question.merge_target = Some(crate::merge_decision::Target {
pr: old_pr.into(),
head: sha.clone(),
language: "en".into(),
});
question.answer(Answer::Choice("merge".into())).unwrap();
let questions = Questions::at(home.path().join("questions"));
questions.put(&mut question).unwrap();
state.land_approval = Some(LandApproval {
question: question.id.clone(),
head: sha.clone(),
});
state.save_under(home.path()).unwrap();
task.start(state.id.clone());
task.hold_machine(Some(format!("Existing PR belongs to run {};", state.id)));
task.fresh_start = true;
let selected = Selection {
url: "https://github.com/example/repo/pull/2".into(),
branch: task.publication_branch(),
head: sha,
source_head: None,
source_run: None,
source_proof: None,
disposition: Some(Disposition::Land),
instruction: task.instruction.clone(),
approved_at: jiff::Timestamp::now(),
};
task.pr_recovery = Some(selected.clone());
let replacement_config = home.path().join("replacement.toml");
std::fs::write(&replacement_config, "[merge]\nremote = 'replacement'\nbase = 'trunk'\n[verify]\ngate = ['gate']\ne2e = ['test']\n").unwrap();
task.overrides = Some(crate::queue::RunOverrides {
config: Some(replacement_config),
..Default::default()
});
queue.put(&mut task).unwrap();
let outbox = Outbox::at(home.path());
let mut decision = Decision::awaiting("merge?".into());
decision.accept("decision: merge").unwrap();
decision.source_answer_at = question.answered_at;
outbox
.enqueue(Inquiry {
schema: 1,
id: question.id.clone(),
task: task.id.clone(),
run: Some(state.id.clone()),
repo: task.repo.clone(),
source: land::APPROVAL_NODE.into(),
occurrence: None,
text: "approval".into(),
display: "approval".into(),
key: format!("question:{}", question.id),
evidence: None,
created_at: question.asked_at,
delivered_to: None,
decision: Some(decision),
delivery_error: None,
archived: false,
})
.unwrap();
let retire = async |lifecycle| {
retire_closed_with(
&queue,
home.path(),
&task.id,
&state.id,
&question.id,
async |task, old, selection| {
if matches!(lifecycle, Ok(land::PrLifecycle::Closed)) {
let (remote, base) = replacement_target(task, selection).await?;
assert_eq!((remote.as_str(), base.as_str()), ("replacement", "trunk"));
assert_ne!(base, old.base_branch);
}
lifecycle
},
)
.await
};
assert!(retire(Ok(land::PrLifecycle::Closed)).await.is_err());
outbox
.update_decision(&question.id, |d| {
d.settle_legacy("owner cancelled obsolete approval")
})
.unwrap();
for (lifecycle, diagnostic) in [
(Ok(land::PrLifecycle::Open), "still open"),
(Ok(land::PrLifecycle::Merged), "was merged"),
(
Err(anyhow::anyhow!("unknown")),
"cannot verify old PR lifecycle",
),
] {
let error = retire(lifecycle).await.unwrap_err();
assert!(error.to_string().contains(diagnostic), "{error:#}");
}
let mut other = outbox.get(&question.id).unwrap();
other.id = "other-decision".into();
other.key = "question:other-decision".into();
other.decision = Some(Decision::awaiting("another decision".into()));
outbox.enqueue(other).unwrap();
let error = retire(Ok(land::PrLifecycle::Closed)).await.unwrap_err();
assert!(error.to_string().contains("other-decision"), "{error:#}");
outbox
.update_decision("other-decision", |d| d.settle("no effect needed"))
.unwrap();
let mut legacy = Question::new(
state.id.clone(),
"ask".into(),
"operator".into(),
"another question".into(),
"still pending".into(),
vec![],
);
questions.put(&mut legacy).unwrap();
let error = retire(Ok(land::PrLifecycle::Closed)).await.unwrap_err();
assert!(error.to_string().contains(&legacy.id), "{error:#}");
legacy.abandon("no effect needed");
questions.put(&mut legacy).unwrap();
let migration = home.path().join("notifications/task-chat-migration-v1");
std::fs::create_dir_all(&migration).unwrap();
let journal = migration.join("state.json");
std::fs::write(
&journal,
serde_json::to_vec(&serde_json::json!({
"schema": 1, "pending": [&legacy.id], "sources": [&legacy.id]
}))
.unwrap(),
)
.unwrap();
let error = retire(Ok(land::PrLifecycle::Closed)).await.unwrap_err();
assert!(error.to_string().contains(&legacy.id), "{error:#}");
std::fs::write(
&journal,
serde_json::to_vec(&serde_json::json!({
"schema": 1, "pending": [], "sources": [&legacy.id]
}))
.unwrap(),
)
.unwrap();
let held = crate::driver::maintenance(home.path(), &state.id).unwrap();
assert!(retire(Ok(land::PrLifecycle::Closed)).await.is_err());
drop(held);
assert_eq!(
RunState::load_under(&state.id, home.path()).unwrap().status,
RunStatus::Blocked
);
let owner = crate::daemon::public_resume_owner(home.path(), &task.runs, &task.repo)
.await
.unwrap()
.unwrap();
assert_eq!(owner.id, state.id);
retire(Ok(land::PrLifecycle::Closed)).await.unwrap();
let retired = RunState::load_under(&state.id, home.path()).unwrap();
assert_eq!(retired.status, RunStatus::Superseded);
assert_eq!(retired.pr.as_ref().unwrap().state, "closed");
assert!(!crate::handover::landing_checkpoint(&retired));
assert!(
crate::daemon::public_resume_owner(home.path(), &task.runs, &task.repo)
.await
.unwrap()
.is_none()
);
assert_eq!(
questions
.read_history(&question.id)
.unwrap()
.resolution()
.as_deref(),
Some("merge")
);
assert!(
questions
.get_for_effects(&question.id)
.unwrap()
.resolution()
.is_none()
);
let queued = queue.get(&task.id).unwrap();
assert_eq!(queued.status, TaskStatus::Queued);
assert!(queued.fresh_start);
assert_eq!(queued.pr_recovery.as_ref(), Some(&selected));
assert_eq!(queued.attempts, task.attempts);
retire(Ok(land::PrLifecycle::Closed)).await.unwrap();
assert_eq!(
RunState::load_under(&state.id, home.path())
.unwrap()
.closed_pr_retirement,
retired.closed_pr_retirement
);
}
#[test]
fn recovery_uses_resolved_layers_and_preserves_unrelated_overrides() {
let dir = tempfile::tempdir().unwrap();
let machine = dir.path().join("machine.toml");
let repo = dir.path().join("repository.toml");
std::fs::write(&machine, "[verify]\ngate = ['documented gate']\ne2e = ['real checks']\n[graph]\nland = false\nland_approval = false\n").unwrap();
std::fs::write(&repo, "[merge]\nmode = 'none'\nbase = 'trunk'\n").unwrap();
let mut config = Config::load_layers(&[machine, repo]).unwrap();
let overrides = crate::queue::RunOverrides {
merge: Some("none".into()),
reviewers: Some(2),
..Default::default()
};
overrides.apply(&mut config);
let mut selection = Selection {
url: "url".into(),
branch: "magi/task-t".into(),
head: "a".repeat(40),
source_head: None,
source_run: None,
source_proof: None,
disposition: Some(Disposition::Land),
instruction: "criteria".into(),
approved_at: jiff::Timestamp::now(),
};
selection.configure(&mut config).unwrap();
assert_eq!(config.merge.mode, MergeMode::Pr);
assert_eq!(config.graph.reviewers, 2);
assert_eq!(config.merge.base.as_deref(), Some("trunk"));
assert_eq!(config.verify.gate, ["documented gate"]);
assert_eq!(config.verify.e2e, ["real checks"]);
assert!(config.graph.land && config.graph.land_approval);
let explicit = dir.path().join("explicit.toml");
std::fs::write(&explicit, "[merge]\nbase = 'other'\n").unwrap();
let (mut replacement, paths) = Config::discover(dir.path(), Some(&explicit)).unwrap();
assert_eq!(paths, [explicit]);
assert!(
selection
.configure(&mut replacement)
.unwrap_err()
.to_string()
.contains("verify.gate")
);
replacement.verify.gate = vec![" ".into()];
assert!(selection.configure(&mut replacement).is_err());
selection.disposition = Some(Disposition::Review);
selection.configure(&mut replacement).unwrap();
assert_eq!(replacement.merge.mode, MergeMode::None);
assert!(!replacement.graph.land);
}
#[test]
fn selected_source_requires_the_same_fetch_and_push_repository() {
for remote in [
"https://example.test/team/project.git",
"git@example.test:team/project.git",
"ssh://git@example.test/team/project.git",
] {
assert_eq!(
remote_slug(remote).as_deref(),
Some("example.test/team/project")
);
}
assert!(remote_slug("/tmp/another.git").is_none());
assert!(
land::ensure_same_repo(
&remote_slug("git@example.test:team/other.git").unwrap(),
"example.test/team/project"
)
.is_err()
);
assert!(
land::ensure_same_repo(
&remote_slug("git@other.test:team/project.git").unwrap(),
"example.test/team/project"
)
.is_err()
);
}
#[test]
fn selected_head_refuses_moved_or_foreign_public_heads() {
let raw = r#"{"headRefName":"magi/task-t","headRefOid":"aaa","baseRefName":"main","state":"OPEN","isCrossRepository":false}"#;
assert!(validate_view(raw, "magi/task-t", "main", "aaa").is_ok());
assert!(validate_view(raw, "magi/task-t", "main", "bbb").is_err());
assert!(validate_view(raw, "magi/task-other", "main", "aaa").is_err());
assert!(validate_view(raw, "magi/task-t", "other", "aaa").is_err());
assert!(
validate_view(&raw.replace("false", "true"), "magi/task-t", "main", "aaa").is_err()
);
assert!(
validate_view(&raw.replace("OPEN", "CLOSED"), "magi/task-t", "main", "aaa").is_err()
);
}
#[test]
fn selected_head_is_bound_to_authored_criteria_and_task() {
let selected = Selection {
url: "url".into(),
branch: "magi/task-t".into(),
head: "a".repeat(40),
source_head: None,
source_run: None,
source_proof: None,
disposition: Some(Disposition::Review),
instruction: "approved".into(),
approved_at: jiff::Timestamp::now(),
};
assert!(selected.check_task("t", "approved").is_ok());
assert!(
selected
.check_task("t", "prose mentioning another candidate")
.is_err()
);
assert!(selected.check_task("other", "approved").is_err());
assert!(selected.check_task_assignment("t", "approved", 2).is_err());
let mut reassigned = selected;
reassigned.branch = "magi/task-t-assignment-2".into();
assert!(reassigned.check_task_assignment("t", "approved", 2).is_ok());
assert!(
reassigned
.check_task_assignment("t", "approved", 1)
.is_err()
);
assert!(reassigned.check_task("t", "approved").is_err());
}
fn fake_recovery_gh(
dir: &Path,
name: &str,
list: (&str, &str, i32),
view: (&str, &str, i32),
) -> std::path::PathBuf {
let list_out = dir.join(format!("{name}-list.stdout"));
let list_err = dir.join(format!("{name}-list.stderr"));
let view_out = dir.join(format!("{name}-view.stdout"));
let view_err = dir.join(format!("{name}-view.stderr"));
std::fs::write(&list_out, list.0).unwrap();
std::fs::write(&list_err, list.1).unwrap();
std::fs::write(&view_out, view.0).unwrap();
std::fs::write(&view_err, view.1).unwrap();
#[cfg(windows)]
{
let script = dir.join(format!("{name}.cmd"));
let mut body = String::from("@echo off\r\n");
body.push_str("if \"%~1 %~2\"==\"pr list\" (\r\n");
if !list.0.is_empty() {
body.push_str(&format!(" type \"{}\"\r\n", list_out.display()));
}
if !list.1.is_empty() {
body.push_str(&format!(" type \"{}\" 1>&2\r\n", list_err.display()));
}
body.push_str(&format!(" exit /b {}\r\n)\r\n", list.2));
body.push_str("if \"%~1 %~2\"==\"pr view\" (\r\n");
if !view.0.is_empty() {
body.push_str(&format!(" type \"{}\"\r\n", view_out.display()));
}
if !view.1.is_empty() {
body.push_str(&format!(" type \"{}\" 1>&2\r\n", view_err.display()));
}
body.push_str(&format!(" exit /b {}\r\n)\r\n", view.2));
body.push_str("exit /b 1\r\n");
std::fs::write(&script, body).unwrap();
script
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
let script = dir.join(name);
let emit = |out: &Path, err: &Path, has_out: bool, has_err: bool, code: i32| {
let mut s = String::new();
if has_out {
s.push_str(&format!("cat {}; ", quote(out)));
}
if has_err {
s.push_str(&format!("cat {} >&2; ", quote(err)));
}
s.push_str(&format!("exit {code}"));
s
};
let body = format!(
"#!/bin/sh\ncase \"$1 $2\" in\n 'pr list') {} ;;\n 'pr view') {} ;;\n *) exit 1 ;;\nesac\n",
emit(
&list_out,
&list_err,
!list.0.is_empty(),
!list.1.is_empty(),
list.2
),
emit(
&view_out,
&view_err,
!view.0.is_empty(),
!view.1.is_empty(),
view.2
),
);
let status = std::process::Command::new("sh")
.args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
.arg(&script)
.arg(&body)
.status()
.unwrap();
assert!(status.success());
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
script
}
}
#[tokio::test]
async fn verify_forge_separates_json_stdout_from_stderr_hints_and_keeps_strict_guards() {
let tmp = tempfile::tempdir().unwrap();
let sha = "a".repeat(40);
let selected = Selection {
url: "https://github.com/example/repo/pull/1".into(),
branch: "magi/task-t".into(),
head: sha.clone(),
source_head: None,
source_run: None,
source_proof: None,
disposition: Some(Disposition::Land),
instruction: "approved".into(),
approved_at: jiff::Timestamp::now(),
};
let hint = "To listen to events, run: gh pr view --web\n";
let list_json = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: recovered","baseRefName":"main","isCrossRepository":false}]"#;
let view_json = format!(
r#"{{"headRefName":"magi/task-t","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":false}}"#
);
let concatenated = format!("{view_json}\n{hint}");
let strict_err = validate_view(&concatenated, &selected.branch, "main", &sha).unwrap_err();
assert!(
format!("{strict_err:#}").contains("trailing characters"),
"{strict_err:#}"
);
let ok_gh = fake_recovery_gh(
tmp.path(),
"ok",
(&format!("{list_json}\n"), hint, 0),
(&format!("{view_json}\n"), hint, 0),
);
selected
.verify_forge_with(&ok_gh, tmp.path(), "main", &sha)
.await
.unwrap();
let malformed_gh = fake_recovery_gh(
tmp.path(),
"malformed",
(&format!("{list_json}\n"), "", 0),
(&format!("{view_json}\ntrailing text\n"), "", 0),
);
let err = selected
.verify_forge_with(&malformed_gh, tmp.path(), "main", &sha)
.await
.unwrap_err();
assert!(
format!("{err:#}").contains("trailing characters"),
"{err:#}"
);
let empty_gh = fake_recovery_gh(
tmp.path(),
"empty",
(&format!("{list_json}\n"), "", 0),
("", hint, 0),
);
assert!(
selected
.verify_forge_with(&empty_gh, tmp.path(), "main", &sha)
.await
.is_err()
);
let failed_gh = fake_recovery_gh(
tmp.path(),
"failed",
(&format!("{list_json}\n"), "", 0),
(
&format!("{view_json}\n"),
"gh: authentication required\n",
1,
),
);
let err = selected
.verify_forge_with(&failed_gh, tmp.path(), "main", &sha)
.await
.unwrap_err()
.to_string();
assert!(err.contains("authentication required"), "{err}");
assert!(
selected
.verify_forge_with(&ok_gh, tmp.path(), "main", &"b".repeat(40))
.await
.unwrap_err()
.to_string()
.contains("moved")
);
let wrong_branch_gh = fake_recovery_gh(
tmp.path(),
"wrong-branch",
(&format!("{list_json}\n"), hint, 0),
(
&format!(
r#"{{"headRefName":"magi/task-other","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":false}}"#
),
hint,
0,
),
);
assert!(
selected
.verify_forge_with(&wrong_branch_gh, tmp.path(), "main", &sha)
.await
.unwrap_err()
.to_string()
.contains("ownership or base changed")
);
let fork_gh = fake_recovery_gh(
tmp.path(),
"fork",
(&format!("{list_json}\n"), hint, 0),
(
&format!(
r#"{{"headRefName":"magi/task-t","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":true}}"#
),
hint,
0,
),
);
assert!(
selected
.verify_forge_with(&fork_gh, tmp.path(), "main", &sha)
.await
.unwrap_err()
.to_string()
.contains("ownership or base changed")
);
}
}