aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
//! Process-lifetime re-exec identity, independent of the deployment pathname.
//!
//! Placement may rename a new binary over the daemon's fixed deployment pathname
//! while it serves requests. Its children must keep using the startup image.
//! Standalone hosts use versioned paths and retain normal executable discovery.

use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

#[cfg(target_os = "linux")]
mod linux_image;
#[cfg(all(target_os = "linux", feature = "test-hooks"))]
pub use linux_image::prepare_fixture_pin;

#[rustfmt::skip]
test_support_visibility! {
struct PinnedExecutable {
    #[cfg(any(test, feature = "test-support"))]
    pub executable: PathBuf,
    #[cfg(not(any(test, feature = "test-support")))]
    executable: PathBuf,
    #[cfg(any(test, feature = "test-support"))]
    pub directory: PathBuf,
    #[cfg(not(any(test, feature = "test-support")))]
    directory: PathBuf,
    state: Mutex<PinState>,
}
}

struct PinState {
    owner: Option<std::fs::File>,
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    source: std::fs::File,
    #[cfg(target_os = "linux")]
    image_key: linux_image::ImageKey,
    #[cfg(target_os = "linux")]
    pin_identity: linux_image::PinIdentity,
}

#[rustfmt::skip]
test_support_visibility! {
static PINNED: OnceLock<PinnedExecutable> = OnceLock::new();
}

thread_local! {
    static TASK_IMAGE: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
}

const OWNER_LOCK: &str = "owner.lock";
pub const TASK_IMAGE_DIR: &str = "startup-image";

#[cfg(target_os = "macos")]
struct StartupSource {
    path: PathBuf,
    file: std::fs::File,
}
#[cfg(target_os = "macos")]
static SOURCE: OnceLock<Result<StartupSource, String>> = OnceLock::new();

/// On macOS, hold the startup executable open without creating a persistent
/// pin. Metadata-only CLI modes may call this; other platforms need no handle.
pub fn capture_at_startup() {
    #[cfg(target_os = "macos")]
    SOURCE.get_or_init(|| {
        let path = std::env::current_exe()
            .and_then(|path| path.canonicalize())
            .map_err(|error| error.to_string())?;
        let file = std::fs::File::open(&path).map_err(|error| error.to_string())?;
        Ok(StartupSource { path, file })
    });
}

/// Called once by the daemon, before any serving-process child can be spawned.
pub fn initialize() -> io::Result<()> {
    if PINNED.get().is_some() {
        return Ok(());
    }
    let storage = crate::storage_path::storage_dir(None);
    let pin = prepare(&storage)?;
    PINNED
        .set(pin)
        .map_err(|_| io::Error::other("executable pin was initialized concurrently"))
}

#[rustfmt::skip]
test_support_visibility! {

fn prepare(storage: &Path) -> io::Result<PinnedExecutable> {
    // Resolve the image before touching storage. Keep an open source when a
    // copy is needed so a concurrent placement cannot change the copied bytes.
    #[cfg(target_os = "macos")]
    capture_at_startup();
    #[cfg(target_os = "macos")]
    let source = SOURCE
        .get()
        .expect("startup source captured")
        .as_ref()
        .map_err(|error| io::Error::other(error.clone()))?;
    #[cfg(target_os = "macos")]
    let mut source_file = source.file.try_clone()?;
    #[cfg(target_os = "macos")]
    let source_path = source.path.clone();
    // Landlock shells cannot dereference an unsandboxed daemon's procfs exe
    // link. Materialize that kernel-held image once, rather than per command.
    #[cfg(target_os = "linux")]
    let source_file = std::fs::File::open(linux_image_path())?;
    #[cfg(target_os = "linux")]
    let image_key = linux_image::ImageKey::new(&source_file)?;

    crate::private_storage::open_root(storage)?;
    let storage = storage.canonicalize()?;
    let run = storage.join("run");
    match crate::private_storage::create_dir(&run) {
        Ok(()) => {}
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
        Err(error) => return Err(error),
    }
    // Require the storage `run` path to be a directory, not a symlink.
    if !std::fs::symlink_metadata(&run)?.file_type().is_dir() {
        return Err(io::Error::other(
            "AFT storage run domain is not a directory",
        ));
    }
    crate::private_storage::tighten_open_dir(&storage, &run);
    cleanup(&run)?;
    let pid = std::process::id();
    let start = crate::process_identity::process_start_time_ms(pid)
        .ok_or_else(|| io::Error::other("cannot determine executable pin owner start time"))?;
    let directory = run.join(format!("aft-pinned-{pid}-{start}"));
    crate::private_storage::create_dir(&directory)?;

    let result = (|| {
        let owner = owner_lock(&directory)?;
        #[cfg(target_os = "linux")]
        let (executable, pin_identity) = image_key.pin(&run, &source_file)?;
        #[cfg(target_os = "macos")]
        let executable = {
            let destination = directory.join("aft");
            materialize(&source_path, &mut source_file, &destination, link_image)?;
            warm_new_image(&destination);
            destination
        };
        // Windows holds the executable image open without write/delete sharing;
        // placement cannot replace a running .exe at its deployment pathname.
        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        let executable = std::env::current_exe()?;
        std::fs::metadata(&executable)?;
        Ok(PinnedExecutable {
            executable,
            directory: directory.clone(),
            state: Mutex::new(PinState {
                owner: Some(owner),
                #[cfg(any(target_os = "linux", target_os = "macos"))]
                source: source_file,
                #[cfg(target_os = "linux")]
                image_key,
                #[cfg(target_os = "linux")]
                pin_identity,
            }),
        })
    })();
    if result.is_err() {
        let _ = std::fs::remove_dir_all(directory);
    }
    result
}
}

