trusty-mpm 1.7.4

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! The pool of persistent per-slot build directories (#8261).
//!
//! Why: one shared `CARGO_TARGET_DIR` per repo (#6868) bought the warm cache —
//! ~200 s cold, 103 s warm, 17 s warm again — and paid for it with Cargo's own
//! build-directory lock, which serialises every concurrent build sharing the
//! directory. The 2026-09-17 and 2026-09-19 incidents are what that costs: a
//! `cargo check` that spent 40 of 40m44s blocked on the lock, gates running two
//! to three hours, a sibling worktree's rlib clobbering another's so a
//! verification run reported someone else's test binary as its own verdict. A
//! POOL keeps the warm cache and removes the shared lock: each leased builder
//! compiles into a directory only it holds.
//!
//! What: a slot is one directory `<root>/<owner>/<repo>/slot-<n>/` plus the
//! admission token the daemon grants beside it. The pool grows LAZILY — a
//! machine that never reaches its ceiling never pays for the slots it did not
//! use — and a released slot KEEPS its directory, which is the warm cache the
//! next holder inherits.
//!
//! **Reserving and seeding are two calls, and the split is a hard requirement
//! (#8261 critic round).** [`SlotPool::reserve_path`] is bounded — a marker
//! stat and one `create_dir_all` of the parent — because it runs inside the
//! daemon's claim mutex, and the hook that is waiting on it gives up after 2
//! seconds. [`SlotPool::seed`] is the unbounded half: it APFS-clones (`cp -c`)
//! a target directory that has been measured at 207 GB, which cannot run on
//! that path. The daemon runs it on a blocking task after the answer is sent,
//! so the FIRST claim on a cold slot is admitted without a private directory
//! and the next one finds it seeded.
//!
//! **Clone failure is not slot failure.** A filesystem without copy-on-write
//! clones (any non-APFS volume, and every Linux filesystem `cp -c` does not
//! know) still gets a working slot — an empty, cold directory — and the lease
//! record says so through [`SeedKind::ColdDirectory`], because an operator
//! debugging a slow first build needs to know the clone did not happen.
//!
//! Nothing here decides ADMISSION. The count comes from
//! [`builder_capacity`](crate::core::builder_capacity); this module only turns
//! a granted slot index into a directory.
//!
//! Test: the `#[cfg(test)]` suite below, which uses a temp root throughout —
//! #8311 is the 42,000-directory leak from tests that wrote under the real home.

use std::path::{Path, PathBuf};

use trusty_common::github_path::GithubPath;

/// The marker file that records a slot directory has been seeded.
///
/// Why: seeding must happen ONCE per slot, not on every daemon restart and not
/// on every N-shrink-then-grow cycle — a re-clone over a directory holding a
/// live build's artifacts would corrupt it. A marker file survives both, which
/// an in-memory flag does not.
/// What: written inside the slot directory after a successful seed, with
/// `create_new` so exactly ONE run ever writes it; its presence is the whole
/// test, and it is also what [`SlotPool::reserve_path`] reads to decide whether
/// a slot can be granted now.
/// Test: `a_second_seed_does_not_reseed`,
/// `a_reservation_on_a_seeded_slot_is_ready`,
/// `two_staging_trees_for_one_index_publish_exactly_one_slot`.
pub const SEED_MARKER: &str = ".trusty-slot-seeded";

/// How a slot directory came to exist.
///
/// Why: the lease record must say whether the slot started warm, because that
/// is the difference between a 17-second first gate and a 200-second one, and
/// an operator seeing the slow one needs to know which happened.
/// What: one variant per outcome of the one-time seed.
/// Test: `a_fresh_slot_is_cloned_from_the_shared_directory`,
/// `a_missing_clone_source_still_yields_a_usable_cold_slot`,
/// `a_second_seed_does_not_reseed`.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SeedKind {
    /// Copy-on-write cloned from the repo's shared target directory.
    ClonedFromShared,
    /// Created empty: no clone source, or the filesystem does not support
    /// `cp -c`. The first build in this slot will be cold. `detail` says which.
    ColdDirectory(String),
    /// The directory already existed and carries [`SEED_MARKER`] — the warm
    /// case a released-then-reacquired slot takes.
    AlreadySeeded,
}

