1use std::path::{Path, PathBuf};
22
23use anyhow::Result;
24
25use crate::git;
26use crate::run::{Liveness, RunState, RunStatus};
27
28#[derive(Debug, Clone)]
30pub struct Takeover {
31 pub earlier: Vec<String>,
34 pub home: PathBuf,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Refused(pub String);
44
45impl std::fmt::Display for Refused {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 f.write_str(&self.0)
48 }
49}
50
51impl std::error::Error for Refused {}
52
53#[derive(Debug, Clone)]
56pub struct Released {
57 pub old_id: String,
59 index: usize,
60 path: PathBuf,
61 home: PathBuf,
62 tip: String,
65}
66
67impl Released {
68 pub async fn restore(&self, repo: &Path, branch: &str) {
72 let path = self.path.to_string_lossy().to_string();
73 let refname = format!("refs/heads/{branch}");
76 if git::rev_parse(repo, &refname).await.ok().as_deref() != Some(self.tip.as_str())
77 && let Err(e) = git::git(repo, &["branch", "-f", branch, &self.tip]).await
78 {
79 tracing::warn!("could not put `{branch}` back at {}: {e:#}", self.tip);
80 return;
81 }
82 if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
83 tracing::warn!(
84 "could not put run {}'s worktree back at {path}: {e:#}",
85 self.old_id
86 );
87 return;
88 }
89 let put_back = RunState::load_under(&self.old_id, &self.home).and_then(|mut s| {
90 if let Some(c) = s.candidates.get_mut(self.index) {
91 c.folded = false;
92 }
93 s.released_to = None;
94 s.released_branches.retain(|b| b != branch);
95 s.events.pop();
96 s.save_under(&self.home)
97 });
98 if let Err(e) = put_back {
99 tracing::warn!("could not unmark run {}: {e:#}", self.old_id);
100 }
101 }
102}
103
104#[derive(Debug, Clone)]
106pub struct Holder {
107 pub run: String,
109 pub status: RunStatus,
111 pub liveness: Liveness,
113 pub driver_unproven: bool,
116 pub dirty: bool,
118 pub head: String,
120 pub tip: String,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126pub enum Decision {
127 Release,
129 Refuse(String),
132 NotOurs,
135}
136
137fn short(sha: &str) -> String {
138 sha.chars().take(7).collect()
139}
140
141pub fn decide(superseded: bool, holder: &Holder) -> Decision {
147 if !superseded {
148 return Decision::NotOurs;
149 }
150 let mut why = Vec::new();
151 if holder.liveness == Liveness::Live {
152 why.push("that run is being worked on right now".to_owned());
153 } else if holder.driver_unproven {
154 why.push("its driver process could not be shown to be gone".to_owned());
155 }
156 if holder.dirty {
157 why.push("its worktree has uncommitted changes".to_owned());
158 }
159 if holder.head != holder.tip {
160 why.push("its HEAD is not at the branch tip".to_owned());
161 }
162 if why.is_empty() {
163 return Decision::Release;
164 }
165 Decision::Refuse(format!(
166 "run {} (status `{}`, worktree {}, HEAD {}, branch tip {}) is an earlier attempt \
167 at this task and still has the branch checked out, so it was not released \
168 automatically: {}",
169 crate::run::short_of(&holder.run),
170 holder.status.as_str(),
171 if holder.dirty { "dirty" } else { "clean" },
172 short(&holder.head),
173 short(&holder.tip),
174 why.join("; ")
175 ))
176}
177
178async fn inspect(
180 repo: &Path,
181 branch: &str,
182 path: &Path,
183 state: &RunState,
184 home: &Path,
185) -> Result<Holder> {
186 let claimed = crate::daemon::is_working_on(home, &state.id, jiff::Timestamp::now());
187 let liveness = state.liveness(claimed);
188 Ok(Holder {
189 run: state.id.clone(),
190 status: state.status,
191 liveness,
192 driver_unproven: liveness == Liveness::Unknown && state.driver_pid.is_some(),
193 dirty: !git::status_porcelain(path).await?.trim().is_empty(),
194 head: git::rev_parse(path, "HEAD").await?,
195 tip: git::rev_parse(repo, &format!("refs/heads/{branch}")).await?,
196 })
197}
198
199fn same_path(a: &Path, b: &Path) -> bool {
200 let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
201 canon(a) == canon(b)
202}
203
204pub async fn release(
212 repo: &Path,
213 branch: &str,
214 new_run: &str,
215 takeover: &Takeover,
216) -> Result<Option<Released>> {
217 let Some(path) = git::worktree_holding(repo, branch).await? else {
218 return Ok(None);
219 };
220 let mut owner = None;
223 for id in &takeover.earlier {
224 let Ok(state) = RunState::load_under(id, &takeover.home) else {
225 continue;
226 };
227 if let Some(i) = state
228 .candidates
229 .iter()
230 .position(|c| !c.folded && same_path(&c.worktree, &path))
231 {
232 owner = Some((state, i));
233 break;
234 }
235 }
236 let Some((mut state, index)) = owner else {
237 return Err(Refused(format!(
238 "branch `{branch}` is checked out in {}, which is not a worktree of an earlier \
239 attempt at this task (a run of another task, or one made by hand), so it was \
240 not touched. Remove that worktree (`git worktree remove`) if it is not needed, \
241 and try again.",
242 path.display()
243 ))
244 .into());
245 };
246
247 let holder = inspect(repo, branch, &path, &state, &takeover.home).await?;
248 match decide(true, &holder) {
249 Decision::NotOurs => return Ok(None),
250 Decision::Refuse(why) => {
251 return Err(Refused(format!(
252 "branch `{branch}` is checked out in {}: {why}. Commit or discard the work \
253 there and remove that worktree (`git worktree remove`), or say the run may be \
254 discarded, and try again.",
255 path.display()
256 ))
257 .into());
258 }
259 Decision::Release => {}
260 }
261
262 let old_id = state.id.clone();
263 state.candidates[index].folded = true;
264 state.released_to = Some(new_run.to_owned());
265 if !state.released_branches.iter().any(|b| b == branch) {
266 state.released_branches.push(branch.to_owned());
267 }
268 state.event(
269 "release",
270 format!(
271 "worktree of `{branch}` released to run {}; this run can no longer be resumed \
272 from here",
273 crate::run::short_of(new_run)
274 ),
275 );
276 state.save_under(&takeover.home)?;
277
278 let again = match RunState::load_under(&old_id, &takeover.home) {
286 Ok(fresh) => inspect(repo, branch, &path, &fresh, &takeover.home).await,
287 Err(e) => Err(e),
288 };
289 let safe = matches!(&again, Ok(h) if decide(true, h) == Decision::Release);
290 let removed = safe
291 && git::worktree_remove_clean(repo, &path)
292 .await
293 .unwrap_or(false);
294 if !removed || path.exists() {
295 state = RunState::load_under(&old_id, &takeover.home)?;
296 state.candidates[index].folded = false;
297 state.released_to = None;
298 state.released_branches.retain(|b| b != branch);
299 state.events.pop();
300 state.save_under(&takeover.home)?;
301 return Err(Refused(format!(
302 "branch `{branch}` is checked out in {} by run {}, and releasing that worktree \
303 failed or found it changed (git refuses to remove a worktree with uncommitted \
304 changes); it was left as it was",
305 path.display(),
306 crate::run::short_of(&old_id)
307 ))
308 .into());
309 }
310 Ok(Some(Released {
311 old_id,
312 index,
313 path,
314 home: takeover.home.clone(),
315 tip: holder.tip,
316 }))
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 fn holder() -> Holder {
324 Holder {
325 run: "20260901-000000-f82f".to_owned(),
326 status: RunStatus::Gating,
327 liveness: Liveness::Unknown,
328 driver_unproven: false,
329 dirty: false,
330 head: "a".repeat(40),
331 tip: "a".repeat(40),
332 }
333 }
334
335 #[test]
336 fn a_clean_superseded_stale_run_is_released() {
337 assert_eq!(decide(true, &holder()), Decision::Release);
338 let dead = Holder {
339 liveness: Liveness::Dead,
340 ..holder()
341 };
342 assert_eq!(decide(true, &dead), Decision::Release);
343 }
344
345 #[test]
346 fn a_run_that_is_not_superseded_is_not_ours() {
347 assert_eq!(decide(false, &holder()), Decision::NotOurs);
348 }
349
350 #[test]
351 fn a_dirty_worktree_is_refused_and_says_why() {
352 let dirty = Holder {
353 dirty: true,
354 ..holder()
355 };
356 let Decision::Refuse(why) = decide(true, &dirty) else {
357 panic!("dirty must be refused");
358 };
359 assert!(why.contains("uncommitted"), "{why}");
360 assert!(why.contains("f82f") && why.contains("gating") && why.contains("dirty"));
361 }
362
363 #[test]
364 fn a_live_run_is_refused() {
365 let live = Holder {
366 liveness: Liveness::Live,
367 ..holder()
368 };
369 let Decision::Refuse(why) = decide(true, &live) else {
370 panic!("live must be refused");
371 };
372 assert!(why.contains("right now"), "{why}");
373 }
374
375 #[test]
376 fn a_driver_that_could_not_be_shown_dead_is_refused() {
377 let unproven = Holder {
378 driver_unproven: true,
379 ..holder()
380 };
381 let Decision::Refuse(why) = decide(true, &unproven) else {
382 panic!("an unproven driver must be refused");
383 };
384 assert!(why.contains("driver"), "{why}");
385 }
386
387 #[test]
388 fn a_head_off_the_tip_is_refused() {
389 let off = Holder {
390 head: "b".repeat(40),
391 ..holder()
392 };
393 assert!(matches!(decide(true, &off), Decision::Refuse(_)));
394 }
395}