fn cleanup(run: &Path) -> io::Result<()> {
    for entry in std::fs::read_dir(run)? {
        let entry = entry?;
        let name = entry.file_name();
        let Some((pid, start)) = owner(&name.to_string_lossy()) else {
            continue;
        };
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let alive = match crate::process_identity::process_start_time_ms(pid) {
            Some(actual) => actual == start,
            // An inaccessible start time is not proof of death.
            None => crate::fs_lock::process_alive(pid),
        };
        if !alive {
            // The kernel lease is authoritative even if another PID namespace
            // or a changed boot-clock conversion reports a different owner.
            let lease_path = entry.path().join(OWNER_LOCK);
            let lease = if lease_path.try_exists()? {
                let mut options = crate::private_storage::options();
                #[cfg(unix)]
                {
                    use std::os::unix::fs::OpenOptionsExt;
                    options.custom_flags(libc::O_NOFOLLOW);
                }
                let Ok(file) = options.read(true).write(true).open(&lease_path) else {
                    continue;
                };
                if file.try_lock().is_err() {
                    continue;
                }
                Some(file)
            } else {
                None
            };
            // Windows cannot unlink an open lock file. The owner is already
            // dead and pin names are never reused, so release before removal.
            drop(lease);
            match std::fs::remove_dir_all(entry.path()) {
                Ok(()) => {}
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
        }
    }
    Ok(())
}

fn owner_lock(directory: &Path) -> io::Result<std::fs::File> {
    let file = crate::private_storage::options()
        .read(true)
        .write(true)
        .create_new(true)
        .open(directory.join(OWNER_LOCK))?;
    file.lock_shared()?;
    Ok(file)
}

impl PinnedExecutable {
    fn path(&self) -> io::Result<PathBuf> {
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        #[cfg(target_os = "linux")]
        let has_image = self
            .executable
            .symlink_metadata()
            .is_ok_and(|metadata| state.pin_identity.matches(&metadata));
        #[cfg(not(target_os = "linux"))]
        let has_image = self.executable.is_file();
        if has_image && self.directory.is_dir() {
            return Ok(self.executable.clone());
        }
        crate::slog_warn!(
            "startup executable pin missing; restoring {}",
            self.executable.display()
        );
        crate::private_storage::create_dir_all(&self.directory)?;
        if !self.directory.join(OWNER_LOCK).try_exists()? {
            state.owner = Some(owner_lock(&self.directory)?);
        }
        #[cfg(target_os = "linux")]
        {
            (_, state.pin_identity) = state.image_key.pin(
                self.directory.parent().expect("pin owner directory in run"),
                &state.source,
            )?;
        }
        #[cfg(target_os = "macos")]
        {
            let temporary = self.directory.join("aft.repin");
            let _ = std::fs::remove_file(&temporary);
            // The deployment pathname may now contain a different build. Only
            // the held startup image is a valid source for repair.
            materialize(&self.executable, &mut state.source, &temporary, |_, _| {
                Err(io::Error::other("repair from held startup image"))
            })?;
            std::fs::rename(temporary, &self.executable)?;
        }
        std::fs::metadata(&self.executable)?;
        Ok(self.executable.clone())
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn cleanup_at_exit(&self) {
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.owner.take();
        let _ = std::fs::remove_dir_all(&self.directory);
    }
    }

    fn task_image(&self, task_io: &Path) -> io::Result<PathBuf> {
        let executable = self.path()?;
        let directory = task_io.join(TASK_IMAGE_DIR);
        crate::private_storage::create_dir(&directory)?;
        let destination = task_executable(task_io);
        #[cfg(unix)]
        {
            #[cfg(target_os = "linux")]
            std::os::unix::fs::symlink(&executable, &destination)?;
            #[cfg(not(target_os = "linux"))]
            {
                let mut source = std::fs::File::open(&executable)?;
                materialize(&executable, &mut source, &destination, |from, to| {
                    std::fs::hard_link(from, to)
                })?;
            }
            let entry = self.directory.join("shims/gh");
            let retained = directory.join("shims/gh");
            match std::fs::symlink_metadata(&entry) {
                Ok(metadata) if metadata.is_symlink() => {
                    let target = std::fs::read_link(&entry)?;
                    let target = if target == self.executable {
                        destination
                    } else {
                        target
                    };
                    crate::private_storage::create_dir(&directory.join("shims"))?;
                    std::os::unix::fs::symlink(target, &retained)?;
                }
                Ok(metadata) if metadata.is_file() => {
                    // An unverified candidate is replaced by a script that
                    // refuses to run gh. Keep that script executable in the
                    // task's PATH rather than exposing the system gh.
                    crate::private_storage::create_dir(&directory.join("shims"))?;
                    std::fs::copy(&entry, &retained)?;
                }
                Ok(_) => return Err(io::Error::other("unexpected gh shim file type")),
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
        }
        #[cfg(windows)]
        {
            // Windows keeps the running deployment image locked, but not the
            // daemon-owned gh.cmd pathname. Retain both in the task's lifetime.
            if std::fs::hard_link(&executable, &destination).is_err() {
                std::fs::copy(&executable, &destination)?;
            }
            let shim = self.directory.join("shims/gh.cmd");
            if shim.is_file() {
                let contents = std::fs::read(&shim)?;
                let contents = if contents == crate::gh_shim_paths::windows_gh_cmd(&executable) {
                    crate::gh_shim_paths::windows_gh_cmd(&destination)
                } else {
                    contents
                };
                crate::private_storage::create_dir(&directory.join("shims"))?;
                std::fs::write(directory.join("shims/gh.cmd"), contents)?;
            }
        }
        Ok(directory)
    }
}

/// Freeze the launcher and shim into the task's own artifact lifetime before
/// constructing a native profile or launching an unconfined shell. Foreground
/// tasks need the same lifetime because they can be promoted to background.
pub fn with_task_image<R>(task_io: &Path, run: impl FnOnce() -> R) -> io::Result<R> {
    let Some(pin) = PINNED.get() else {
        return Ok(run());
    };
    let directory = pin.task_image(task_io)?;
    struct Scope(Option<PathBuf>);
    impl Drop for Scope {
        fn drop(&mut self) {
            TASK_IMAGE.with(|slot| {
                slot.replace(self.0.take());
            });
        }
    }
    let _scope = Scope(TASK_IMAGE.with(|slot| slot.replace(Some(directory))));
    Ok(run())
}

pub fn task_executable(task_io: &Path) -> PathBuf {
    task_io
        .join(TASK_IMAGE_DIR)
        .join(if cfg!(windows) { "aft.exe" } else { "aft" })
}

/// Non-launcher plans have no launcher pathname to carry the retained image.
/// Redirect their request overrides before either the pipe or PTY adapter runs.
pub fn retain_task_environment(
    task_io: &Path,
    environment: &mut std::collections::HashMap<String, String>,
) -> io::Result<()> {
    with_task_image(task_io, || {
        let mut values = environment
            .iter()
            .map(|(key, value)| (key.into(), value.into()))
            .collect();
        task_environment(&task_executable(task_io), &mut values);
        *environment = values
            .into_iter()
            .map(|(key, value)| {
                (
                    key.to_string_lossy().into_owned(),
                    value.to_string_lossy().into_owned(),
                )
            })
            .collect();
    })
}

pub fn is_dead_pin_path(path: &Path) -> bool {
    path.is_absolute()
        && path.ancestors().any(|ancestor| {
            ancestor
                .file_name()
                .and_then(|name| name.to_str())
                .and_then(owner)
                .is_some()
                && ancestor.parent().and_then(Path::file_name) == Some(std::ffi::OsStr::new("run"))
        })
        && matches!(path.try_exists(), Ok(false))
}

pub fn task_environment(
    launcher: &Path,
    environment: &mut std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>,
) {
    let Some(pin) = PINNED.get() else {
        return;
    };
    let Some(directory) = launcher
        .parent()
        .filter(|path| path.file_name() == Some(std::ffi::OsStr::new(TASK_IMAGE_DIR)))
    else {
        return;
    };
    let redirect = |path: &Path| {
        if path == pin.executable {
            return launcher.to_path_buf();
        }
        path.strip_prefix(&pin.directory)
            .map(|suffix| directory.join(suffix))
            .unwrap_or_else(|_| path.to_path_buf())
    };
    for key in [
        crate::gh_shim_paths::GH_SHIMS_DIR_ENV,
        crate::gh_shim_paths::GH_SHIM_BINARY_ENV,
    ] {
        if let Some(value) = environment.get_mut(std::ffi::OsStr::new(key)) {
            *value = redirect(Path::new(value)).into_os_string();
        }
    }
    if let Some(value) = environment.get_mut(std::ffi::OsStr::new("PATH")) {
        let entries = std::env::split_paths(value)
            .map(|path| redirect(&path))
            .filter(|path| !is_dead_pin_path(path))
            .collect::<Vec<_>>();
        if let Ok(path) = std::env::join_paths(entries) {
            *value = path;
        }
    }
}

fn owner(name: &str) -> Option<(u32, u64)> {
    let (pid, start) = name.strip_prefix("aft-pinned-")?.split_once('-')?;
    Some((pid.parse().ok()?, start.parse().ok()?))
}

#[cfg(target_os = "macos")]
fn link_image(source: &Path, destination: &Path) -> io::Result<()> {
    // The privacy controls name the program that asks for protected
    // files (a removable volume, Documents, ...) by the path the kernel
    // reports for the responsible process's executable, and with several hard
    // links that can be any of them. Every task image then looked like a
    // different "aft", so an Allow never stuck and the prompt blocked the
    // volume until someone answered. Clone or copy the held image instead.
    let _ = (source, destination);
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "the daemon's executable is never hard-linked",
    ))
}