/// What one claim-time reservation resolved to (#8261 critic round).
///
/// Why: the claim path may not clone, and it may not hand out a directory that
/// has not been cloned yet — a builder pointed at a half-seeded slot would
/// compile against a partial cache. So the bounded call answers which of the two
/// states the slot is in, and the caller decides.
/// What: [`Self::Ready`] is a slot carrying [`SEED_MARKER`] and usable now.
/// [`Self::Seeding`] is a slot whose parent now exists and whose seed has still
/// to run; its path is NOT granted to this claim.
/// Test: `a_reservation_on_an_unseeded_slot_seeds_nothing`,
/// `a_reservation_on_a_seeded_slot_is_ready`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SlotReservation {
    /// The slot is seeded and can be built in now.
    Ready(PathBuf),
    /// The slot still needs [`SlotPool::seed`], which the caller must run off
    /// its own hot path.
    Seeding(PathBuf),
}

/// Why a slot directory could not be provided.
///
/// Why: a session that cannot be given a slot gets NO slot (fail closed) rather
/// than silently falling back to the shared directory — falling back is exactly
/// the clobbering this module exists to end.
/// What: `thiserror`, because this is library code.
/// Test: `an_unwritable_root_is_an_error_not_a_shared_fallback`.
// #8372: non_exhaustive from its first release, so a new failure is not an API break.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SlotPoolError {
    /// The slot directory could not be created.
    #[error("could not create builder slot directory {path}: {source}")]
    Create {
        /// The directory that could not be made.
        path: PathBuf,
        /// The underlying error.
        #[source]
        source: std::io::Error,
    },
}

/// One repo's slot pool, rooted at the operator's `builders.slot_pool_root`.
///
/// Why: keyed by `<owner>/<repo>` for the same reason the shared target
/// directory is (#6868) — two checkouts of one repo share a warm cache, and two
/// different repos never contend on one cargo lock. A slot index means nothing
/// across repos, so the repo is part of the pool's identity rather than a
/// parameter on every call.
/// What: holds only paths; creates nothing until [`Self::reserve_path`] is
/// called for a slot index the daemon has actually granted, and nothing beyond
/// that slot's parent until [`Self::seed`] runs off the claim path.
/// Test: `slot_paths_are_keyed_by_owner_and_repo`.
#[derive(Debug, Clone)]
pub struct SlotPool {
    root: PathBuf,
    identity: GithubPath,
}

impl SlotPool {
    /// A pool under `root` for one repo.
    ///
    /// Test: `slot_paths_are_keyed_by_owner_and_repo`.
    #[must_use]
    pub fn new(root: PathBuf, identity: GithubPath) -> Self {
        Self { root, identity }
    }

    /// Where slot `index` lives, whether or not it exists yet.
    ///
    /// Why: pure, so a doctor row or a refusal message can name a slot's
    /// directory without creating it. Creating a directory as a side effect of
    /// reporting would make the diagnosis change the thing diagnosed.
    /// What: `<root>/<owner>/<repo>/slot-<index>`.
    /// Test: `slot_paths_are_keyed_by_owner_and_repo`.
    #[must_use]
    pub fn slot_path(&self, index: u32) -> PathBuf {
        self.root
            .join(&self.identity.owner)
            .join(&self.identity.repo)
            .join(format!("slot-{index}"))
    }

