1use std::collections::BTreeSet;
25use std::path::{Path, PathBuf};
26
27use anyhow::{Context as _, Result, bail};
28use jiff::{SignedDuration, Timestamp};
29use serde::Deserialize;
30
31use crate::ask::Questions;
32use crate::config::Disk;
33use crate::run::{RunState, RunStatus, SCHEMA, short_of};
34
35use crate::disk::{Prune, dir_size};
36
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39pub struct Housekeeping {
40 pub folded: usize,
42 pub unreadable: usize,
52 pub orphaned_worktrees: usize,
55 pub cache_files: usize,
57 pub cache_freed: u64,
59 pub questions_abandoned: usize,
62 pub external_merges_recorded: usize,
67 pub stale_pr_states_repaired: usize,
71}
72
73pub async fn housekeep(
81 cfg: &crate::config::Config,
82 home: &Path,
83 worktrees_root: &Path,
84 repo: &Path,
85 now: Timestamp,
86) -> Housekeeping {
87 let mut out = Housekeeping::default();
88 crate::retention::sweep(home, &cfg.disk, now).await;
89 if cfg.disk.auto_fold {
90 let runs = home.join("runs");
91 match fold_due(&runs, home, worktrees_root, &cfg.disk, now).await {
92 Ok((folded, unreadable)) => {
93 out.folded = folded;
94 out.unreadable = unreadable;
95 }
96 Err(e) => {
97 tracing::warn!("housekeep: fold due runs: {e:#}");
98 crate::notices::raise_in(
101 home,
102 crate::notices::Notice::warn(
103 "housekeep:fold",
104 "Automatic cleanup of finished runs failed; disk usage may keep growing.",
105 ),
106 );
107 }
108 }
109 out.orphaned_worktrees =
110 fold_orphaned_worktrees(&runs, worktrees_root, home, cfg.disk.fold_grace_secs, now)
111 .await;
112 if let Err(e) = crate::git::worktree_prune(repo).await {
116 tracing::warn!("housekeep: prune worktree registrations: {e:#}");
117 }
118 out.external_merges_recorded = reconcile_external_merges(&runs, home, &cfg.disk, now).await;
119 out.stale_pr_states_repaired = crate::land::repair_stale_pr_states(home, 5).await.0;
122 }
123 match prune_cache_if_over_limit(cfg, home) {
124 Ok(Some(pruned)) => {
125 out.cache_files = pruned.files;
126 out.cache_freed = pruned.freed;
127 }
128 Ok(None) => {}
129 Err(e) => tracing::warn!("housekeep: prune cache: {e:#}"),
130 }
131 match crate::build_target::prune_registered(home, &cfg.disk) {
132 Ok(pruned) => {
133 out.cache_files = out.cache_files.saturating_add(pruned.files);
134 out.cache_freed = out.cache_freed.saturating_add(pruned.freed);
135 }
136 Err(e) => tracing::warn!("housekeep: prune isolated builds: {e:#}"),
137 }
138 out.questions_abandoned =
146 abandon_settled_questions(&Questions::at(home.join("questions")), &home.join("runs"));
147 out
148}
149
150pub fn abandon_settled_questions(store: &Questions, runs: &Path) -> usize {
161 let waiting_on: BTreeSet<String> = store
162 .list()
163 .into_iter()
164 .filter(|q| q.status.open())
165 .map(|q| q.run)
166 .collect();
167 let mut abandoned = 0;
168 for run in waiting_on {
169 let Ok(meta) = read_meta(runs, &run) else {
170 continue;
171 };
172 match store.settle_run(&run, meta.status) {
173 Ok(n) => abandoned += n,
174 Err(e) => tracing::warn!("housekeep: abandon questions for {run}: {e:#}"),
175 }
176 }
177 abandoned
178}
179
180pub async fn fold_due(
205 runs: &Path,
206 home: &Path,
207 _worktrees_root: &Path,
208 disk: &Disk,
209 now: Timestamp,
210) -> Result<(usize, usize)> {
211 let mut folded = 0usize;
212 let mut unreadable = 0usize;
213 let mut ids: Vec<String> = std::fs::read_dir(runs)
214 .into_iter()
215 .flatten()
216 .flatten()
217 .filter(|e| e.path().join("run.json").is_file())
218 .map(|e| e.file_name().to_string_lossy().into_owned())
219 .collect();
220 ids.sort_unstable();
221 for id in ids {
222 if crate::daemon::is_working_on(home, &id, now) {
223 continue;
224 }
225 let meta = match read_meta(runs, &id) {
226 Ok(meta) => meta,
227 Err(e) => {
228 unreadable += 1;
229 tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
230 continue;
231 }
232 };
233 if meta.status.resumable() || !due(now, meta.updated_at, disk.fold_grace_secs) {
234 continue;
235 }
236 let mut state = match read_state(runs, &id) {
245 Ok(state) => state,
246 Err(e) => {
247 unreadable += 1;
248 tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
249 continue;
250 }
251 };
252 if state.startup.as_ref().is_some_and(|s| !s.complete) {
253 continue;
254 }
255 if let Some(reason) = crate::pr_recovery::source_retention_reason(home, &state) {
256 tracing::info!(%id, %reason, "housekeep: source retained; fold refused");
257 continue;
258 }
259 if state.schema != SCHEMA {
260 tracing::info!(
261 "housekeep: run {id} was written by schema {} (this build speaks {SCHEMA}); \
262 folding it anyway",
263 state.schema
264 );
265 }
266 let drop_winner = matches!(
276 state.status,
277 RunStatus::Merged | RunStatus::Superseded | RunStatus::AlreadyInBase
278 );
279 match crate::graph::fold_run(&mut state, drop_winner, home).await {
286 Ok(_) => folded += 1,
287 Err(e) => tracing::warn!("housekeep: fold {id}: {e:#}"),
288 }
289 }
290 Ok((folded, unreadable))
291}
292
293#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
295pub struct FetchReport {
296 pub fetched: usize,
298 pub no_origin: usize,
300 pub failed: usize,
302}
303
304pub async fn fetch_origins(
312 roots: &[PathBuf],
313 per_repo: std::time::Duration,
314 stop: impl Fn() -> bool,
315) -> FetchReport {
316 let mut report = FetchReport::default();
317 for repo in crate::repos::scan(roots) {
318 if stop() {
319 break;
320 }
321 match crate::git::git_raw(&repo.path, &["remote", "get-url", "origin"]).await {
322 Ok(out) if out.ok() => {}
323 _ => {
324 report.no_origin += 1;
325 continue;
326 }
327 }
328 match crate::git::fetch_origin(&repo.path, per_repo).await {
329 Ok(()) => report.fetched += 1,
330 Err(e) => {
331 tracing::warn!("fetch origin in {}: {e:#}", repo.name);
332 report.failed += 1;
333 }
334 }
335 }
336 report
337}
338
339pub fn due(now: Timestamp, updated: Timestamp, grace_secs: u64) -> bool {
345 now.duration_since(updated) > SignedDuration::new(grace_secs as i64, 0)
346}
347
348#[derive(Deserialize)]
351struct Meta {
352 status: RunStatus,
353 updated_at: Timestamp,
354}
355
356fn read_meta(runs: &Path, id: &str) -> Result<Meta> {
360 let path = runs.join(id).join("run.json");
361 let body =
362 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
363 let meta: Meta =
364 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
365 Ok(meta)
366}
367
368const MAX_EXTERNAL_MERGE_CHECKS_PER_PASS: usize = 5;
374
375#[derive(Deserialize)]
378struct ExternalMergeMeta {
379 status: RunStatus,
380 updated_at: Timestamp,
381 #[serde(default)]
382 merge: Option<crate::run::MergeOutcome>,
383}
384
385fn read_external_merge_meta(runs: &Path, id: &str) -> Result<ExternalMergeMeta> {
386 let path = runs.join(id).join("run.json");
387 let body =
388 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
389 let meta: ExternalMergeMeta =
390 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
391 Ok(meta)
392}
393
394pub fn eligible_for_external_merge_check(
403 status: RunStatus,
404 merge_recorded: bool,
405 updated_at: Timestamp,
406 now: Timestamp,
407 grace_secs: u64,
408) -> bool {
409 status == RunStatus::Blocked && !merge_recorded && due(now, updated_at, grace_secs)
410}
411
412fn rotate_from(ids: &[String], start: usize) -> Vec<String> {
430 if ids.is_empty() {
431 return Vec::new();
432 }
433 let start = start % ids.len();
434 ids[start..]
435 .iter()
436 .chain(ids[..start].iter())
437 .cloned()
438 .collect()
439}
440
441const EXTERNAL_MERGE_CURSOR_FILE: &str = "external-merge-cursor";
445
446fn read_external_merge_cursor(home: &Path) -> usize {
451 std::fs::read_to_string(home.join(EXTERNAL_MERGE_CURSOR_FILE))
452 .ok()
453 .and_then(|s| s.trim().parse().ok())
454 .unwrap_or(0)
455}
456
457fn write_external_merge_cursor(home: &Path, cursor: usize) {
462 if let Err(e) = std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), cursor.to_string()) {
463 tracing::warn!("housekeep: persist the external-merge sweep's cursor: {e:#}");
464 }
465}
466
467async fn reconcile_external_merges(runs: &Path, home: &Path, disk: &Disk, now: Timestamp) -> usize {
488 reconcile_external_merges_with(runs, home, disk, now, |state| async move {
489 crate::land::find_external_merge(&state).await
490 })
491 .await
492}
493
494async fn reconcile_external_merges_with<F, Fut>(
495 runs: &Path,
496 home: &Path,
497 disk: &Disk,
498 now: Timestamp,
499 check: F,
500) -> usize
501where
502 F: Fn(RunState) -> Fut,
503 Fut: std::future::Future<Output = Result<Option<crate::land::ExternalMerge>>>,
504{
505 let mut ids: Vec<String> = std::fs::read_dir(runs)
506 .into_iter()
507 .flatten()
508 .flatten()
509 .filter(|e| e.path().join("run.json").is_file())
510 .map(|e| e.file_name().to_string_lossy().into_owned())
511 .collect();
512 ids.sort_unstable();
513
514 let mut eligible: Vec<String> = Vec::new();
520 for id in ids {
521 if crate::daemon::is_working_on(home, &id, now) {
522 continue;
523 }
524 let meta = match read_external_merge_meta(runs, &id) {
525 Ok(meta) => meta,
526 Err(_) => continue,
529 };
530 if eligible_for_external_merge_check(
531 meta.status,
532 meta.merge.is_some(),
533 meta.updated_at,
534 now,
535 disk.fold_grace_secs,
536 ) {
537 eligible.push(id);
538 }
539 }
540
541 if eligible.is_empty() {
542 return 0;
543 }
544 let cursor = read_external_merge_cursor(home);
545 let window: Vec<String> = rotate_from(&eligible, cursor)
546 .into_iter()
547 .take(MAX_EXTERNAL_MERGE_CHECKS_PER_PASS)
548 .collect();
549 write_external_merge_cursor(home, (cursor + window.len()) % eligible.len());
554
555 let mut reconciled = 0usize;
556 for id in window {
557 let mut state = match read_state(runs, &id) {
558 Ok(state) => state,
559 Err(_) => continue,
560 };
561 if let Ok(record) = serde_json::to_value(&state)
562 && let Some(reason) =
563 crate::external_merge_attention::historical_reason(home, &id, &record)
564 {
565 tracing::info!("housekeep: external merge for {id}: {reason}");
566 continue;
567 }
568 match check(state.clone()).await {
569 Ok(Some(found)) => {
570 match crate::land::correct_confirmed_external_merge(&mut state, &found.url).await {
571 Ok(_) => {
572 if let Err(e) = crate::graph::fold_run(&mut state, true, home).await {
573 tracing::warn!(
574 "housekeep: fold {id} after recording its external merge: {e:#}"
575 );
576 }
577 reconciled += 1;
578 }
579 Err(e) => tracing::warn!(
580 "housekeep: record external merge {} for {id}: {e:#}",
581 found.url
582 ),
583 }
584 }
585 Ok(None) => {}
586 Err(e) => {
587 tracing::warn!("housekeep: check external merge for {id}: {e:#}");
588 crate::notices::raise_in(
589 home,
590 crate::notices::Notice::warn(
591 &format!("merged-unrecorded:{id}"),
592 format!(
593 "Run {id} is blocked with no recorded merge, and checking GitHub \
594 for a merge failed; check by hand."
595 ),
596 )
597 .link(crate::notices::Link::Run { id: id.clone() }),
598 );
599 }
600 }
601 }
602 reconciled
603}
604
605fn read_state(runs: &Path, id: &str) -> Result<RunState> {
620 let path = runs.join(id).join("run.json");
621 let body =
622 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
623 let state: RunState =
624 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
625 Ok(state)
626}
627
628async fn remove_clean_bay(root: &Path) -> Result<()> {
631 let mut pending = vec![root.to_path_buf()];
632 let mut directories = Vec::new();
633 let mut worktrees = Vec::new();
634 while let Some(path) = pending.pop() {
635 if path.join(".git").exists() {
636 if !crate::git::is_clean(&path).await? {
637 anyhow::bail!("uncommitted work in {}; recovery required", path.display());
638 }
639 worktrees.push(path);
640 } else {
641 for entry in std::fs::read_dir(&path)? {
642 let entry = entry?;
643 if !entry.file_type()?.is_dir() {
644 anyhow::bail!(
645 "unknown worktree content in {}; recovery required",
646 path.display()
647 );
648 }
649 pending.push(entry.path());
650 }
651 directories.push(path);
652 }
653 }
654 for path in worktrees {
655 if !crate::git::worktree_remove_clean(&path, &path).await? {
656 anyhow::bail!("clean worktree removal refused: {}", path.display());
657 }
658 }
659 for path in directories.into_iter().rev() {
660 std::fs::remove_dir(path)?;
661 }
662 Ok(())
663}
664
665pub async fn fold_unreadable(runs: &Path, worktrees_root: &Path, id: &str) -> Result<Vec<String>> {
673 let resolved = resolve_id_path(runs, id)?;
674 let mut removed = Vec::new();
675 let run_dir = runs.join(&resolved);
676 let wt = worktrees_root.join(short_of(&resolved));
677 if wt.exists() {
678 remove_clean_bay(&wt).await?;
679 removed.push(wt.to_string_lossy().into_owned());
680 }
681 if run_dir.exists() {
683 std::fs::remove_dir_all(&run_dir)
684 .with_context(|| format!("remove {}", run_dir.display()))?;
685 removed.push(format!("runs/{resolved}"));
686 }
687 Ok(removed)
688}
689
690pub async fn fold_orphaned_worktrees(
729 runs: &Path,
730 worktrees_root: &Path,
731 home: &Path,
732 grace_secs: u64,
733 now: Timestamp,
734) -> usize {
735 let known: std::collections::HashSet<String> = std::fs::read_dir(runs)
736 .into_iter()
737 .flatten()
738 .flatten()
739 .map(|e| e.file_name().to_string_lossy().into_owned())
740 .filter(|name| crate::run::is_run_id(name))
741 .map(|id| short_of(&id).to_owned())
742 .collect();
743
744 let mut folded = 0usize;
745 for entry in std::fs::read_dir(worktrees_root)
746 .into_iter()
747 .flatten()
748 .flatten()
749 {
750 if !entry.path().is_dir() {
751 continue;
752 }
753 let short = entry.file_name().to_string_lossy().into_owned();
754 if !looks_like_a_worktree_bay(&short) {
755 continue;
756 }
757 if known.contains(&short) || crate::daemon::is_working_on_short(home, &short, now) {
758 continue;
759 }
760 let wt = entry.path();
761 if !stale_enough(&wt, grace_secs, now) {
762 continue;
763 }
764 match remove_clean_bay(&wt).await {
765 Ok(()) => folded += 1,
766 Err(e) => tracing::warn!(
767 "housekeep: remove orphaned worktree {}: {e:#}",
768 wt.display()
769 ),
770 }
771 }
772 folded
773}
774
775fn looks_like_a_worktree_bay(name: &str) -> bool {
784 name.len() == 4 && name.bytes().all(|b| b.is_ascii_alphanumeric())
785}
786
787fn stale_enough(dir: &Path, grace_secs: u64, now: Timestamp) -> bool {
806 let Ok(modified) = std::fs::metadata(dir).and_then(|m| m.modified()) else {
807 return false;
808 };
809 let Ok(ts) = Timestamp::try_from(modified) else {
810 return false;
811 };
812 due(now, ts, grace_secs.max(MIN_ORPHAN_AGE_SECS))
813}
814
815const MIN_ORPHAN_AGE_SECS: u64 = 5 * 60;
826
827fn resolve_id_path(runs: &Path, prefix: &str) -> Result<String> {
830 if runs.join(prefix).is_dir() && crate::run::is_run_id(prefix) {
835 return Ok(prefix.to_owned());
836 }
837 let mut hits: Vec<String> = Vec::new();
838 for e in std::fs::read_dir(runs).into_iter().flatten().flatten() {
839 if !e.path().is_dir() {
840 continue;
841 }
842 let id = e.file_name().to_string_lossy().into_owned();
843 if crate::run::is_run_id(&id) && (id.starts_with(prefix) || id.ends_with(prefix)) {
844 hits.push(id);
845 }
846 }
847 match hits.len() {
848 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
849 0 => bail!("no run matches `{prefix}`"),
850 _ => bail!(
851 "`{prefix}` matches {} runs: {}",
852 hits.len(),
853 hits.join(", ")
854 ),
855 }
856}
857
858pub fn clear_abandoned_active(state: &mut RunState, home: &Path, now: Timestamp) -> Result<bool> {
873 if crate::daemon::is_working_on(home, &state.id, now) || !state.active_all_overrun(now) {
874 return Ok(false);
875 }
876 state.abandon("fold");
877 state.save_under(home)?;
878 if let Err(e) = Questions::at(home.join("questions")).settle_run(&state.id, state.status) {
886 tracing::warn!("abandon questions for {}: {e:#}", state.id);
887 }
888 Ok(true)
889}
890
891pub fn prune_cache(home: &Path, cache: &Path, limit_bytes: u64) -> Result<Option<Prune>> {
900 crate::cache::maintenance_prune(home, cache, limit_bytes)
901}
902
903pub fn prune_cache_if_over_limit(
913 cfg: &crate::config::Config,
914 home: &Path,
915) -> Result<Option<Prune>> {
916 if cfg.disk.cache_limit_bytes == 0 {
917 return Ok(None);
918 }
919 let Some(cache) = cfg.cache_dir() else {
920 return Ok(None);
921 };
922 let limit = crate::disk::free_bytes(&cache)
923 .ok()
924 .map_or(cfg.disk.cache_limit_bytes, |free| {
925 crate::disk::pressure_limit(
926 dir_size(&cache),
927 cfg.disk.cache_limit_bytes,
928 cfg.disk.min_free_bytes,
929 free,
930 )
931 });
932 prune_cache(home, &cache, limit)
933}
934
935pub fn cache_report(cfg: &crate::config::Config) -> Option<(PathBuf, u64, u64)> {
941 let cache = cfg.cache_dir()?;
942 Some((
943 cache.clone(),
944 cache_size(&cache),
945 cfg.disk.cache_limit_bytes,
946 ))
947}
948
949pub fn cache_size(cache: &Path) -> u64 {
951 dir_size(cache)
952}
953
954#[cfg(test)]
955mod tests {
956
957 async fn sh(cwd: &Path, args: &[&str]) {
958 let out = crate::git::git_raw(cwd, args).await.expect("spawn git");
959 assert!(out.ok(), "git {args:?}: {}", out.stderr);
960 }
961
962 async fn commit(cwd: &Path, file: &str, body: &str) {
963 std::fs::write(cwd.join(file), body).unwrap();
964 sh(cwd, &["add", file]).await;
965 sh(
966 cwd,
967 &[
968 "-c",
969 "user.name=t",
970 "-c",
971 "user.email=t@example.com",
972 "commit",
973 "-q",
974 "-m",
975 body,
976 ],
977 )
978 .await;
979 }
980
981 const LONG: std::time::Duration = std::time::Duration::from_secs(30);
982
983 #[tokio::test]
984 async fn fetch_advances_origin_main_and_leaves_the_checkout_alone() {
985 let tmp = tempfile::tempdir().unwrap();
986 let t = tmp.path();
987 let bare = t.join("remote.git");
988 sh(
989 t,
990 &["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
991 )
992 .await;
993 let dir = t.join("root/h/o/r");
994 std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
995 sh(
996 t,
997 &["clone", "-q", bare.to_str().unwrap(), dir.to_str().unwrap()],
998 )
999 .await;
1000 sh(&dir, &["checkout", "-q", "-b", "main"]).await;
1001 commit(&dir, "a.txt", "one").await;
1002 sh(&dir, &["push", "-q", "origin", "main"]).await;
1003 sh(&dir, &["checkout", "-q", "--detach"]).await;
1004 std::fs::write(dir.join("a.txt"), "dirty").unwrap();
1005
1006 let other = t.join("other");
1007 sh(
1008 t,
1009 &[
1010 "clone",
1011 "-q",
1012 bare.to_str().unwrap(),
1013 other.to_str().unwrap(),
1014 ],
1015 )
1016 .await;
1017 commit(&other, "b.txt", "two").await;
1018 sh(&other, &["push", "-q", "origin", "HEAD:main"]).await;
1019
1020 let rev = |d: PathBuf, r: &'static str| async move {
1021 crate::git::git(&d, &["rev-parse", r]).await.unwrap()
1022 };
1023 let head = rev(dir.clone(), "HEAD").await;
1024 let before = rev(dir.clone(), "origin/main").await;
1025 let status = crate::git::git(&dir, &["status", "--porcelain"])
1026 .await
1027 .unwrap();
1028
1029 let r = fetch_origins(&[t.join("root")], LONG, || false).await;
1030 assert_eq!(
1031 r,
1032 FetchReport {
1033 fetched: 1,
1034 no_origin: 0,
1035 failed: 0
1036 }
1037 );
1038
1039 assert_ne!(rev(dir.clone(), "origin/main").await, before);
1040 assert_eq!(rev(dir.clone(), "HEAD").await, head);
1041 assert_eq!(
1042 crate::git::git(&dir, &["status", "--porcelain"])
1043 .await
1044 .unwrap(),
1045 status
1046 );
1047 assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "dirty");
1048 }
1049
1050 #[tokio::test]
1051 async fn fetch_never_writes_a_local_branch_whatever_the_configured_refspec() {
1052 let tmp = tempfile::tempdir().unwrap();
1053 let t = tmp.path();
1054 let bare = t.join("remote.git");
1055 sh(
1056 t,
1057 &["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
1058 )
1059 .await;
1060 let dir = t.join("root/h/o/r");
1061 std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
1062 sh(
1063 t,
1064 &["clone", "-q", bare.to_str().unwrap(), dir.to_str().unwrap()],
1065 )
1066 .await;
1067 sh(&dir, &["checkout", "-q", "-b", "main"]).await;
1068 commit(&dir, "a.txt", "one").await;
1069 sh(&dir, &["push", "-q", "origin", "main"]).await;
1070 sh(&dir, &["checkout", "-q", "--detach"]).await;
1071 sh(
1073 &dir,
1074 &[
1075 "config",
1076 "remote.origin.fetch",
1077 "+refs/heads/main:refs/heads/main",
1078 ],
1079 )
1080 .await;
1081 let _ = crate::git::git_raw(&dir, &["update-ref", "-d", "refs/remotes/origin/main"]).await;
1082
1083 let other = t.join("other");
1084 sh(
1085 t,
1086 &[
1087 "clone",
1088 "-q",
1089 bare.to_str().unwrap(),
1090 other.to_str().unwrap(),
1091 ],
1092 )
1093 .await;
1094 commit(&other, "b.txt", "two").await;
1095 sh(&other, &["push", "-q", "origin", "HEAD:main"]).await;
1096 let remote_tip = crate::git::git(&other, &["rev-parse", "HEAD"])
1097 .await
1098 .unwrap();
1099 let local_main = crate::git::git(&dir, &["rev-parse", "refs/heads/main"])
1100 .await
1101 .unwrap();
1102
1103 let r = fetch_origins(&[t.join("root")], LONG, || false).await;
1104 assert_eq!(r.fetched, 1);
1105 assert_eq!(
1106 crate::git::git(&dir, &["rev-parse", "refs/remotes/origin/main"])
1107 .await
1108 .unwrap(),
1109 remote_tip
1110 );
1111 assert_eq!(
1112 crate::git::git(&dir, &["rev-parse", "refs/heads/main"])
1113 .await
1114 .unwrap(),
1115 local_main
1116 );
1117 }
1118
1119 #[tokio::test]
1120 async fn fetch_skips_no_origin_and_survives_an_unreachable_origin() {
1121 let tmp = tempfile::tempdir().unwrap();
1122 let t = tmp.path();
1123 let root = t.join("root");
1124 let bare = t.join("remote.git");
1125 sh(t, &["init", "-q", "--bare", bare.to_str().unwrap()]).await;
1126
1127 let none = root.join("h/o/none");
1128 let dead = root.join("h/o/dead");
1129 let good = root.join("h/o/good");
1130 for d in [&none, &dead, &good] {
1131 std::fs::create_dir_all(d).unwrap();
1132 sh(d, &["init", "-q"]).await;
1133 }
1134 sh(
1135 &dead,
1136 &[
1137 "remote",
1138 "add",
1139 "origin",
1140 t.join("missing").to_str().unwrap(),
1141 ],
1142 )
1143 .await;
1144 sh(&good, &["remote", "add", "origin", bare.to_str().unwrap()]).await;
1145
1146 let r = fetch_origins(&[root], LONG, || false).await;
1147 assert_eq!(
1148 r,
1149 FetchReport {
1150 fetched: 1,
1151 no_origin: 1,
1152 failed: 1
1153 }
1154 );
1155 }
1156 use super::*;
1157 use crate::config::Disk;
1158 use std::fs;
1159
1160 fn ts(s: &str) -> Timestamp {
1161 s.parse().expect("rfc3339")
1162 }
1163
1164 fn block_on<F: std::future::Future>(f: F) -> F::Output {
1165 tokio::runtime::Runtime::new().expect("runtime").block_on(f)
1166 }
1167
1168 #[test]
1169 fn a_run_is_due_after_its_grace_and_not_before() {
1170 let now = ts("2026-09-05T00:00:00Z");
1171 let grace = 600;
1172 let old = now - SignedDuration::new(601, 0);
1173 let fresh = now - SignedDuration::new(599, 0);
1174 assert!(due(now, old, grace));
1175 assert!(!due(now, fresh, grace));
1176 let edge = now - SignedDuration::new(600, 0);
1178 assert!(!due(now, edge, grace));
1179 assert!(due(now, old, 0));
1181 }
1182
1183 #[test]
1184 fn rotate_from_moves_the_starting_point_as_the_cursor_advances() {
1185 let ids: Vec<String> = ["a", "b", "c", "d", "e"]
1186 .iter()
1187 .map(|s| s.to_string())
1188 .collect();
1189
1190 assert_eq!(rotate_from(&ids, 0), ids);
1192
1193 let at_2 = rotate_from(&ids, 2);
1196 assert_eq!(at_2, vec!["c", "d", "e", "a", "b"]);
1197 for id in &ids {
1198 assert!(at_2.contains(id));
1199 }
1200
1201 assert_eq!(rotate_from(&ids, 7), rotate_from(&ids, 2));
1204
1205 assert_eq!(rotate_from(&[], 0), Vec::<String>::new());
1207 }
1208
1209 #[test]
1216 fn advancing_the_cursor_by_the_window_size_gives_every_id_a_turn() {
1217 let ids: Vec<String> = (0..12).map(|n| format!("run-{n}")).collect();
1218 let cap = 5usize;
1219 let mut cursor = 0usize;
1220 let mut ever_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1221 for _ in 0..ids.len() {
1222 let window: Vec<String> = rotate_from(&ids, cursor).into_iter().take(cap).collect();
1223 ever_seen.extend(window.iter().cloned());
1224 cursor = (cursor + window.len()) % ids.len();
1225 }
1226 assert_eq!(
1227 ever_seen.len(),
1228 ids.len(),
1229 "every id must be checked at least once across a full rotation, whatever \
1230 the cadence between passes"
1231 );
1232 }
1233
1234 #[test]
1235 fn the_external_merge_cursor_round_trips_through_a_files_absence() {
1236 let dir = tempfile::tempdir().unwrap();
1237 let home = dir.path();
1238
1239 assert_eq!(read_external_merge_cursor(home), 0);
1241
1242 write_external_merge_cursor(home, 7);
1243 assert_eq!(read_external_merge_cursor(home), 7);
1244
1245 std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), "not a number").unwrap();
1248 assert_eq!(read_external_merge_cursor(home), 0);
1249 }
1250
1251 #[test]
1252 fn a_run_qualifies_for_an_external_merge_check_only_when_blocked_unmerged_and_due() {
1253 let now = ts("2026-09-05T00:00:00Z");
1254 let grace = 600;
1255 let old = now - SignedDuration::new(601, 0);
1256 let fresh = now - SignedDuration::new(599, 0);
1257
1258 assert!(
1259 eligible_for_external_merge_check(RunStatus::Blocked, false, old, now, grace),
1260 "blocked, unmerged, and past its grace period is exactly the run this exists for"
1261 );
1262 assert!(
1263 !eligible_for_external_merge_check(RunStatus::Blocked, false, fresh, now, grace),
1264 "an operator mid-fix deserves the same grace window `fold_due` gives before \
1265 the janitor starts asking GitHub about it"
1266 );
1267 assert!(
1268 !eligible_for_external_merge_check(RunStatus::Blocked, true, old, now, grace),
1269 "a run `land::land` already recorded a merge outcome for has its own answer \
1270 already; this check is only for a run with nothing recorded at all"
1271 );
1272 assert!(
1273 !eligible_for_external_merge_check(RunStatus::Stalled, false, old, now, grace),
1274 "stalled is not blocked - it means the tally never reached quorum, which a \
1275 pull request cannot fix"
1276 );
1277 assert!(
1278 !eligible_for_external_merge_check(RunStatus::Ready, false, old, now, grace),
1279 "ready has nothing to correct - it was never landed by design"
1280 );
1281 assert!(
1282 !eligible_for_external_merge_check(RunStatus::Superseded, false, old, now, grace),
1283 "a superseded run's task already has its answer from a later attempt; \
1284 there is nothing left for GitHub to confirm here"
1285 );
1286 }
1287
1288 fn write_blocked_run(runs: &Path, id: &str, updated_at: Timestamp) {
1291 use crate::run::{Candidate, Tally};
1292 use std::collections::BTreeMap;
1293
1294 let mut state = RunState::new(
1295 runs.parent().unwrap().to_path_buf(),
1296 "main".to_owned(),
1297 "0000000000000000000000000000000000000000".to_owned(),
1298 String::new(),
1299 crate::config::Config::default(),
1300 );
1301 state.id = id.to_owned();
1302 state.status = RunStatus::Blocked;
1303 state.updated_at = updated_at;
1304 state.candidates.push(Candidate {
1305 index: 0,
1306 label: 'A',
1307 agent: "agent".to_owned(),
1308 branch: format!("magi/{id}/A"),
1309 worktree: runs.parent().unwrap().join("candidate"),
1310 summary: String::new(),
1311 stat: String::new(),
1312 files: 0,
1313 commits: 0,
1314 empty: false,
1315 failed: None,
1316 verified_noop: None,
1317 duration_ms: 0,
1318 folded: false,
1319 });
1320 state.tally = Some(Tally {
1321 first_choice: BTreeMap::from([('A', 1)]),
1322 borda: BTreeMap::new(),
1323 winner: 'A',
1324 rankings: 1,
1325 unanimous_initial: true,
1326 deliberated: false,
1327 changed_votes: 0,
1328 unanimous_final: true,
1329 tie_break: None,
1330 judges: 1,
1331 present: 1,
1332 quorum: 1,
1333 met_quorum: true,
1334 uncontested: None,
1335 });
1336 std::fs::create_dir_all(runs.join(id)).unwrap();
1337 std::fs::write(
1338 runs.join(id).join("run.json"),
1339 serde_json::to_string_pretty(&state).unwrap(),
1340 )
1341 .unwrap();
1342 }
1343
1344 #[tokio::test]
1349 async fn reconcile_external_merges_leaves_ineligible_and_unconfirmable_runs_alone() {
1350 let dir = tempfile::tempdir().unwrap();
1351 let runs = dir.path().join("runs");
1352 let home = dir.path().to_path_buf();
1353 std::fs::create_dir_all(&runs).unwrap();
1354
1355 let now = ts("2026-09-05T00:00:00Z");
1356 let disk = Disk {
1357 fold_grace_secs: 600,
1358 ..Disk::default()
1359 };
1360
1361 let due_id = "20260905-000000-blkd";
1362 write_blocked_run(&runs, due_id, ts("2026-08-01T00:00:00Z"));
1363
1364 let fresh_id = "20260905-000000-fres";
1365 write_blocked_run(&runs, fresh_id, now);
1366
1367 let live_id = "20260905-000000-live";
1368 write_blocked_run(&runs, live_id, ts("2026-08-01T00:00:00Z"));
1369 let mut status = crate::daemon::Status::new();
1370 status.current = vec![crate::daemon::Current {
1371 worker: None,
1372 task: "20260905-000000-task".to_owned(),
1373 run: live_id.to_owned(),
1374 }];
1375 status.updated_at = now;
1376 crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
1377
1378 let reconciled = reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
1379 anyhow::bail!("injected forge authentication failure")
1380 })
1381 .await;
1382 assert_eq!(reconciled, 0, "a forge failure can never confirm a merge");
1383 for id in [due_id, fresh_id, live_id] {
1384 assert_eq!(
1385 read_meta(&runs, id).unwrap().status,
1386 RunStatus::Blocked,
1387 "{id} must be left exactly as it was found"
1388 );
1389 }
1390 let notices = crate::notices::Notices::at(home.join("notifications")).list();
1391 let due_notice = notices
1392 .iter()
1393 .find(|n| n.key == format!("merged-unrecorded:{due_id}"))
1394 .expect("notice for due_id must be raised");
1395 assert_eq!(
1396 due_notice.link,
1397 Some(crate::notices::Link::Run {
1398 id: due_id.to_owned(),
1399 })
1400 );
1401 }
1402
1403 #[tokio::test]
1404 async fn historical_external_merge_check_preserves_unknown_history() {
1405 let home = tempfile::tempdir().unwrap();
1406 let runs = home.path().join("runs");
1407 let id = "legacy";
1408 write_blocked_run(&runs, id, ts("2026-08-01T00:00:00Z"));
1409 let path = runs.join(id).join("run.json");
1410 let mut state = read_state(&runs, id).unwrap();
1411 state.repo = home.path().join("removed");
1412 state.candidates[0].folded = true;
1413 let original = serde_json::to_vec(&state).unwrap();
1414 std::fs::write(&path, &original).unwrap();
1415 let count = reconcile_external_merges_with(
1416 &runs,
1417 home.path(),
1418 &Disk::default(),
1419 ts("2026-11-14T00:00:00Z"),
1420 |_| async { panic!("historical unavailable checkout must not invoke the forge") },
1421 )
1422 .await;
1423 assert_eq!(count, 0);
1424 assert_eq!(std::fs::read(&path).unwrap(), original);
1425 assert!(
1426 crate::notices::Notices::at(home.path().join("notifications"))
1427 .all()
1428 .is_empty()
1429 );
1430
1431 let queue = crate::queue::Queue::at(home.path().join("queue"));
1433 let mut task = crate::queue::Task::new(
1434 "current".into(),
1435 "current".into(),
1436 state.repo.clone(),
1437 crate::queue::Source::Human,
1438 );
1439 task.runs.push(id.into());
1440 queue.put(&mut task).unwrap();
1441 reconcile_external_merges_with(
1442 &runs,
1443 home.path(),
1444 &Disk::default(),
1445 ts("2026-11-14T00:00:00Z"),
1446 |_| async { anyhow::bail!("current checkout unavailable") },
1447 )
1448 .await;
1449 assert_eq!(
1450 crate::notices::Notices::at(home.path().join("notifications"))
1451 .list()
1452 .len(),
1453 1
1454 );
1455 assert_eq!(std::fs::read(&path).unwrap(), original);
1456 }
1457
1458 #[tokio::test]
1468 async fn reconcile_external_merges_covers_a_larger_fleet_across_repeated_passes_at_one_instant()
1469 {
1470 let dir = tempfile::tempdir().unwrap();
1471 let runs = dir.path().join("runs");
1472 let home = dir.path().to_path_buf();
1473 std::fs::create_dir_all(&runs).unwrap();
1474
1475 let now = ts("2026-09-05T00:00:00Z");
1476 let disk = Disk {
1477 fold_grace_secs: 600,
1478 ..Disk::default()
1479 };
1480 let old = ts("2026-08-01T00:00:00Z");
1481
1482 let ids: Vec<String> = (0..8).map(|n| format!("20260905-000000-r{n:03}")).collect();
1483 for id in &ids {
1484 write_blocked_run(&runs, id, old);
1485 }
1486
1487 let notices = crate::notices::Notices::at(home.join("notifications"));
1488
1489 reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
1495 anyhow::bail!("injected forge authentication failure")
1496 })
1497 .await;
1498 let after_first = notices.list().len();
1499 assert_eq!(
1500 after_first, MAX_EXTERNAL_MERGE_CHECKS_PER_PASS,
1501 "the first pass checks exactly one cap's worth"
1502 );
1503
1504 reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
1505 anyhow::bail!("injected forge authentication failure")
1506 })
1507 .await;
1508 let after_second = notices.list().len();
1509 assert_eq!(
1510 after_second,
1511 ids.len(),
1512 "a second pass at the same instant must still reach every id the \
1513 first pass had no room for, not repeat the same cap's worth"
1514 );
1515 }
1516
1517 #[test]
1518 fn the_meta_reader_is_tolerant_of_everything_except_the_deciders() {
1519 let dir = tempfile::tempdir().unwrap();
1520 let runs = dir.path().join("runs");
1521 let id = "20260905-000000-abcd";
1522 std::fs::create_dir_all(runs.join(id)).unwrap();
1523 std::fs::write(
1524 runs.join(id).join("run.json"),
1525 r#"{"schema": 99, "id": "20260905-000000-abcd", "updated_at": "2026-09-05T00:00:00Z", "status": "ready", "junk_from_another_build": [1, 2, 3]}"#,
1526 )
1527 .unwrap();
1528 let meta = read_meta(&runs, id).expect("readable");
1529 assert_eq!(meta.status, RunStatus::Ready);
1530 assert_eq!(meta.updated_at, ts("2026-09-05T00:00:00Z"));
1531 assert!(read_meta(&runs, "nope").is_err(), "missing file unreadable");
1532 std::fs::write(runs.join(id).join("run.json"), "not json at all").unwrap();
1533 assert!(read_meta(&runs, id).is_err(), "garbage unreadable");
1534 }
1535
1536 #[test]
1537 fn fold_unreadable_preserves_unknown_content_and_recovery_artifacts() {
1538 let dir = tempfile::tempdir().unwrap();
1539 let runs = dir.path().join("runs");
1540 let wt = dir.path().join("wt");
1541 let id = "20260905-000000-abcd";
1542 std::fs::create_dir_all(runs.join(id).join("artifacts")).unwrap();
1543 std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
1544 std::fs::create_dir_all(wt.join("abcd")).unwrap();
1545 std::fs::write(wt.join("abcd/leftover"), "owned edits").unwrap();
1546 assert!(block_on(fold_unreadable(&runs, &wt, id)).is_err());
1547 assert!(runs.join(id).join("artifacts").exists());
1548 assert_eq!(
1549 std::fs::read_to_string(wt.join("abcd/leftover")).unwrap(),
1550 "owned edits"
1551 );
1552 }
1553
1554 #[test]
1555 fn fold_unreadable_releases_run_dir_and_worktrees() {
1556 let dir = tempfile::tempdir().unwrap();
1557 let runs = dir.path().join("runs");
1558 let wt = dir.path().join("wt");
1559 let id = "20260905-000000-abcd";
1560 std::fs::create_dir_all(runs.join(id)).unwrap();
1561 std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
1562 std::fs::create_dir_all(wt.join("abcd")).unwrap();
1563
1564 let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold");
1565 assert_eq!(removed.len(), 2);
1566 assert!(!runs.join(id).exists(), "run dir gone");
1567 assert!(!wt.join("abcd").exists(), "worktrees gone");
1568
1569 std::fs::create_dir_all(runs.join(id)).unwrap();
1571 std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
1572 std::fs::create_dir_all(wt.join("abcd")).unwrap();
1573 let removed = block_on(fold_unreadable(&runs, &wt, "20260905")).expect("by prefix");
1574 assert_eq!(removed.len(), 2);
1575 assert!(
1579 block_on(fold_unreadable(&runs, &wt, id)).is_err(),
1580 "a run already gone cannot be resolved again"
1581 );
1582 }
1583
1584 #[test]
1585 fn prune_cache_sheds_the_oldest_generation_until_it_fits() {
1586 let home = tempfile::tempdir().unwrap();
1587 let dir = tempfile::tempdir().unwrap();
1588 fs::write(dir.path().join("old"), b"xx").unwrap();
1591 fs::write(dir.path().join("new"), b"yy").unwrap();
1592 touch(&dir.path().join("old"), 1_000_000);
1593 touch(&dir.path().join("new"), 2_000_000);
1594
1595 let out = prune_cache(home.path(), dir.path(), 2)
1596 .expect("prune")
1597 .expect("the cache is free");
1598 assert_eq!(out.files, 1, "one deletion is enough to reach the cap");
1599 assert_eq!(out.remaining, 2);
1600 assert!(!dir.path().join("old").exists(), "the older file went");
1601 assert!(dir.path().join("new").exists(), "the newer one stayed");
1602
1603 let tied = tempfile::tempdir().unwrap();
1608 fs::write(tied.path().join("big"), b"xxxx").unwrap();
1609 fs::write(tied.path().join("small"), b"yy").unwrap();
1610 touch(&tied.path().join("big"), 1_000_000);
1611 touch(&tied.path().join("small"), 1_000_000);
1612 let out = prune_cache(home.path(), tied.path(), 2)
1613 .expect("prune")
1614 .expect("the cache is free");
1615 assert_eq!(out.files, 1, "the big one alone gets under the cap");
1616 assert_eq!(out.remaining, 2);
1617 assert!(tied.path().join("small").exists());
1618 }
1619
1620 #[test]
1621 fn prune_cache_if_over_limit_resolves_the_opt_outs_before_ever_measuring() {
1622 let home = tempfile::tempdir().unwrap();
1623 let dir = tempfile::tempdir().unwrap();
1624 fs::write(dir.path().join("big"), vec![0u8; 10]).unwrap();
1625
1626 let mut cfg = crate::config::Config::default();
1627 cfg.verify.gate = vec![format!(
1628 "CARGO_TARGET_DIR={} cargo make check",
1629 dir.path().display()
1630 )];
1631
1632 cfg.disk.cache_limit_bytes = 0;
1635 assert_eq!(
1636 prune_cache_if_over_limit(&cfg, home.path()).unwrap(),
1637 None,
1638 "a zero cap must not even look at the directory"
1639 );
1640 assert!(dir.path().join("big").exists());
1641
1642 let mut no_cache = crate::config::Config::default();
1645 no_cache.disk.cache_limit_bytes = 1;
1646 assert_eq!(
1647 prune_cache_if_over_limit(&no_cache, home.path()).unwrap(),
1648 None
1649 );
1650
1651 cfg.disk.cache_limit_bytes = 1;
1654 let pruned = prune_cache_if_over_limit(&cfg, home.path())
1655 .unwrap()
1656 .expect("a real cache dir over its cap prunes");
1657 assert_eq!(pruned.files, 1);
1658 assert!(!dir.path().join("big").exists());
1659 }
1660
1661 fn touch(path: &Path, secs: u64) {
1664 let f = fs::File::options().write(true).open(path).unwrap();
1665 f.set_times(fs::FileTimes::new().set_modified(
1666 std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs),
1667 ))
1668 .unwrap();
1669 }
1670
1671 #[test]
1674 fn fold_unreadable_clears_a_run_whose_state_never_landed() {
1675 let dir = tempfile::tempdir().unwrap();
1676 let runs = dir.path().join("runs");
1677 let wt = dir.path().join("wt");
1678 let id = "20260904-014540-88c0";
1679 std::fs::create_dir_all(runs.join(id)).unwrap();
1680 std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
1681
1682 let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold by id");
1683 assert_eq!(removed, vec![format!("runs/{id}")]);
1684 assert!(!runs.join(id).exists(), "record gone");
1685
1686 std::fs::create_dir_all(runs.join(id)).unwrap();
1688 std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
1689 assert!(
1690 block_on(fold_unreadable(&runs, &wt, "88c0")).is_ok(),
1691 "by prefix"
1692 );
1693
1694 std::fs::create_dir_all(runs.join("scratch")).unwrap();
1696 assert!(
1697 block_on(fold_unreadable(&runs, &wt, "scratch")).is_err(),
1698 "a stray directory is not a run"
1699 );
1700 }
1701
1702 #[test]
1703 fn fold_due_folds_terminal_runs_of_any_schema_but_leaves_genuinely_unreadable_ones() {
1704 let dir = tempfile::tempdir().unwrap();
1705 let runs = dir.path().join("runs");
1706 let wt = dir.path().join("wt");
1707 let home = dir.path().to_path_buf();
1708 let disk = Disk::default();
1709 let now = ts("2026-09-05T00:00:00Z");
1710
1711 let judging = "20260801-000000-0001";
1713 write_meta(&runs, judging, "judging", "2026-08-01T00:00:00Z");
1714
1715 let ready_fresh = "20260904-220000-0002";
1722 write_meta(&runs, ready_fresh, "ready", "2026-09-04T22:00:00Z");
1723
1724 let garbage = "20260901-000000-0004";
1730 std::fs::create_dir_all(runs.join(garbage)).unwrap();
1731 std::fs::write(runs.join(garbage).join("run.json"), "not json").unwrap();
1732 std::fs::create_dir_all(wt.join("0004")).unwrap();
1733
1734 let due_ready = due_run(&runs, &wt, "20260801-000000-ffff", SCHEMA);
1737
1738 let due_old_schema = due_run(&runs, &wt, "20260801-000000-eeee", SCHEMA - 1);
1743
1744 let (folded, unreadable) =
1745 block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
1746 assert_eq!(
1747 folded, 2,
1748 "both due, parseable runs fold regardless of their schema number"
1749 );
1750 assert_eq!(
1751 unreadable, 1,
1752 "only the run with broken JSON counts as unreadable"
1753 );
1754 assert!(runs.join(judging).exists(), "runnable never folded");
1755 assert!(runs.join(ready_fresh).exists(), "fresh never folded");
1756 assert!(runs.join(garbage).exists(), "unreadable record kept");
1757 assert!(wt.join("0004").exists(), "unreadable worktree kept");
1758 assert!(
1759 runs.join(&due_ready).exists(),
1760 "folding drops worktrees, not the record"
1761 );
1762 assert!(
1763 runs.join(&due_old_schema).exists(),
1764 "an old-schema record survives its fold exactly like a current one"
1765 );
1766 for id in [&due_ready, &due_old_schema] {
1772 let saved = read_meta(&runs, id).expect("folded run still parses");
1773 assert_ne!(
1774 saved.updated_at,
1775 ts("2026-08-01T00:00:00Z"),
1776 "fold_run must have saved the updated state back through the \
1777 `runs` directory this test passed to fold_due"
1778 );
1779 }
1780 }
1781
1782 #[tokio::test]
1788 async fn housekeep_leaves_everything_alone_when_auto_fold_is_disabled() {
1789 let dir = tempfile::tempdir().unwrap();
1790 let runs = dir.path().join("runs");
1791 let wt = dir.path().join("wt");
1792 let home = dir.path().to_path_buf();
1793 crate::run::set_home(dir.path().to_path_buf());
1794
1795 let due_id = due_run(&runs, &wt, "20260801-000000-abcd", SCHEMA);
1796 std::fs::create_dir_all(wt.join("orphan").join("cand-A")).unwrap();
1797
1798 let mut cfg = crate::config::Config::default();
1799 cfg.disk.auto_fold = false;
1800 cfg.disk.cache_limit_bytes = 0;
1801
1802 let out = housekeep(&cfg, &home, &wt, &dir.path().join("repo"), Timestamp::now()).await;
1803
1804 assert_eq!(out.folded, 0);
1805 assert_eq!(out.unreadable, 0);
1806 assert_eq!(out.orphaned_worktrees, 0);
1807 assert!(
1808 runs.join(&due_id).exists(),
1809 "a due run's record survives untouched"
1810 );
1811 assert!(
1812 wt.join("orphan").exists(),
1813 "an orphaned worktree survives untouched: the reclaim pass never ran"
1814 );
1815 }
1816
1817 #[test]
1818 fn fold_orphaned_worktrees_removes_only_worktrees_no_run_claims_and_none_in_flight() {
1819 let dir = tempfile::tempdir().unwrap();
1820 let runs = dir.path().join("runs");
1821 let wt = dir.path().join("wt");
1822 let home = dir.path().to_path_buf();
1823
1824 write_meta(
1827 &runs,
1828 "20260801-000000-aaaa",
1829 "ready",
1830 "2026-08-01T00:00:00Z",
1831 );
1832 std::fs::create_dir_all(wt.join("aaaa").join("cand-A")).unwrap();
1833
1834 std::fs::create_dir_all(wt.join("bbbb").join("cand-A")).unwrap();
1838
1839 std::fs::create_dir_all(wt.join("cccc")).unwrap();
1844
1845 std::fs::create_dir_all(wt.join("scratch")).unwrap();
1849
1850 let now = Timestamp::now() + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
1856 let mut status = crate::daemon::Status::new();
1857 status.current = vec![crate::daemon::Current {
1858 worker: None,
1859 task: "20260905-000000-t111".to_owned(),
1860 run: "20260905-000000-cccc".to_owned(),
1861 }];
1862 status.updated_at = now;
1863 crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
1864
1865 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
1866 assert_eq!(
1867 folded, 1,
1868 "only the truly orphaned, idle, bay-shaped worktree is removed"
1869 );
1870 assert!(wt.join("aaaa").exists(), "claimed by a run record");
1871 assert!(!wt.join("bbbb").exists(), "orphaned and idle: reclaimed");
1872 assert!(wt.join("cccc").exists(), "a run in flight is never touched");
1873 assert!(
1874 wt.join("scratch").exists(),
1875 "not shaped like a worktree bay, so never a reclaim target"
1876 );
1877 }
1878
1879 #[test]
1887 fn fold_orphaned_worktrees_leaves_a_freshly_created_bay_alone() {
1888 let dir = tempfile::tempdir().unwrap();
1889 let runs = dir.path().join("runs");
1890 let wt = dir.path().join("wt");
1891 let home = dir.path().to_path_buf();
1892
1893 std::fs::create_dir_all(wt.join("dddd").join("under-review")).unwrap();
1894
1895 let now = Timestamp::now();
1896 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 6 * 60 * 60, now));
1897 assert_eq!(
1898 folded, 0,
1899 "too fresh to tell apart from a run still being set up"
1900 );
1901 assert!(wt.join("dddd").exists());
1902 }
1903
1904 fn open_question(store: &Questions, run: &str) -> crate::ask::Question {
1906 let mut q = crate::ask::Question::new(
1907 run.to_owned(),
1908 "implement".to_owned(),
1909 "impl-A".to_owned(),
1910 "Which storage backend should the cache use?".to_owned(),
1911 String::new(),
1912 vec!["SQLite".to_owned(), "Redis".to_owned()],
1913 );
1914 store.put(&mut q).unwrap();
1915 q
1916 }
1917
1918 #[test]
1924 fn a_finished_runs_open_question_is_swept_up() {
1925 let dir = tempfile::tempdir().unwrap();
1926 let runs = dir.path().join("runs");
1927 let store = Questions::at(dir.path().join("questions"));
1928
1929 let failed = "20260908-205802-c9eb";
1930 write_meta(&runs, failed, "failed", "2026-09-08T20:58:02Z");
1931 let failed_q = open_question(&store, failed);
1932
1933 let merged = "20260908-205501-ca67";
1934 write_meta(&runs, merged, "merged", "2026-09-08T20:55:01Z");
1935 let merged_q = open_question(&store, merged);
1936
1937 let n = abandon_settled_questions(&store, &runs);
1938 assert_eq!(n, 2, "both dead runs' questions are swept in one pass");
1939
1940 for (id, run) in [(&failed_q.id, failed), (&merged_q.id, merged)] {
1941 let back = store.get(id).unwrap();
1942 assert!(!back.status.open(), "{run} is done; nobody reads an answer");
1943 assert!(back.detail.contains(run), "{}", back.detail);
1944 }
1945 }
1946
1947 #[test]
1948 fn a_still_alive_runs_open_question_survives_the_sweep() {
1949 let dir = tempfile::tempdir().unwrap();
1950 let runs = dir.path().join("runs");
1951 let store = Questions::at(dir.path().join("questions"));
1952
1953 for (id, status) in [
1957 ("20260908-000000-b10c", "blocked"),
1958 ("20260908-000000-5ta1", "stalled"),
1959 ("20260908-000000-jud6", "judging"),
1960 ] {
1961 write_meta(&runs, id, status, "2026-09-08T00:00:00Z");
1962 let q = open_question(&store, id);
1963
1964 let n = abandon_settled_questions(&store, &runs);
1965 assert_eq!(n, 0, "{status} run is not done; nothing to sweep");
1966 assert!(
1967 store.get(&q.id).unwrap().status.open(),
1968 "{status} run's question must still be waiting"
1969 );
1970 }
1971 }
1972
1973 #[test]
1974 fn the_sweep_leaves_an_answered_question_and_an_unreadable_run_alone() {
1975 let dir = tempfile::tempdir().unwrap();
1976 let runs = dir.path().join("runs");
1977 let store = Questions::at(dir.path().join("questions"));
1978
1979 let done = "20260908-000000-answ";
1982 write_meta(&runs, done, "failed", "2026-09-08T00:00:00Z");
1983 let mut answered = open_question(&store, done);
1984 answered
1985 .answer(crate::ask::Answer::Choice("SQLite".to_owned()))
1986 .unwrap();
1987 store.put(&mut answered).unwrap();
1988
1989 let gone = "20260908-000000-gone";
1991 let orphan = open_question(&store, gone);
1992
1993 assert_eq!(abandon_settled_questions(&store, &runs), 0);
1994 assert_eq!(
1995 store.get(&answered.id).unwrap().status,
1996 crate::ask::QuestionStatus::Answered,
1997 "a real answer is never overwritten by a sweep"
1998 );
1999 assert!(
2000 store.get(&orphan.id).unwrap().status.open(),
2001 "a run this sweep cannot read is left exactly as it was, not guessed at"
2002 );
2003 }
2004
2005 #[test]
2014 fn fold_orphaned_worktrees_floors_a_zero_grace_at_the_race_safe_minimum() {
2015 let dir = tempfile::tempdir().unwrap();
2016 let runs = dir.path().join("runs");
2017 let wt = dir.path().join("wt");
2018 let home = dir.path().to_path_buf();
2019
2020 std::fs::create_dir_all(wt.join("eeee").join("under-review")).unwrap();
2021
2022 let now = Timestamp::now();
2024 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
2025 assert_eq!(
2026 folded, 0,
2027 "a zero grace must not defeat the race-safety floor"
2028 );
2029 assert!(wt.join("eeee").exists());
2030
2031 let later = now + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
2034 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, later));
2035 assert_eq!(folded, 1, "old enough now, regardless of the zero grace");
2036 assert!(!wt.join("eeee").exists());
2037 }
2038
2039 #[test]
2040 fn clear_abandoned_active_only_acts_once_dead_and_overrun() {
2041 let dir = tempfile::tempdir().unwrap();
2042 crate::run::set_home(dir.path().to_path_buf());
2047 let home = dir.path().to_path_buf();
2048 let now = ts("2026-09-14T12:00:00Z");
2049 let overrun_seat = || crate::run::ActiveSeat {
2050 node: "implement".to_owned(),
2051 started_at: now - SignedDuration::new(21_000, 0),
2052 timeout_secs: 3_600,
2053 attempt: 0,
2054 task: None,
2055 command: None,
2056 index: None,
2057 total: None,
2058 };
2059
2060 let mut state = RunState::new(
2061 PathBuf::from("/repo"),
2062 "main".to_owned(),
2063 "abc1234".to_owned(),
2064 "fixture".to_owned(),
2065 crate::config::Config::default(),
2066 );
2067 state.status = RunStatus::Implementing;
2068 state.active.insert("impl-A".to_owned(), overrun_seat());
2069
2070 let mut fresh = state.clone();
2073 fresh.active.insert(
2074 "impl-B".to_owned(),
2075 crate::run::ActiveSeat {
2076 node: "implement".to_owned(),
2077 started_at: now,
2078 timeout_secs: 3_600,
2079 attempt: 0,
2080 task: None,
2081 command: None,
2082 index: None,
2083 total: None,
2084 },
2085 );
2086 assert!(!clear_abandoned_active(&mut fresh, &home, now).unwrap());
2087 assert!(!fresh.active.is_empty());
2088 assert_eq!(fresh.status, RunStatus::Implementing);
2089
2090 let store = Questions::at(home.join("questions"));
2091 let q = open_question(&store, &state.id);
2092
2093 assert!(clear_abandoned_active(&mut state, &home, now).unwrap());
2094 assert!(state.active.is_empty());
2095 assert_eq!(state.status, RunStatus::Failed);
2096 assert!(
2097 !store.get(&q.id).unwrap().status.open(),
2098 "the abandoned seat's own open question must not keep badging the \
2099 operator until some later daemon startup notices it"
2100 );
2101 }
2102
2103 fn write_meta(runs: &Path, id: &str, status: &str, updated_at: &str) {
2105 let day = &updated_at[..10];
2106 std::fs::create_dir_all(runs.join(id)).unwrap();
2107 let body = format!(
2108 r#"{{"schema": {SCHEMA}, "id": "{id}", "repo": "/nonexistent/repo", "base_branch": "main", "base_commit": "0000000000000000000000000000000000000000", "instruction": "", "created_at": "{day}T00:00:00Z", "updated_at": "{updated_at}", "status": "{status}", "seed": 1}}"#
2109 );
2110 std::fs::write(runs.join(id).join("run.json"), body).unwrap();
2111 }
2112
2113 fn due_run(runs: &Path, wt: &Path, id: &str, schema: u32) -> String {
2123 due_run_with_status(runs, wt, id, schema, RunStatus::Ready)
2124 }
2125
2126 fn due_run_with_status(
2129 runs: &Path,
2130 wt: &Path,
2131 id: &str,
2132 schema: u32,
2133 status: RunStatus,
2134 ) -> String {
2135 let mut config = crate::config::Config::default();
2136 config.graph.worktree_root = Some(wt.to_path_buf());
2137 let mut state = RunState::new(
2138 PathBuf::from("/nonexistent/repo"),
2139 "main".to_owned(),
2140 "0000000000000000000000000000000000000000".to_owned(),
2141 String::new(),
2142 config,
2143 );
2144 state.id = id.to_owned();
2145 state.status = status;
2146 state.updated_at = ts("2026-08-01T00:00:00Z");
2147 let mut value = serde_json::to_value(&state).unwrap();
2148 value["schema"] = serde_json::json!(schema);
2149 std::fs::create_dir_all(runs.join(id)).unwrap();
2150 std::fs::write(
2151 runs.join(id).join("run.json"),
2152 serde_json::to_string_pretty(&value).unwrap(),
2153 )
2154 .unwrap();
2155 id.to_owned()
2156 }
2157
2158 #[test]
2159 fn fold_due_folds_a_superseded_run_same_as_any_other_terminal_one() {
2160 let dir = tempfile::tempdir().unwrap();
2161 let runs = dir.path().join("runs");
2162 let wt = dir.path().join("wt");
2163 let home = dir.path().to_path_buf();
2164 let disk = Disk::default();
2165 let now = ts("2026-09-05T00:00:00Z");
2166
2167 let superseded = due_run_with_status(
2168 &runs,
2169 &wt,
2170 "20260801-000000-cccc",
2171 SCHEMA,
2172 RunStatus::Superseded,
2173 );
2174
2175 let (folded, unreadable) =
2176 block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
2177 assert_eq!(
2178 folded, 1,
2179 "a superseded run has nothing left for a human to check, so it folds \
2180 exactly like a merged one"
2181 );
2182 assert_eq!(unreadable, 0);
2183 assert!(
2184 read_meta(&runs, &superseded).is_ok(),
2185 "folding drops the worktree, not the record"
2186 );
2187 }
2188
2189 fn init_repo(dir: &Path) {
2192 use crate::proc::Quiet as _;
2193 let run = |args: &[&str]| {
2194 let out = std::process::Command::new("git")
2195 .args(args)
2196 .current_dir(dir)
2197 .quiet()
2198 .output()
2199 .expect("spawn git");
2200 assert!(
2201 out.status.success(),
2202 "git {args:?} failed: {}",
2203 String::from_utf8_lossy(&out.stderr)
2204 );
2205 };
2206 run(&["init", "-b", "main"]);
2207 run(&["config", "user.name", "magi test"]);
2208 run(&["config", "user.email", "magi@example.com"]);
2209 std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
2210 run(&["add", "-A"]);
2211 run(&["commit", "-m", "init"]);
2212 }
2213
2214 async fn due_run_with_winner_worktree(
2218 runs: &Path,
2219 wt: &Path,
2220 repo: &Path,
2221 id: &str,
2222 status: RunStatus,
2223 ) -> (String, PathBuf) {
2224 use crate::run::{Candidate, Tally};
2225 use std::collections::BTreeMap;
2226
2227 let mut config = crate::config::Config::default();
2228 config.graph.worktree_root = Some(wt.to_path_buf());
2229 let mut state = RunState::new(
2230 repo.to_path_buf(),
2231 "main".to_owned(),
2232 "0000000000000000000000000000000000000000".to_owned(),
2233 String::new(),
2234 config,
2235 );
2236 state.id = id.to_owned();
2237 state.status = status;
2238 state.updated_at = ts("2026-08-01T00:00:00Z");
2239
2240 let winner_wt = state.worktree_root().join("cand-A");
2241 crate::git::worktree_add_branch(repo, &winner_wt, &format!("magi/{id}/A"), "main")
2242 .await
2243 .expect("winner worktree");
2244
2245 state.candidates.push(Candidate {
2246 index: 0,
2247 label: 'A',
2248 agent: "agent".to_owned(),
2249 branch: format!("magi/{id}/A"),
2250 worktree: winner_wt.clone(),
2251 summary: String::new(),
2252 stat: String::new(),
2253 files: 0,
2254 commits: 0,
2255 empty: false,
2256 failed: None,
2257 verified_noop: None,
2258 duration_ms: 0,
2259 folded: false,
2260 });
2261 state.tally = Some(Tally {
2262 first_choice: BTreeMap::from([('A', 1)]),
2263 borda: BTreeMap::new(),
2264 winner: 'A',
2265 rankings: 1,
2266 unanimous_initial: true,
2267 deliberated: false,
2268 changed_votes: 0,
2269 unanimous_final: true,
2270 tie_break: None,
2271 judges: 1,
2272 present: 1,
2273 quorum: 1,
2274 met_quorum: true,
2275 uncontested: None,
2276 });
2277 std::fs::create_dir_all(runs.join(id)).unwrap();
2278 std::fs::write(
2279 runs.join(id).join("run.json"),
2280 serde_json::to_string_pretty(&state).unwrap(),
2281 )
2282 .unwrap();
2283 (id.to_owned(), winner_wt)
2284 }
2285
2286 #[tokio::test]
2287 async fn completed_task_retains_independent_historical_sources_without_a_merge_proof() {
2288 let dir = tempfile::tempdir().unwrap();
2289 let home = dir.path();
2290 let runs = home.join("runs");
2291 let wt = home.join("wt");
2292 let repo = home.join("repo");
2293 std::fs::create_dir_all(&repo).unwrap();
2294 init_repo(&repo);
2295 let queue = crate::queue::Queue::at(home.join("queue"));
2296 let mut task = crate::queue::Task::new(
2297 "completed".into(),
2298 "retain independent historical changes".into(),
2299 repo.clone(),
2300 crate::queue::Source::Human,
2301 );
2302 let mut sources = Vec::new();
2303 for (id, status) in [
2304 ("20260801-000000-old1", RunStatus::Superseded),
2305 ("20260801-000000-old2", RunStatus::Failed),
2306 ] {
2307 let (id, worktree) = due_run_with_winner_worktree(&runs, &wt, &repo, id, status).await;
2308 std::fs::write(worktree.join("independent.txt"), &id).unwrap();
2309 crate::git::git(&worktree, &["add", "independent.txt"])
2310 .await
2311 .unwrap();
2312 crate::git::git(
2313 &worktree,
2314 &["commit", "-m", "Independent historical change"],
2315 )
2316 .await
2317 .unwrap();
2318 let head = crate::git::rev_parse(&worktree, "HEAD").await.unwrap();
2319 let mut state = RunState::load_under(&id, home).unwrap();
2320 state.driver_exited = true;
2321 if status == RunStatus::Failed {
2322 state.tally = None;
2323 }
2324 state.save_under(home).unwrap();
2325 task.link_run(&id);
2326 sources.push((id, worktree, head));
2327 }
2328 let mut latest = RunState::new(
2331 repo.clone(),
2332 "main".into(),
2333 crate::git::rev_parse(&repo, "main").await.unwrap(),
2334 task.instruction.clone(),
2335 crate::config::Config::default(),
2336 );
2337 latest.status = RunStatus::Ready;
2338 latest.driver_exited = true;
2339 latest.save_under(home).unwrap();
2340 task.start(latest.id.clone());
2341 task.succeed();
2342 queue.put(&mut task).unwrap();
2343
2344 let (folded, unreadable) = fold_due(
2345 &runs,
2346 home,
2347 &wt,
2348 &Disk::default(),
2349 ts("2026-09-05T00:00:00Z"),
2350 )
2351 .await
2352 .unwrap();
2353 assert_eq!((folded, unreadable), (0, 0));
2354 for (id, worktree, head) in sources {
2355 assert!(worktree.exists());
2356 assert_eq!(
2357 crate::git::rev_parse(&worktree, "HEAD").await.unwrap(),
2358 head
2359 );
2360 let mut state = RunState::load_under(&id, home).unwrap();
2361 assert!(!state.candidates[0].folded);
2362 let error = crate::graph::fold_run(&mut state, true, home)
2363 .await
2364 .unwrap_err();
2365 assert!(
2366 error
2367 .to_string()
2368 .contains(&format!("source of task {}", task.id))
2369 );
2370 assert_eq!(
2371 crate::git::rev_parse(&repo, &state.candidates[0].branch)
2372 .await
2373 .unwrap(),
2374 head
2375 );
2376 assert!(worktree.exists());
2377 assert!(runs.join(&id).join("run.json").exists());
2378 }
2379 }
2380
2381 #[tokio::test]
2382 async fn recovery_retains_historical_sources_after_success_and_automatic_cleanup() {
2383 let dir = tempfile::tempdir().unwrap();
2384 let home = dir.path();
2385 let runs = home.join("runs");
2386 let wt = home.join("wt");
2387 let repo = home.join("repo");
2388 std::fs::create_dir_all(&repo).unwrap();
2389 init_repo(&repo);
2390 let mut task = crate::queue::Task::new(
2391 "recover".into(),
2392 "keep measured behavior".into(),
2393 repo.clone(),
2394 crate::queue::Source::Human,
2395 );
2396 let mut sources = Vec::new();
2397 for (id, status) in [
2398 ("20260801-000000-old1", RunStatus::Blocked),
2399 ("20260801-000000-old2", RunStatus::Stalled),
2400 ] {
2401 let (id, worktree) = due_run_with_winner_worktree(&runs, &wt, &repo, id, status).await;
2402 let mut state = RunState::load_under(&id, home).unwrap();
2403 state.driver_exited = true;
2404 state.save_under(home).unwrap();
2405 task.link_run(&id);
2406 sources.push((id, worktree));
2407 }
2408 crate::pr_recovery::retain_sources(&task, home).unwrap();
2409 let mut recovered = RunState::new(
2410 repo.clone(),
2411 "main".into(),
2412 "base".into(),
2413 task.instruction.clone(),
2414 crate::config::Config::default(),
2415 );
2416 recovered.config.graph.worktree_root = Some(wt.clone());
2417 recovered.status = RunStatus::Ready;
2418 recovered.driver_exited = true;
2419 recovered.save_under(home).unwrap();
2420 task.start(recovered.id.clone());
2421 task.succeed();
2422 crate::daemon::supersede_prior_runs(&task, home);
2423 for (id, _) in &sources {
2424 assert_eq!(
2425 RunState::load_under(id, home).unwrap().status,
2426 RunStatus::Superseded
2427 );
2428 }
2429 let disk = Disk::default();
2430 let now = Timestamp::now()
2431 .checked_add(SignedDuration::from_secs(
2432 i64::try_from(disk.fold_grace_secs + 1).unwrap(),
2433 ))
2434 .unwrap();
2435 let (_, unreadable) = fold_due(&runs, home, &wt, &disk, now).await.unwrap();
2436 assert_eq!(unreadable, 0);
2437 for (id, worktree) in sources {
2438 assert!(worktree.exists());
2439 assert!(
2440 crate::git::branch_exists(&repo, &format!("magi/{id}/A"))
2441 .await
2442 .unwrap()
2443 );
2444 let mut historical = RunState::load_under(&id, home).unwrap();
2445 assert!(!historical.candidates[0].folded);
2446 let error = crate::graph::fold_run(&mut historical, true, home)
2447 .await
2448 .unwrap_err();
2449 assert!(
2450 error
2451 .to_string()
2452 .contains("explicitly retained recovery source")
2453 );
2454 assert!(!historical.candidates[0].folded);
2455 assert!(
2456 worktree.exists(),
2457 "every automatic fold entry preserves retained sources"
2458 );
2459 }
2460 }
2461
2462 #[tokio::test]
2463 async fn fold_due_drops_a_superseded_runs_own_winner_worktree_but_keeps_a_readys() {
2464 let dir = tempfile::tempdir().unwrap();
2465 let runs = dir.path().join("runs");
2466 let wt = dir.path().join("wt");
2467 let repo = dir.path().join("repo");
2468 let home = dir.path().to_path_buf();
2469 let disk = Disk::default();
2470 let now = ts("2026-09-05T00:00:00Z");
2471 std::fs::create_dir_all(&repo).unwrap();
2472 init_repo(&repo);
2473
2474 let (superseded_id, superseded_wt) = due_run_with_winner_worktree(
2475 &runs,
2476 &wt,
2477 &repo,
2478 "20260801-000000-supw",
2479 RunStatus::Superseded,
2480 )
2481 .await;
2482 let (ready_id, ready_wt) = due_run_with_winner_worktree(
2489 &runs,
2490 &wt,
2491 &repo,
2492 "20260801-000000-rdyw",
2493 RunStatus::Ready,
2494 )
2495 .await;
2496
2497 let (folded, unreadable) = fold_due(&runs, &home, &wt, &disk, now)
2498 .await
2499 .expect("fold_due");
2500 assert_eq!(folded, 2);
2501 assert_eq!(unreadable, 0);
2502
2503 assert!(
2504 !superseded_wt.exists(),
2505 "a superseded run's own winner never lands anywhere else, so its worktree \
2506 must be dropped exactly like a merged run's"
2507 );
2508 assert!(
2509 ready_wt.exists(),
2510 "a still-ready run's winner may yet be merged by hand - folding must not \
2511 touch it"
2512 );
2513
2514 assert!(read_meta(&runs, &superseded_id).is_ok());
2516 assert!(read_meta(&runs, &ready_id).is_ok());
2517 }
2518}