#[cfg(all(unix, not(target_os = "linux")))]
fn materialize(
    source_path: &Path,
    source: &mut std::fs::File,
    destination: &Path,
    link: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};
    match link(source_path, destination) {
        Ok(()) => {
            let held = source.metadata()?;
            let linked = std::fs::metadata(destination)?;
            if (held.dev(), held.ino()) != (linked.dev(), linked.ino()) {
                let _ = std::fs::remove_file(destination);
                return Err(io::Error::other("deployment image changed while pinning"));
            }
        }
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return Err(error),
        Err(_) => {
            // On APFS a clone of the held image is a separate file that shares
            // its blocks, so it costs no disk and keeps the signed bytes.
            #[cfg(target_os = "macos")]
            if clone_held_image(source, destination).is_ok() {
                return Ok(());
            }
            // The pin is never a link (`link_image`), and storage may be on
            // another volume. Stream the already-open image unchanged so
            // embedded code signatures on macOS remain valid.
            let mut output = crate::private_storage::executable_options()
                .write(true)
                .create_new(true)
                .open(destination)?;
            // Cloned startup handles share a cursor. Positional reads let
            // concurrent task copies and later repairs read the complete image.
            use std::io::Write;
            use std::os::unix::fs::FileExt;
            let mut offset = 0;
            let mut buffer = [0; 64 * 1024];
            loop {
                let count = match source.read_at(&mut buffer, offset) {
                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                    result => result?,
                };
                if count == 0 {
                    break;
                }
                output.write_all(&buffer[..count])?;
                offset += count as u64;
            }
            aft_store::sync::sync_all(&output, destination)?;
            output.set_permissions(std::fs::Permissions::from_mode(0o500))?;
        }
    }
    Ok(())
}