    /// Is slot `index` usable right now, and if not, prepare for its seed.
    ///
    /// Why: this is the only half of the pool a claim may run. It is BOUNDED —
    /// one stat and one `create_dir_all` of the parent — because it executes
    /// inside the daemon's claim mutex while a hook waits on a 2-second budget.
    /// The clone that is not bounded lives in [`Self::seed`]. Creating the
    /// parent here is not incidental: it is still the fail-closed gate, so a
    /// pool root that cannot be written refuses the claim at claim time rather
    /// than minutes later on a background task nobody is reading.
    /// What: [`SlotReservation::Ready`] when [`SEED_MARKER`] is present — the
    /// warm case a released slot leaves for its next holder — else
    /// [`SlotReservation::Seeding`], which grants NO directory and obliges the
    /// caller to run [`Self::seed`] off its own hot path.
    ///
    /// # Errors
    ///
    /// [`SlotPoolError::Create`] when the slot's parent cannot be made. The
    /// caller must then grant NO slot: falling back to the shared directory is
    /// the clobbering this module exists to end.
    ///
    /// Test: `a_reservation_on_an_unseeded_slot_seeds_nothing`,
    /// `a_reservation_on_a_seeded_slot_is_ready`,
    /// `an_unwritable_root_is_an_error_not_a_shared_fallback`.
    pub fn reserve_path(&self, index: u32) -> Result<SlotReservation, SlotPoolError> {
        let path = self.slot_path(index);
        if path.join(SEED_MARKER).is_file() {
            return Ok(SlotReservation::Ready(path));
        }
        let parent = path.parent().unwrap_or(path.as_path());
        std::fs::create_dir_all(parent).map_err(|source| SlotPoolError::Create {
            path: parent.to_path_buf(),
            source,
        })?;
        Ok(SlotReservation::Seeding(path))
    }

    /// Create slot `index` if it does not exist, seeding it once.
    ///
    /// Why: LAZY growth is the owner's 2026-09-20 ruling — the pool is not
    /// pre-sized to the ceiling, so a machine that never reaches its ceiling
    /// never pays that disk. Seeding is one-time because a re-clone over a live
    /// build's artifacts would corrupt them; [`SEED_MARKER`] is what makes it
    /// one-time across daemon restarts. This is the UNBOUNDED half of the pool
    /// and must never run on a path a hook is waiting on — see the module doc.
    /// What: returns the slot's path and how it came to be. An existing,
    /// marked directory is returned untouched. A clone that fails for ANY
    /// reason still yields a usable cold directory.
    ///
    /// `clone_from` is the repo's current shared `CARGO_TARGET_DIR`. `None`, or
    /// a path that does not exist, gives a cold slot rather than an error — a
    /// machine with no warm directory yet is an ordinary first run.
    ///
    /// # Errors
    ///
    /// [`SlotPoolError::Create`] when the slot directory cannot be made, or when
    /// [`SEED_MARKER`] cannot be written. The marker failure is an error and not
    /// a warning (#8261 critic round): an unmarked directory is re-seeded by the
    /// next caller, and a re-seed over a directory a builder is using is the
    /// corruption the marker exists to prevent.
    ///
    /// Test: `a_fresh_slot_is_cloned_from_the_shared_directory`,
    /// `a_missing_clone_source_still_yields_a_usable_cold_slot`,
    /// `a_second_seed_does_not_reseed`,
    /// `a_released_slot_directory_is_reused_by_the_next_holder`,
    /// `an_unmarked_directory_is_reseeded_without_nesting`,
    /// `an_unwritable_root_is_an_error_not_a_shared_fallback`.
    pub fn seed(
        &self,
        index: u32,
        clone_from: Option<&Path>,
    ) -> Result<(PathBuf, SeedKind), SlotPoolError> {
        let path = self.slot_path(index);
        if path.join(SEED_MARKER).is_file() {
            return Ok((path, SeedKind::AlreadySeeded));
        }
        sweep_abandoned_staging(&path);
        let seed = match clone_from.filter(|src| src.is_dir()) {
            Some(src) => match clone_directory(src, &path) {
                Ok(()) => SeedKind::ClonedFromShared,
                Err(detail) => {
                    // A clone that lost the publish race to another run leaves
                    // the marker here; treat that as the warm case rather than
                    // stamping ColdDirectory over its tree.
                    if path.join(SEED_MARKER).is_file() {
                        return Ok((path, SeedKind::AlreadySeeded));
                    }
                    create_cold(&path)?;
                    SeedKind::ColdDirectory(detail)
                }
            },
            None => {
                create_cold(&path)?;
                SeedKind::ColdDirectory("no warm shared target directory to clone from".to_string())
            }
        };
        // The marker goes down last, so a seed interrupted partway is retried
        // rather than inherited as a half-cloned directory. `create_new` makes
        // the write itself the election: exactly one run ever marks a slot, so
        // two runs that survived a daemon restart together cannot both claim to
        // have seeded it (#8261 critic round 3).
        let marker = path.join(SEED_MARKER);
        match std::fs::File::create_new(&marker) {
            Ok(mut file) => {
                use std::io::Write;
                file.write_all(seed_marker_body(&seed).as_bytes())
                    .map_err(|source| SlotPoolError::Create {
                        path: marker,
                        source,
                    })?;
                Ok((path, seed))
            }
            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
                Ok((path, SeedKind::AlreadySeeded))
            }
            Err(source) => Err(SlotPoolError::Create {
                path: marker,
                source,
            }),
        }
    }
}

/// What the marker file records, for a human reading the pool directory.
fn seed_marker_body(seed: &SeedKind) -> String {
    format!("#8261 builder slot pool\nseed: {seed:?}\n")
}

/// This run's private staging directory for `dst`.
///
/// Why: a fixed staging name is a shared mutable directory between any two seed
/// runs, and the first act of a seed is to clear it — so the later run deletes
/// the earlier one's tree mid-copy. The in-daemon registry cannot prevent that
/// pairing across a restart: `std::process::Command` sets no death signal (macOS
/// has none), so a `cp -c -R` outlives the daemon that spawned it while the new
/// daemon's registry starts empty (#8261 critic round 3). PID plus nanoseconds
/// is unique across both processes and repeated seeds within one.
/// What: `<parent>/.<slot>.seeding.<pid>.<nanos>`.
/// Test: `two_staging_trees_for_one_index_publish_exactly_one_slot`.
fn staging_path(parent: &Path, slot: &str) -> PathBuf {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    parent.join(format!(
        "{STAGING_PREFIX_DOT}{slot}.seeding.{}.{nanos}",
        std::process::id()
    ))
}

/// The leading character every staging directory's name carries.
const STAGING_PREFIX_DOT: &str = ".";

/// Delete staging trees left by seed runs whose process is gone (#8261).
///
/// Why: a staging tree is a full clone of the shared target directory, so an
/// abandoned one is real disk — and abandoning one is now possible, because a
/// `cp` that outlives its daemon can be killed before it publishes. Liveness is
/// the only safe test: deleting a LIVE run's staging tree would restore exactly
/// the two-writer corruption the unique name removes.
/// What: scans the slot's parent for `.<slot>.seeding.<pid>.<nanos>` entries and
/// removes only those whose `<pid>` is confirmed dead. An unparseable name, or a
/// pid that is alive or undeterminable, is left alone (ADR-0045).
/// Test: `two_staging_trees_for_one_index_publish_exactly_one_slot`.
fn sweep_abandoned_staging(dst: &Path) {
    let (Some(parent), Some(slot)) = (
        dst.parent(),
        dst.file_name().and_then(std::ffi::OsStr::to_str),
    ) else {
        return;
    };
    let prefix = format!("{STAGING_PREFIX_DOT}{slot}.seeding.");
    let Ok(entries) = std::fs::read_dir(parent) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(rest) = name.to_str().and_then(|n| n.strip_prefix(&prefix)) else {
            continue;
        };
        let Ok(pid) = rest.split('.').next().unwrap_or_default().parse::<u32>() else {
            continue;
        };
        if crate::core::process::is_process_alive(pid) {
            continue;
        }
        if let Err(err) = std::fs::remove_dir_all(entry.path()) {
            tracing::warn!(
                "could not sweep abandoned builder-slot staging {}: {err}",
                entry.path().display()
            );
        }
    }
}

/// Create an empty slot directory, parents included.
fn create_cold(path: &Path) -> Result<(), SlotPoolError> {
    std::fs::create_dir_all(path).map_err(|source| SlotPoolError::Create {
        path: path.to_path_buf(),
        source,
    })
}