/// Run a newly created image once, so its first launch is paid here.
///
/// On macOS the pin is a new file, not another name for the running image,
/// and the first launch of a new executable can be slow (the system assesses
/// it, and a large debug build pays for its size). The gh shim's version
/// probe allows only two seconds, so without this a slow first launch would
/// refuse the shim and leave shells without `gh`. A failure here is only
/// logged: the probe still decides whether the image is usable.
#[cfg(target_os = "macos")]
fn warm_new_image(image: &Path) {
    use std::os::unix::process::CommandExt;
    use std::process::{Command, Stdio};
    const WARM_BUDGET: std::time::Duration = std::time::Duration::from_secs(30);
    let started = std::time::Instant::now();
    let mut child = match Command::new(image)
        .env_clear()
        .args(["gh-shim", "--shim-version"])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .process_group(0)
        .spawn()
    {
        Ok(child) => child,
        Err(error) => {
            log::warn!("pinned image first launch failed to start: {error}");
            return;
        }
    };
    loop {
        match child.try_wait() {
            Ok(Some(_)) => break,
            Ok(None) if started.elapsed() < WARM_BUDGET => {
                std::thread::sleep(std::time::Duration::from_millis(10))
            }
            _ => {
                // SAFETY: the child leads its own process group (spawned above).
                unsafe {
                    libc::kill(-(child.id() as i32), libc::SIGKILL);
                }
                let _ = child.wait();
                log::warn!(
                    "pinned image first launch did not finish within {}s",
                    WARM_BUDGET.as_secs()
                );
                return;
            }
        }
    }
    let elapsed = started.elapsed();
    if elapsed > std::time::Duration::from_secs(1) {
        log::info!("pinned image first launch took {}ms", elapsed.as_millis());
    }
}

/// Clone the held (already open) image into `destination` as a new file, then
/// make it owner-only like every other file under AFT's storage.
#[cfg(target_os = "macos")]
fn clone_held_image(source: &std::fs::File, destination: &Path) -> io::Result<()> {
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::PermissionsExt;
    use std::os::unix::io::AsRawFd;
    let target =
        std::ffi::CString::new(destination.as_os_str().as_bytes()).map_err(io::Error::other)?;
    // SAFETY: the descriptor is open for this call's duration and the path is
    // NUL-terminated. Cloning from the descriptor, not a path, copies the image
    // this process started from even if the deployment path was replaced.
    if unsafe { libc::fclonefileat(source.as_raw_fd(), libc::AT_FDCWD, target.as_ptr(), 0) } != 0 {
        return Err(io::Error::last_os_error());
    }
    if let Err(error) =
        std::fs::set_permissions(destination, std::fs::Permissions::from_mode(0o500))
    {
        let _ = std::fs::remove_file(destination);
        return Err(error);
    }
    Ok(())
}

/// Remove this daemon's private launch directory, including exits that skip Drop.
/// Startup cleanup handles crashes and any best-effort removal failures.
pub fn cleanup_at_exit() {
    if let Some(pin) = PINNED.get() {
        pin.cleanup_at_exit();
    }
}

/// The metadata of the executable image this process started from, even
/// after another binary was renamed over its path: on Linux the image the
/// kernel holds, on macOS the file opened at startup (see
/// [`capture_at_startup`]). Elsewhere a running executable cannot be
/// replaced, so its path is read. `None` when the image cannot be examined.
pub fn startup_image_metadata() -> Option<std::fs::Metadata> {
    #[cfg(target_os = "linux")]
    {
        std::fs::metadata(linux_image_path()).ok()
    }
    #[cfg(target_os = "macos")]
    {
        capture_at_startup();
        SOURCE.get()?.as_ref().ok()?.file.metadata().ok()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        std::env::current_exe().and_then(std::fs::metadata).ok()
    }
}

/// Return the daemon's startup pin, or normal executable discovery for standalone
/// and library-only hosts that have not initialized a pin.
pub fn path() -> io::Result<PathBuf> {
    // On Linux the task-local path is only for the task's environment. The
    // daemon always launches the private pin, not a mutable task artifact.
    #[cfg(not(target_os = "linux"))]
    if let Some(directory) = TASK_IMAGE.with(|slot| slot.borrow().clone()) {
        return Ok(directory.join(if cfg!(windows) { "aft.exe" } else { "aft" }));
    }
    if let Some(pin) = PINNED.get() {
        return pin.path();
    }
    std::env::current_exe()
}