/// Copy-on-write clone `src` to `dst`, or say why not.
///
/// Why: `cp -c` is the only portable way to ask APFS for a clone from Rust
/// without an `fcntl`/`clonefile` binding, and the cost matters: a clone of the
/// 207 GB shared directory is near-zero disk and seconds of wall clock, against
/// ~200 s for the cold build it replaces.
/// What: `cp -c -R` on macOS, into a staging sibling that is then renamed into
/// place. Any non-zero exit, any missing `cp`, and every non-macOS platform
/// return `Err(detail)` — the caller then creates a cold directory, because a
/// slot that works slowly beats no slot at all.
///
/// **Never `cp -c -R <src> <dst>` onto an existing `dst`.** BSD `cp` then writes
/// `dst/<basename(src)>` and still exits 0, so the slot would be reported
/// [`SeedKind::ClonedFromShared`] with an empty top level and a nested copy
/// underneath — a cold build that claims to be warm (#8261 critic round). The
/// staging tree has no such case, and the rename is atomic.
///
/// **The staging tree is private to this run** ([`staging_path`]), and `dst` is
/// replaced only while it carries no [`SEED_MARKER`]. Together those two make a
/// second run — one that survived a daemon restart, which the in-memory registry
/// cannot see — unable to delete this run's tree or to overwrite a slot a
/// builder was granted (#8261 critic round 3).
///
/// # Errors
///
/// A human-readable reason the clone did not happen, for [`SeedKind::ColdDirectory`].
///
/// Test: `a_missing_clone_source_still_yields_a_usable_cold_slot`,
/// `two_staging_trees_for_one_index_publish_exactly_one_slot`, and
/// `a_fresh_slot_is_cloned_from_the_shared_directory`,
/// `an_unmarked_directory_is_reseeded_without_nesting` on macOS.
fn clone_directory(src: &Path, dst: &Path) -> Result<(), String> {
    if !cfg!(target_os = "macos") {
        return Err(format!(
            "copy-on-write clone is macOS/APFS only; this is {}",
            std::env::consts::OS
        ));
    }
    let Some(parent) = dst.parent() else {
        return Err(format!("{} has no parent directory", dst.display()));
    };
    if let Err(err) = std::fs::create_dir_all(parent) {
        return Err(format!("could not create {}: {err}", parent.display()));
    }
    let slot = dst
        .file_name()
        .and_then(std::ffi::OsStr::to_str)
        .unwrap_or("slot");
    let staging = staging_path(parent, slot);
    // `cp -c` fails outright rather than falling back to a full byte copy when
    // the volume cannot clone, which is the behaviour wanted here: a silent
    // 207 GB real copy would fill the disk this design is trying to conserve.
    let output = std::process::Command::new("cp")
        .arg("-c")
        .arg("-R")
        .arg(src)
        .arg(&staging)
        .output()
        .map_err(|err| format!("could not run cp: {err}"))?;
    if !output.status.success() {
        drop(std::fs::remove_dir_all(&staging));
        return Err(format!(
            "cp -c exited {}: {}",
            output.status,
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    // Re-read the marker here, not only at `seed`'s entry: a run that survived
    // a daemon restart can have published this slot while `cp` was running, and
    // replacing a MARKED directory would destroy a tree a builder holds.
    if dst.join(SEED_MARKER).is_file() {
        drop(std::fs::remove_dir_all(&staging));
        return Err(format!("another seed published {} first", dst.display()));
    }
    if dst.exists()
        && let Err(err) = std::fs::remove_dir_all(dst)
    {
        drop(std::fs::remove_dir_all(&staging));
        return Err(format!(
            "could not replace the unseeded {}: {err}",
            dst.display()
        ));
    }
    std::fs::rename(&staging, dst).map_err(|err| {
        drop(std::fs::remove_dir_all(&staging));
        format!("could not move the clone into {}: {err}", dst.display())
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn identity() -> GithubPath {
        GithubPath {
            owner: "bobmatnyc".to_string(),
            repo: "trusty-tools".to_string(),
        }
    }

    /// Every test here roots the pool in a temp dir. #8311: tests that wrote
    /// under the real `~/.trusty-tools` leaked 42,000 directories.
    fn pool(root: &Path) -> SlotPool {
        SlotPool::new(root.to_path_buf(), identity())
    }

    #[test]
    fn slot_paths_are_keyed_by_owner_and_repo() {
        let pool = SlotPool::new(PathBuf::from("/pool"), identity());
        assert_eq!(
            pool.slot_path(3),
            Path::new("/pool/bobmatnyc/trusty-tools/slot-3")
        );
        // Nothing was created by asking.
        assert!(!Path::new("/pool/bobmatnyc").exists());
    }

    #[test]
    fn a_fresh_slot_is_cloned_from_the_shared_directory() {
        let tmp = tempfile::tempdir().expect("temp root");
        let shared = tmp.path().join("shared");
        std::fs::create_dir_all(shared.join("debug")).expect("a warm shared dir");
        std::fs::write(shared.join("debug/libfoo.rlib"), b"warm").expect("an artifact");

        let (path, seed) = pool(&tmp.path().join("pool"))
            .seed(0, Some(&shared))
            .expect("a slot on a writable root");

        assert!(path.is_dir(), "the slot directory exists");
        if cfg!(target_os = "macos") {
            assert_eq!(seed, SeedKind::ClonedFromShared, "APFS clones");
            assert_eq!(
                std::fs::read(path.join("debug/libfoo.rlib")).expect("the cloned artifact"),
                b"warm",
                "the slot starts warm — that is the whole point of seeding"
            );
        } else {
            // Non-APFS platforms take the documented cold path, and still get a
            // usable slot.
            assert!(matches!(seed, SeedKind::ColdDirectory(_)), "{seed:?}");
        }
    }

    #[test]
    fn a_missing_clone_source_still_yields_a_usable_cold_slot() {
        let tmp = tempfile::tempdir().expect("temp root");
        // A clone source that does not exist is the "no warm directory yet"
        // case: a cold slot, never an error.
        let (path, seed) = pool(&tmp.path().join("pool"))
            .seed(1, Some(Path::new("/nonexistent/shared")))
            .expect("a missing clone source is not a slot failure");
        assert!(path.is_dir(), "a cold slot is still a usable slot");
        assert!(matches!(seed, SeedKind::ColdDirectory(_)), "{seed:?}");
    }

    /// #8261 critic round: the claim path may only RESERVE. A reservation on an
    /// unseeded slot must create nothing but the parent and grant no directory,
    /// or the 207 GB clone runs under the daemon's claim mutex against a hook
    /// that gives up after 2 seconds.
    #[test]
    fn a_reservation_on_an_unseeded_slot_seeds_nothing() {
        let tmp = tempfile::tempdir().expect("temp root");
        let root = tmp.path().join("pool");
        let shared = tmp.path().join("shared");
        std::fs::create_dir_all(&shared).expect("a shared dir");
        std::fs::write(shared.join("sentinel"), b"warm").expect("a sentinel artifact");

        let reserved = pool(&root).reserve_path(0).expect("a writable root");

        let SlotReservation::Seeding(path) = reserved else {
            panic!("an unseeded slot reserves as Seeding, got {reserved:?}");
        };
        assert!(
            !path.exists(),
            "the slot directory itself is the seed's to make: {path:?}"
        );
        assert!(
            path.parent().is_some_and(Path::is_dir),
            "the parent IS created — it is the fail-closed gate"
        );
        assert!(
            !path.join("sentinel").exists(),
            "nothing may be cloned on the claim path"
        );
    }

    /// The warm case: a marked slot reserves as `Ready` and is handed straight
    /// to the builder.
    #[test]
    fn a_reservation_on_a_seeded_slot_is_ready() {
        let tmp = tempfile::tempdir().expect("temp root");
        let pool = pool(&tmp.path().join("pool"));
        let (seeded, _) = pool.seed(0, None).expect("a cold slot");

        assert_eq!(
            pool.reserve_path(0).expect("a writable root"),
            SlotReservation::Ready(seeded),
            "a marked slot is usable now"
        );
    }

    /// #8261 critic round: `cp -c -R src dst` onto an existing `dst` nests the
    /// copy under `dst/<basename(src)>` and still exits 0. An unmarked
    /// directory — the state a failed marker write used to leave behind — must
    /// therefore be re-seeded flat, never nested.
    #[test]
    fn an_unmarked_directory_is_reseeded_without_nesting() {
        let tmp = tempfile::tempdir().expect("temp root");
        let shared = tmp.path().join("shared");
        std::fs::create_dir_all(&shared).expect("a shared dir");
        std::fs::write(shared.join("sentinel"), b"warm").expect("an artifact");
        let pool = pool(&tmp.path().join("pool"));

        // An UNMARKED slot directory, as an interrupted seed leaves one.
        let slot = pool.slot_path(0);
        std::fs::create_dir_all(&slot).expect("a half-made slot");

        let (path, seed) = pool.seed(0, Some(&shared)).expect("the re-seed succeeds");

        assert!(
            !path.join("shared").exists(),
            "the clone must not nest under the slot: {path:?}"
        );
        if cfg!(target_os = "macos") {
            assert_eq!(seed, SeedKind::ClonedFromShared);
            assert!(
                path.join("sentinel").is_file(),
                "a ClonedFromShared slot must actually carry the cache"
            );
        }
        assert!(
            path.join(SEED_MARKER).is_file(),
            "the re-seed marks the slot, or the next caller re-seeds it again"
        );
    }

    #[test]
    fn a_slot_with_no_clone_source_says_so() {
        let tmp = tempfile::tempdir().expect("temp root");
        let (_, seed) = pool(&tmp.path().join("pool"))
            .seed(0, None)
            .expect("a slot with no source");
        match seed {
            SeedKind::ColdDirectory(detail) => {
                assert!(
                    detail.contains("no warm shared target directory"),
                    "{detail}"
                );
            }
            other => panic!("expected ColdDirectory, got {other:?}"),
        }
    }

    #[test]
    fn a_second_seed_does_not_reseed() {
        let tmp = tempfile::tempdir().expect("temp root");
        let shared = tmp.path().join("shared");
        std::fs::create_dir_all(&shared).expect("a shared dir");
        let pool = pool(&tmp.path().join("pool"));

        let (path, _) = pool.seed(0, Some(&shared)).expect("first lease");
        // An artifact the live build wrote. A re-clone would destroy it.
        std::fs::write(path.join("in-progress"), b"mine").expect("a build artifact");

        let (again, seed) = pool.seed(0, Some(&shared)).expect("second lease");
        assert_eq!(again, path);
        assert_eq!(seed, SeedKind::AlreadySeeded);
        assert_eq!(
            std::fs::read(path.join("in-progress")).expect("the artifact survived"),
            b"mine",
        );
    }

    #[test]
    fn a_released_slot_directory_is_reused_by_the_next_holder() {
        let tmp = tempfile::tempdir().expect("temp root");
        let pool = pool(&tmp.path().join("pool"));
        let (first, _) = pool.seed(2, None).expect("holder one");
        std::fs::write(first.join("warm.rlib"), b"cache").expect("an artifact");

        // Releasing a lease keeps the directory — it IS the warm cache.
        let (second, seed) = pool.seed(2, None).expect("holder two");
        assert_eq!(second, first);
        assert_eq!(seed, SeedKind::AlreadySeeded);
        assert!(
            second.join("warm.rlib").is_file(),
            "the next holder inherits the previous holder's cache"
        );
    }

    #[test]
    fn an_unwritable_root_is_an_error_not_a_shared_fallback() {
        let tmp = tempfile::tempdir().expect("temp root");
        // A FILE where the pool root must be a directory: create_dir_all fails.
        let blocked = tmp.path().join("blocked");
        std::fs::write(&blocked, b"not a directory").expect("a blocking file");

        // The RESERVATION is the fail-closed gate, so it is what must refuse —
        // by the time `seed` runs, the claim has already been answered.
        let err = pool(&blocked).reserve_path(0).expect_err(
            "a slot that cannot be made must be refused, never swapped for the shared dir",
        );
        assert!(
            matches!(err, SlotPoolError::Create { .. }),
            "expected Create, got {err:?}"
        );
    }

    /// #8261 critic round 3, MEDIUM: two seed runs never share a staging tree.
    ///
    /// The in-daemon registry cannot pair with a `cp -c -R` that outlived the
    /// daemon that spawned it — `std::process::Command` sets no death signal,
    /// and macOS has none — so the new daemon's empty registry would spawn a
    /// second seed whose first act, under the old fixed `.slot-N.seeding` name,
    /// was `remove_dir_all` of the survivor's tree. Staging names are now
    /// per-run, only a dead run's tree is swept, and `create_new` makes the
    /// marker write the single election.
    #[test]
    fn two_staging_trees_for_one_index_publish_exactly_one_slot() {
        let tmp = tempfile::tempdir().expect("temp root");
        let shared = tmp.path().join("shared");
        std::fs::create_dir_all(&shared).expect("a shared dir");
        std::fs::write(shared.join("sentinel"), b"warm").expect("an artifact");
        let pool = pool(&tmp.path().join("pool"));
        let slot = pool.slot_path(0);
        let parent = slot.parent().expect("a slot has a parent").to_path_buf();
        std::fs::create_dir_all(&parent).expect("the pool parent");

        // A tree left by a run whose process is gone — pid 1 is `launchd` and
        // never dies, so the LIVE case is the one held by a real pid here.
        let abandoned = parent.join(".slot-0.seeding.4294967294.1");
        std::fs::create_dir_all(&abandoned).expect("an abandoned staging tree");
        let live = parent.join(format!(".slot-0.seeding.{}.1", std::process::id()));
        std::fs::create_dir_all(&live).expect("a live run's staging tree");

        let (path, _) = pool.seed(0, Some(&shared)).expect("the seed publishes");

        assert!(
            !abandoned.exists(),
            "a dead run's staging tree is swept: {abandoned:?}"
        );
        assert!(
            live.exists(),
            "a LIVE run's staging tree must never be deleted — that is the \
             two-writer corruption this fix removes"
        );
        assert!(
            path.join(SEED_MARKER).is_file(),
            "the winner marks the slot"
        );
        let staging_left: Vec<_> = std::fs::read_dir(&parent)
            .expect("read the pool parent")
            .flatten()
            .filter(|e| {
                e.file_name()
                    .to_str()
                    .is_some_and(|n| n.starts_with(".slot-0.seeding.") && !e.path().eq(&live))
            })
            .collect();
        assert!(
            staging_left.is_empty(),
            "the published run leaves no staging tree behind: {staging_left:?}"
        );

        // A second run over the published slot writes no second marker and
        // reports the warm case rather than re-cloning.
        let marked_at = std::fs::metadata(path.join(SEED_MARKER))
            .and_then(|m| m.modified())
            .expect("marker mtime");
        let (again, seed) = pool.seed(0, Some(&shared)).expect("the second run");
        assert_eq!(again, path);
        assert_eq!(seed, SeedKind::AlreadySeeded);
        assert_eq!(
            std::fs::metadata(path.join(SEED_MARKER))
                .and_then(|m| m.modified())
                .expect("marker mtime"),
            marked_at,
            "the marker is written exactly once"
        );
    }

    #[test]
    fn two_slots_are_two_directories() {
        let tmp = tempfile::tempdir().expect("temp root");
        let pool = pool(&tmp.path().join("pool"));
        let (a, _) = pool.seed(0, None).expect("slot 0");
        let (b, _) = pool.seed(1, None).expect("slot 1");
        assert_ne!(a, b, "two concurrent builders never share a directory");
        assert!(a.is_dir() && b.is_dir());
    }
}