/// A native profile may read and execute the task's exact launcher, not its
/// containing cache. Outside launch setup there is no task grant to add.
#[cfg(target_os = "linux")]
pub fn linux_task_pin() -> io::Result<Option<PathBuf>> {
    if TASK_IMAGE.with(|slot| slot.borrow().is_some()) {
        PINNED.get().map(PinnedExecutable::path).transpose()
    } else {
        Ok(None)
    }
}

pub fn shims_dir(storage: &Path) -> PathBuf {
    if let Some(directory) = TASK_IMAGE.with(|slot| slot.borrow().clone()) {
        return directory.join("shims");
    }
    match PINNED.get() {
        // A shared, mutable `shims/gh` could be retargeted by a second daemon
        // running a different build. Keep each server's PATH entry immutable.
        Some(pin) => pin.directory.join("shims"),
        None => storage.join(crate::gh_shim_paths::SHIMS_DIR_NAME),
    }
}

#[cfg(target_os = "linux")]
fn linux_image_path() -> PathBuf {
    // When a child shell resolves /proc/self/exe, it names the shell's image,
    // not AFT's. Use the serving PID for both the supervisor and the gh link.
    PathBuf::from(format!("/proc/{}/exe", std::process::id()))
}

#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod tests {
    use super::*;

    #[test]
    fn pinned_executable_unpinned_path_is_current_exe() {
        assert!(PINNED.get().is_none());
        assert_eq!(path().unwrap(), std::env::current_exe().unwrap());
    }

    #[test]
    fn pinned_executable_unpinned_shims_use_storage() {
        assert!(PINNED.get().is_none());
        let storage = tempfile::tempdir().unwrap();
        assert_eq!(
            shims_dir(storage.path()),
            storage.path().join(crate::gh_shim_paths::SHIMS_DIR_NAME)
        );
    }

    #[rustfmt::skip]
    test_support_visibility! {
    #[cfg_attr(test, test)]
    fn pinned_executable_cleanup_preserves_live_owner_and_unrelated_entries() {
        let storage = tempfile::tempdir().unwrap();
        let run = storage.path();
        let pid = std::process::id();
        let start = crate::process_identity::process_start_time_ms(pid).unwrap();
        let live = run.join(format!("aft-pinned-{pid}-{start}"));
        let reused = run.join(format!("aft-pinned-{pid}-{}", start - 1));
        let unrelated = run.join("operator-state");
        for directory in [&live, &reused, &unrelated] {
            std::fs::create_dir(directory).unwrap();
            std::fs::write(directory.join("aft"), b"image").unwrap();
        }
        cleanup(run).unwrap();
        assert!(live.join("aft").exists());
        assert!(!reused.exists(), "a reused PID must not retain an old pin");
        assert!(unrelated.join("aft").exists());
    }
    }

    #[cfg(unix)]
    #[test]
    fn pinned_executable_cleanup_preserves_another_live_process() {
        let mut child = std::process::Command::new("/bin/sleep")
            .arg("60")
            .spawn()
            .unwrap();
        let storage = tempfile::tempdir().unwrap();
        let pid = child.id();
        let start = crate::process_identity::process_start_time_ms(pid).unwrap();
        let directory = storage.path().join(format!("aft-pinned-{pid}-{start}"));
        std::fs::create_dir(&directory).unwrap();
        std::fs::write(directory.join("aft"), b"live image").unwrap();
        let result = cleanup(storage.path());
        let retained = directory.join("aft").exists();
        let alive = child.try_wait().unwrap().is_none();
        child.kill().unwrap();
        child.wait().unwrap();
        result.unwrap();
        assert!(
            alive && retained,
            "cleanup removed a live process's executable"
        );
        cleanup(storage.path()).unwrap();
        assert!(!directory.exists());
    }

    #[test]
    fn pinned_executable_cleanup_lease_overrides_mismatched_process_clock() {
        let storage = tempfile::tempdir().unwrap();
        let pid = std::process::id();
        let start = crate::process_identity::process_start_time_ms(pid).unwrap();
        let directory = storage
            .path()
            .join(format!("aft-pinned-{pid}-{}", start - 1));
        std::fs::create_dir(&directory).unwrap();
        let lease = owner_lock(&directory).unwrap();
        cleanup(storage.path()).unwrap();
        assert!(
            directory.exists(),
            "a held lease must override an apparent PID reuse"
        );
        drop(lease);
        cleanup(storage.path()).unwrap();
        assert!(!directory.exists());
    }

    #[cfg(unix)]
    #[test]
    fn pinned_executable_task_image_and_shim_outlive_daemon_pin() {
        let storage = tempfile::tempdir().unwrap();
        let task = tempfile::tempdir().unwrap();
        let pin = prepare(storage.path()).unwrap();
        std::fs::create_dir(pin.directory.join("shims")).unwrap();
        std::os::unix::fs::symlink(&pin.executable, pin.directory.join("shims/gh")).unwrap();
        let image = pin.task_image(task.path()).unwrap();
        pin.cleanup_at_exit();
        assert!(!pin.directory.exists());
        assert_eq!(
            std::fs::read_link(image.join("shims/gh")).unwrap(),
            image.join("aft")
        );
        let output = std::process::Command::new(image.join("shims/gh"))
            .args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        assert!(String::from_utf8_lossy(&output.stdout).contains("1 test"));
    }

    #[cfg(windows)]
    #[test]
    fn pinned_executable_windows_task_wrapper_outlives_daemon_pin() {
        let storage = tempfile::tempdir().unwrap();
        let task = tempfile::tempdir().unwrap();
        let pin = prepare(storage.path()).unwrap();
        std::fs::create_dir(pin.directory.join("shims")).unwrap();
        std::fs::write(
            pin.directory.join("shims/gh.cmd"),
            crate::gh_shim_paths::windows_gh_cmd(&pin.executable),
        )
        .unwrap();
        let image = pin.task_image(task.path()).unwrap();
        pin.cleanup_at_exit();
        assert!(!pin.directory.exists());
        assert_eq!(
            std::fs::read(image.join("shims/gh.cmd")).unwrap(),
            crate::gh_shim_paths::windows_gh_cmd(&image.join("aft.exe"))
        );
        assert!(image.join("aft.exe").is_file());
    }

    #[cfg(unix)]
    #[test]
    fn pinned_executable_missing_pin_is_repaired_from_complete_held_image() {
        use sha2::{Digest, Sha256};
        use std::io::Seek;
        let storage = tempfile::tempdir().unwrap();
        let pin = prepare(storage.path()).unwrap();
        let digest = |path: &Path| {
            let mut hash = Sha256::new();
            io::copy(&mut std::fs::File::open(path).unwrap(), &mut hash).unwrap();
            hash.finalize()
        };
        let original = digest(&pin.executable);
        pin.state
            .lock()
            .unwrap()
            .source
            .seek(io::SeekFrom::End(0))
            .unwrap();
        std::fs::remove_dir_all(&pin.directory).unwrap();
        #[cfg(target_os = "linux")]
        std::fs::remove_file(&pin.executable).unwrap();
        assert_eq!(pin.path().unwrap(), pin.executable);
        assert_eq!(original, digest(&pin.executable));
        assert!(pin.directory.join(OWNER_LOCK).exists());
        pin.cleanup_at_exit();
    }

    #[cfg(unix)]
    #[test]
    fn pinned_executable_cleanup_does_not_follow_symlinks() {
        let storage = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let name = format!("aft-pinned-{}-1", std::process::id());
        let link = storage.path().join(name);
        std::fs::write(outside.path().join("aft"), b"keep").unwrap();
        std::os::unix::fs::symlink(outside.path(), &link).unwrap();
        cleanup(storage.path()).unwrap();
        assert!(link.is_symlink());
        assert_eq!(std::fs::read(outside.path().join("aft")).unwrap(), b"keep");
    }

    #[cfg(unix)]
    #[test]
    fn pinned_executable_refuses_redirected_run_directory() {
        let storage = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        std::os::unix::fs::symlink(outside.path(), storage.path().join("run")).unwrap();
        assert!(prepare(storage.path()).is_err());
        assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0);
    }

    #[cfg(all(unix, not(target_os = "linux")))]
    #[test]
    fn pinned_executable_cross_volume_fallback_preserves_signed_bytes_and_executes() {
        use sha2::{Digest, Sha256};
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let storage = tempfile::tempdir().unwrap();
        let executable = std::env::current_exe().unwrap();
        let mut source = std::fs::File::open(&executable).unwrap();
        let destination = storage.path().join("aft");
        materialize(&executable, &mut source, &destination, |_, _| {
            Err(io::Error::from_raw_os_error(libc::EXDEV))
        })
        .unwrap();
        let digest = |path: &Path| {
            let mut file = std::fs::File::open(path).unwrap();
            let mut hash = Sha256::new();
            io::copy(&mut file, &mut hash).unwrap();
            hash.finalize()
        };
        assert_eq!(digest(&executable), digest(&destination));
        let copied = std::fs::metadata(&destination).unwrap();
        assert_ne!(source.metadata().unwrap().ino(), copied.ino());
        assert_eq!(copied.permissions().mode() & 0o777, 0o500);
        let output = std::process::Command::new(&destination)
            .args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        assert!(String::from_utf8_lossy(&output.stdout).contains("1 test"));
    }

    /// The daemon's own executable keeps exactly one name: its pin is a separate
    /// file, so macOS cannot report the daemon by a pin or task-image path.
    #[cfg(target_os = "macos")]
    #[test]
    fn pinned_executable_pin_is_a_separate_file_from_the_running_image() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let storage = tempfile::tempdir().unwrap();
        let executable = storage.path().join("deploy");
        std::fs::copy(std::env::current_exe().unwrap(), &executable).unwrap();
        let mut source = std::fs::File::open(&executable).unwrap();
        let destination = storage.path().join("aft");
        materialize(&executable, &mut source, &destination, link_image).unwrap();
        let held = source.metadata().unwrap();
        let pinned = std::fs::metadata(&destination).unwrap();
        assert_ne!(held.ino(), pinned.ino(), "the pin is a hard link");
        assert_eq!(held.nlink(), 1, "the running image gained a second name");
        assert_eq!(pinned.permissions().mode() & 0o777, 0o500);
        assert_eq!(
            std::fs::read(&executable).unwrap(),
            std::fs::read(&destination).unwrap()
        );
        let output = std::process::Command::new(&destination)
            .args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
    }

    /// Linking the running image, even once, changes its inode change time and
    /// link count. Keep the storage on the test binary's own mount so that a
    /// hard link would succeed if `prepare` or `task_image` made one.
    #[cfg(target_os = "linux")]
    #[test]
    fn pinned_executable_prepare_and_task_image_leave_the_running_image_unchanged() {
        use std::os::unix::fs::MetadataExt;
        let image = linux_image_path();
        let beside = std::env::current_exe().unwrap();
        let beside = beside.parent().unwrap();
        let storage = tempfile::tempdir_in(beside).unwrap();
        let task = tempfile::tempdir_in(beside).unwrap();
        let before = std::fs::metadata(&image).unwrap();
        let pin = prepare(storage.path()).unwrap();
        pin.task_image(task.path()).unwrap();
        let pinned = std::fs::metadata(&pin.executable).unwrap();
        let after = std::fs::metadata(&image).unwrap();
        assert_ne!(
            (before.dev(), before.ino()),
            (pinned.dev(), pinned.ino()),
            "the pin is a hard link to the running image"
        );
        assert_eq!(
            before.nlink(),
            after.nlink(),
            "the running image gained a name"
        );
        assert_eq!(
            (before.ctime(), before.ctime_nsec()),
            (after.ctime(), after.ctime_nsec()),
            "the running image's inode change time moved"
        );
        pin.cleanup_at_exit();
    }

    #[cfg(all(unix, not(target_os = "linux")))]
    #[test]
    fn pinned_executable_hard_link_holds_original_inode_after_replacement() {
        use std::os::unix::fs::MetadataExt;
        let storage = tempfile::tempdir().unwrap();
        let source_path = storage.path().join("deploy");
        let destination = storage.path().join("aft");
        std::fs::write(&source_path, b"original image").unwrap();
        let mut source = std::fs::File::open(&source_path).unwrap();
        materialize(&source_path, &mut source, &destination, |from, to| {
            std::fs::hard_link(from, to)
        })
        .unwrap();
        assert_eq!(
            source.metadata().unwrap().ino(),
            destination.metadata().unwrap().ino()
        );
        let replacement = storage.path().join("new-build");
        std::fs::write(&replacement, b"replacement image").unwrap();
        std::fs::rename(replacement, &source_path).unwrap();
        assert_eq!(std::fs::read(&destination).unwrap(), b"original image");
        assert_eq!(std::fs::read(&source_path).unwrap(), b"replacement image");
    }
}