shepherd-cli 6.6.1

The canonical shepherd command-line interface over the per-project registry, run artifacts, and sprint pipeline.
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
/*
    Appellation: execution-context <module>
    Created At: 2026.08.14
    Contrib: @FL03
*/
//! Filesystem, environment, git, clock, identifier, and stdio discovery.
//!
//! The core receives only already-read configuration layers. This module is
//! the single host boundary that turns ambient machine state into one explicit
//! value shared by every command.

use std::{
    collections::BTreeSet,
    env,
    ffi::{OsStr, OsString},
    fs,
    io::{self, Write},
    path::{Path, PathBuf},
    str::FromStr,
    sync::atomic::{AtomicU64, Ordering},
    time::{SystemTime, UNIX_EPOCH},
};

#[cfg(unix)]
use std::io::Read;

use shepherd::{
    Harness, ShepherdConfig,
    loader::{self, ConfigContext, ConfigSource},
};

use crate::dispatch_service::trusted_git_executable;

/// Stable CLI output selection.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    strum::AsRefStr,
    strum::Display,
    strum::EnumCount,
    strum::EnumIs,
    strum::EnumString,
    strum::IntoStaticStr,
    strum::VariantNames,
)]
#[strum(ascii_case_insensitive, serialize_all = "snake_case")]
pub enum OutputFormat {
    #[default]
    Text,
    Json,
}

/// Host facts supplied before context resolution.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContextInputs {
    pub start_dir: PathBuf,
    pub primary_fallback: Option<PathBuf>,
    pub shepherd_home: Option<PathBuf>,
    pub home_dir: Option<PathBuf>,
    pub active_harness: Option<Harness>,
    pub explicit_config: Option<PathBuf>,
    pub output_format: OutputFormat,
    pub verbosity: u8,
}

impl Default for ContextInputs {
    fn default() -> Self {
        Self {
            start_dir: PathBuf::from("."),
            primary_fallback: None,
            shepherd_home: None,
            home_dir: None,
            active_harness: None,
            explicit_config: None,
            output_format: OutputFormat::Text,
            verbosity: 0,
        }
    }
}

impl ContextInputs {
    /// Read supported host inputs without creating a directory.
    pub fn from_environment(start_dir: impl Into<PathBuf>) -> Result<Self, ContextError> {
        Self::from_environment_with(start_dir, &SystemEnvironment)
    }

    /// Read host inputs through an injectable environment boundary.
    pub fn from_environment_with(
        start_dir: impl Into<PathBuf>,
        environment: &dyn ContextEnvironment,
    ) -> Result<Self, ContextError> {
        let shepherd_home = environment_path(environment, "SHEPHERD_HOME");
        let home_dir = environment_path(environment, "HOME");
        let active_harness = resolve_environment_harness(environment)?;
        Ok(Self {
            start_dir: start_dir.into(),
            shepherd_home,
            home_dir,
            active_harness,
            ..Self::default()
        })
    }
}

/// Read-only environment operations required during host discovery.
pub trait ContextEnvironment {
    fn var_os(&self, key: &OsStr) -> Option<OsString>;
}

/// Production environment implementation. It never mutates process state.
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemEnvironment;

impl ContextEnvironment for SystemEnvironment {
    fn var_os(&self, key: &OsStr) -> Option<OsString> {
        env::var_os(key)
    }
}

/// Injectable wall clock.
pub trait Clock: Send + Sync + core::fmt::Debug {
    fn now_unix_millis(&self) -> i64;
}

/// Injectable identifier sequence.
pub trait IdentifierSource: Send + core::fmt::Debug {
    fn next_id(&mut self) -> String;
}

/// Injectable command I/O boundary.
pub trait IoBoundary: Send + core::fmt::Debug {
    fn read_stdin(&mut self, buffer: &mut String) -> io::Result<usize>;
    fn write_stdout(&mut self, bytes: &[u8]) -> io::Result<()>;
    fn write_stderr(&mut self, bytes: &[u8]) -> io::Result<()>;
}

/// Nondeterministic runtime sources carried by [`ExecutionContext`].
#[derive(Debug)]
pub struct RuntimeBindings {
    clock: Box<dyn Clock>,
    identifiers: Box<dyn IdentifierSource>,
    io: Box<dyn IoBoundary>,
}

impl RuntimeBindings {
    pub fn new(
        clock: Box<dyn Clock>,
        identifiers: Box<dyn IdentifierSource>,
        io: Box<dyn IoBoundary>,
    ) -> Self {
        Self {
            clock,
            identifiers,
            io,
        }
    }

    pub fn system() -> Self {
        Self::new(
            Box::new(SystemClock),
            Box::new(SystemIdentifiers),
            Box::new(SystemIo),
        )
    }
}

/// Filesystem and git operations required during resolution.
pub trait ContextHost {
    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf>;
    fn git_rev_parse(&self, cwd: &Path, argument: &str) -> io::Result<PathBuf>;
    fn read_optional(&self, path: &Path) -> io::Result<Option<String>>;

    /// Inspect a path without following its final symlink component.
    ///
    /// The default is the production implementation. Test hosts can keep
    /// implementing only the older discovery methods while still receiving
    /// the fail-closed symlink check.
    fn symlink_metadata(&self, path: &Path) -> io::Result<fs::Metadata> {
        fs::symlink_metadata(path)
    }
}

/// Production host implementation. It never writes.
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemHost;

impl ContextHost for SystemHost {
    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
        fs::canonicalize(path)
    }

    fn git_rev_parse(&self, cwd: &Path, argument: &str) -> io::Result<PathBuf> {
        let git = trusted_git_executable().map_err(io::Error::other)?;
        parse_git_output(
            std::process::Command::new(git)
                .env_clear()
                .current_dir(cwd)
                .args(["rev-parse", "--path-format=absolute", argument])
                .output()?,
        )
    }

    fn read_optional(&self, path: &Path) -> io::Result<Option<String>> {
        match fs::read_to_string(path) {
            Ok(contents) => Ok(Some(contents)),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(error),
        }
    }
}

/// An opened primary project used as the identity for explicit dispatch.
///
/// Unix discovery and authorization resolve every project path with
/// descriptor-relative, no-follow opens. Linked worktree metadata is read
/// through the supplied worktree descriptor, then authority moves to the
/// descriptor of its shared primary checkout.
#[cfg(unix)]
#[derive(Debug)]
pub struct ProjectRootAnchor {
    primary: DescriptorRoot,
    git_dir: Option<DescriptorRoot>,
    git_common_dir: Option<DescriptorRoot>,
}

#[cfg(unix)]
#[derive(Debug)]
struct DescriptorRoot {
    path: PathBuf,
    directory: std::os::fd::OwnedFd,
}

#[cfg(unix)]
impl DescriptorRoot {
    fn open(path: &Path) -> io::Result<Self> {
        use rustix::fs::{Mode, OFlags, open, openat};

        validate_absolute_path(path)?;
        let mut directory = open(
            "/",
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
            Mode::empty(),
        )
        .map_err(io::Error::from)?;
        let mut traversed = PathBuf::from("/");
        for component in path.components() {
            let std::path::Component::Normal(name) = component else {
                continue;
            };
            traversed.push(name);
            directory = openat(
                &directory,
                name,
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
                Mode::empty(),
            )
            .map_err(|error| project_anchor_error(&traversed, error))?;
        }
        Ok(Self {
            path: path.to_path_buf(),
            directory,
        })
    }

    fn from_directory(path: PathBuf, directory: std::os::fd::OwnedFd) -> Self {
        Self { path, directory }
    }

    fn duplicate(&self) -> io::Result<Self> {
        Ok(Self {
            path: self.path.clone(),
            directory: rustix::io::dup(&self.directory).map_err(io::Error::from)?,
        })
    }

    fn relative(&self, path: &Path) -> io::Result<PathBuf> {
        let relative = path.strip_prefix(&self.path).map_err(|_| {
            io::Error::new(
                io::ErrorKind::PermissionDenied,
                "path is outside the descriptor root",
            )
        })?;
        validate_relative_path(relative)?;
        Ok(relative.to_path_buf())
    }

    fn open_any(&self, path: &Path) -> io::Result<std::os::fd::OwnedFd> {
        self.open_relative(&self.relative(path)?, false)
    }

    fn open_directory(&self, path: &Path) -> io::Result<std::os::fd::OwnedFd> {
        self.open_relative(&self.relative(path)?, true)
    }

    fn open_relative(
        &self,
        relative: &Path,
        final_directory: bool,
    ) -> io::Result<std::os::fd::OwnedFd> {
        use rustix::fs::{Mode, OFlags, openat};

        validate_relative_path(relative)?;
        let mut directory = rustix::io::dup(&self.directory).map_err(io::Error::from)?;
        let components = relative.components().collect::<Vec<_>>();
        for (index, component) in components.iter().enumerate() {
            let std::path::Component::Normal(name) = component else {
                unreachable!("validated relative paths contain only normal components");
            };
            let final_component = index + 1 == components.len();
            let mut flags = OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK;
            if !final_component || final_directory {
                flags |= OFlags::DIRECTORY;
            }
            directory = openat(&directory, *name, flags, Mode::empty())
                .map_err(|error| project_anchor_error(&self.path.join(relative), error))?;
        }
        Ok(directory)
    }

    fn read_optional(&self, path: &Path, limit: usize) -> io::Result<Option<Vec<u8>>> {
        match self.open_any(path) {
            Ok(descriptor) => read_bounded_regular(descriptor, path, limit).map(Some),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(error),
        }
    }
}

#[cfg(unix)]
impl ProjectRootAnchor {
    const GIT_POINTER_LIMIT: usize = 4_096;

    pub fn open(root: impl AsRef<Path>) -> io::Result<Self> {
        let explicit = DescriptorRoot::open(root.as_ref())?;
        let git_marker = explicit.path.join(".git");
        let marker = match explicit.open_any(&git_marker) {
            Ok(marker) => Some(marker),
            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
            Err(error) => return Err(error),
        };
        let Some(marker) = marker else {
            return Ok(Self {
                primary: explicit,
                git_dir: None,
                git_common_dir: None,
            });
        };
        let metadata =
            fs::File::from(rustix::io::dup(&marker).map_err(io::Error::from)?).metadata()?;
        if metadata.is_dir() {
            let git_dir = DescriptorRoot::from_directory(git_marker, marker);
            return Ok(Self {
                primary: explicit,
                git_common_dir: Some(git_dir.duplicate()?),
                git_dir: Some(git_dir),
            });
        }
        if !metadata.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "project .git marker is neither a directory nor a regular file",
            ));
        }

        let pointer = read_bounded_regular(marker, &git_marker, Self::GIT_POINTER_LIMIT)?;
        let git_dir_path = parse_git_pointer(&explicit.path, &pointer)?;
        let git_dir = DescriptorRoot::open(&git_dir_path)?;
        let common_path = match git_dir
            .read_optional(&git_dir.path.join("commondir"), Self::GIT_POINTER_LIMIT)?
        {
            Some(contents) => {
                let value = bounded_text_line(&contents, "commondir")?;
                Some(normalize_absolute(&git_dir.path, value)?)
            }
            None => None,
        };

        let Some(common_path) = common_path else {
            return Ok(Self {
                primary: explicit,
                git_common_dir: Some(git_dir.duplicate()?),
                git_dir: Some(git_dir),
            });
        };
        if common_path.file_name().is_none_or(|name| name != ".git") {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "linked worktree common directory does not identify a primary checkout",
            ));
        }
        let common = DescriptorRoot::open(&common_path)?;
        let primary_path = common_path.parent().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "Git common directory has no parent",
            )
        })?;
        let primary = DescriptorRoot::open(primary_path)?;
        let primary_git = primary.open_directory(&primary.path.join(".git"))?;
        if !same_file(&primary_git, &common.directory)? {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "linked worktree common directory does not match the primary checkout",
            ));
        }
        Ok(Self {
            primary,
            git_dir: Some(git_dir),
            git_common_dir: Some(common),
        })
    }

    #[must_use]
    pub fn root(&self) -> &Path {
        &self.primary.path
    }

    /// Stable Unix device/inode identity for cross-process project custody.
    pub fn filesystem_id(&self) -> io::Result<String> {
        let stat = rustix::fs::fstat(&self.primary.directory).map_err(io::Error::from)?;
        Ok(format!("unix:{:x}:{:x}", stat.st_dev, stat.st_ino))
    }

    /// Open a project directory relative to the retained primary descriptor.
    pub fn open_directory(&self, path: &Path) -> io::Result<std::os::fd::OwnedFd> {
        self.primary.open_directory(path)
    }

    /// Read one bounded regular project file relative to the retained primary descriptor.
    pub fn read_regular(&self, path: &Path, limit: usize) -> io::Result<Vec<u8>> {
        let descriptor = self.primary.open_any(path)?;
        read_bounded_regular(descriptor, path, limit)
    }

    fn canonical_descriptor_path(&self, path: &Path) -> io::Result<bool> {
        if path.starts_with(&self.primary.path) {
            drop(self.primary.open_any(path)?);
            return Ok(true);
        }
        for root in [&self.git_dir, &self.git_common_dir].into_iter().flatten() {
            if path == root.path {
                drop(root.duplicate()?);
                return Ok(true);
            }
        }
        Ok(false)
    }
}

#[cfg(unix)]
impl ContextHost for ProjectRootAnchor {
    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
        if self.canonical_descriptor_path(path)? {
            Ok(path.to_path_buf())
        } else {
            SystemHost.canonicalize(path)
        }
    }

    fn git_rev_parse(&self, cwd: &Path, argument: &str) -> io::Result<PathBuf> {
        if cwd != self.primary.path {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "Git discovery escaped the anchored primary project",
            ));
        }
        match argument {
            "--show-toplevel" if self.git_dir.is_some() => Ok(self.primary.path.clone()),
            "--git-common-dir" => self
                .git_common_dir
                .as_ref()
                .map(|root| root.path.clone())
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::NotFound,
                        "anchored project has no Git common directory",
                    )
                }),
            "--git-dir" => self
                .git_dir
                .as_ref()
                .map(|root| root.path.clone())
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::NotFound,
                        "anchored project has no Git directory",
                    )
                }),
            "--show-toplevel" => Err(io::Error::new(
                io::ErrorKind::NotFound,
                "anchored project is not a Git checkout",
            )),
            _ => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "unsupported anchored Git query",
            )),
        }
    }

    fn read_optional(&self, path: &Path) -> io::Result<Option<String>> {
        if !path.starts_with(&self.primary.path) {
            return SystemHost.read_optional(path);
        }
        self.primary
            .read_optional(path, 1_048_576)?
            .map(|contents| {
                String::from_utf8(contents).map_err(|_| {
                    io::Error::new(
                        io::ErrorKind::InvalidData,
                        "project configuration is not UTF-8",
                    )
                })
            })
            .transpose()
    }

    fn symlink_metadata(&self, path: &Path) -> io::Result<fs::Metadata> {
        if path.starts_with(&self.primary.path) {
            fs::File::from(self.primary.open_any(path)?).metadata()
        } else {
            SystemHost.symlink_metadata(path)
        }
    }
}

#[cfg(unix)]
fn validate_absolute_path(path: &Path) -> io::Result<()> {
    if !path.is_absolute() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "explicit project root must be absolute",
        ));
    }
    if path.components().any(|component| {
        !matches!(
            component,
            std::path::Component::RootDir | std::path::Component::Normal(_)
        )
    }) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "explicit project root must already be canonical",
        ));
    }
    Ok(())
}

#[cfg(unix)]
fn validate_relative_path(path: &Path) -> io::Result<()> {
    if path.is_absolute()
        || path
            .components()
            .any(|component| !matches!(component, std::path::Component::Normal(_)))
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "descriptor-relative path must contain only normal components",
        ));
    }
    Ok(())
}

#[cfg(unix)]
fn read_bounded_regular(
    descriptor: std::os::fd::OwnedFd,
    path: &Path,
    limit: usize,
) -> io::Result<Vec<u8>> {
    let file = fs::File::from(descriptor);
    if !file.metadata()?.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "descriptor target is not a regular file: {}",
                path.display()
            ),
        ));
    }
    let mut contents = Vec::new();
    file.take(u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1))
        .read_to_end(&mut contents)?;
    if contents.len() > limit {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "descriptor target exceeds {limit} bytes: {}",
                path.display()
            ),
        ));
    }
    Ok(contents)
}

#[cfg(unix)]
fn parse_git_pointer(base: &Path, contents: &[u8]) -> io::Result<PathBuf> {
    let line = bounded_text_line(contents, ".git")?;
    let target = line.strip_prefix("gitdir: ").ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "project .git file has no gitdir pointer",
        )
    })?;
    normalize_absolute(base, target)
}

#[cfg(unix)]
fn bounded_text_line<'a>(contents: &'a [u8], label: &str) -> io::Result<&'a str> {
    let value = std::str::from_utf8(contents)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, format!("{label} is not UTF-8")))?
        .trim_end_matches(['\r', '\n']);
    if value.is_empty() || value.contains(['\r', '\n', '\0']) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{label} must contain one non-empty line"),
        ));
    }
    Ok(value)
}

#[cfg(unix)]
fn normalize_absolute(base: &Path, value: &str) -> io::Result<PathBuf> {
    let value = Path::new(value);
    let candidate = if value.is_absolute() {
        value.to_path_buf()
    } else {
        base.join(value)
    };
    let mut normalized = PathBuf::from("/");
    for component in candidate.components() {
        match component {
            std::path::Component::RootDir => normalized = PathBuf::from("/"),
            std::path::Component::CurDir => {}
            std::path::Component::Normal(name) => normalized.push(name),
            std::path::Component::ParentDir => {
                if !normalized.pop() {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "Git metadata path escapes the filesystem root",
                    ));
                }
            }
            std::path::Component::Prefix(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "Git metadata path has an unsupported prefix",
                ));
            }
        }
    }
    validate_absolute_path(&normalized)?;
    Ok(normalized)
}

#[cfg(unix)]
fn same_file(left: &std::os::fd::OwnedFd, right: &std::os::fd::OwnedFd) -> io::Result<bool> {
    let left = rustix::fs::fstat(left).map_err(io::Error::from)?;
    let right = rustix::fs::fstat(right).map_err(io::Error::from)?;
    Ok(left.st_dev == right.st_dev && left.st_ino == right.st_ino)
}

#[cfg(unix)]
fn project_anchor_error(path: &Path, error: rustix::io::Errno) -> io::Error {
    match error {
        rustix::io::Errno::LOOP => io::Error::other(format!(
            "explicit project path contains a symlink: {}",
            path.display()
        )),
        rustix::io::Errno::NOTDIR => io::Error::other(format!(
            "explicit project path component is not a directory: {}",
            path.display()
        )),
        _ => io::Error::from(error),
    }
}

#[cfg(not(unix))]
#[derive(Debug)]
pub struct ProjectRootAnchor {
    root: PathBuf,
}

#[cfg(not(unix))]
impl ProjectRootAnchor {
    pub fn open(root: impl AsRef<Path>) -> io::Result<Self> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            format!(
                "explicit project binding requires handle-relative reparse-point-safe traversal on this platform: {}",
                root.as_ref().display()
            ),
        ))
    }

    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn filesystem_id(&self) -> io::Result<String> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "explicit project filesystem identity unavailable",
        ))
    }

    pub fn read_regular(&self, path: &Path, _limit: usize) -> io::Result<Vec<u8>> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            format!("explicit project anchor unavailable: {}", path.display()),
        ))
    }
}

#[cfg(not(unix))]
impl ContextHost for ProjectRootAnchor {
    fn canonicalize(&self, _path: &Path) -> io::Result<PathBuf> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "explicit project anchor unavailable",
        ))
    }

    fn git_rev_parse(&self, _cwd: &Path, _argument: &str) -> io::Result<PathBuf> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "explicit project anchor unavailable",
        ))
    }

    fn read_optional(&self, _path: &Path) -> io::Result<Option<String>> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "explicit project anchor unavailable",
        ))
    }
}

fn parse_git_output(output: std::process::Output) -> io::Result<PathBuf> {
    if !output.status.success() {
        return Err(io::Error::other(
            "git rev-parse did not resolve a repository",
        ));
    }
    let value = String::from_utf8(output.stdout)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "git returned non-UTF-8"))?;
    let value = value.trim();
    if value.is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "git returned an empty path",
        ));
    }
    Ok(PathBuf::from(value))
}

/// Context resolution failure.
#[derive(Debug, thiserror::Error)]
pub enum ContextError {
    #[error("SHEPHERD_HARNESS must name a supported harness")]
    InvalidHarness,
    #[error("cannot resolve primary repository root: {0}")]
    Primary(String),
    #[error("cannot read configuration candidate {path}: {source}")]
    ReadConfig {
        path: PathBuf,
        #[source]
        source: io::Error,
    },
    #[error("configuration candidate is not canonical: {0}")]
    NonCanonicalCandidate(PathBuf),
    #[error("explicit configuration path is not a canonical shepherd candidate: {0}")]
    NonCanonicalConfig(PathBuf),
    #[error("explicit configuration candidate does not exist: {0}")]
    MissingExplicitConfig(PathBuf),
    #[error("cannot resolve explicit configuration candidate {path}: {source}")]
    ResolveExplicitConfig {
        path: PathBuf,
        #[source]
        source: io::Error,
    },
    #[error("cannot resolve shepherd user home {path}: {source}")]
    ResolveUserHome {
        path: PathBuf,
        #[source]
        source: io::Error,
    },
    #[error("shepherd user home must not overlap the project namespace")]
    UserHomeOverlap,
    #[error("{key}: resolved project path is not canonical: {path}")]
    NonCanonicalProjectPath { key: &'static str, path: PathBuf },
    #[error("cannot resolve {key} project path {path}: {source}")]
    ResolveProjectPath {
        key: &'static str,
        path: PathBuf,
        #[source]
        source: io::Error,
    },
    #[error(transparent)]
    Config(#[from] shepherd::Error),
}

fn resolve_environment_harness(
    environment: &dyn ContextEnvironment,
) -> Result<Option<Harness>, ContextError> {
    if let Some(raw) = environment.var_os(OsStr::new("SHEPHERD_HARNESS"))
        && !raw.is_empty()
    {
        let value = raw.to_str().ok_or(ContextError::InvalidHarness)?.trim();
        if !value.is_empty() {
            return Harness::from_str(value)
                .map(Some)
                .map_err(|_| ContextError::InvalidHarness);
        }
    }
    if environment_value_is_present(environment, "CLAUDECODE")
        || environment_value_is_present(environment, "CLAUDE_PLUGIN_ROOT")
    {
        return Ok(Some(Harness::ClaudeCode));
    }
    if environment_value_is_present(environment, "CODEX_HOME") {
        return Ok(Some(Harness::Codex));
    }
    Ok(None)
}

fn environment_value_is_present(environment: &dyn ContextEnvironment, key: &str) -> bool {
    environment
        .var_os(OsStr::new(key))
        .is_some_and(|value| !value.is_empty())
}

fn environment_path(environment: &dyn ContextEnvironment, key: &str) -> Option<PathBuf> {
    environment
        .var_os(OsStr::new(key))
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
}

/// All resolved machine facts required by CLI commands.
pub struct ExecutionContext {
    /// Canonical checkout or linked-worktree root where this process may act.
    /// Durable Shepherd state remains under [`Self::primary_root`].
    pub workspace_root: PathBuf,
    pub primary_root: PathBuf,
    pub namespace: PathBuf,
    pub docs_root: PathBuf,
    pub ctx_root: PathBuf,
    pub runs_root: PathBuf,
    pub registry_path: PathBuf,
    pub registry_lock_path: PathBuf,
    pub project_id_path: PathBuf,
    pub dups_registry_path: PathBuf,
    pub user_home: Option<PathBuf>,
    pub active_harness: Option<Harness>,
    pub explicit_config: Option<PathBuf>,
    pub config: ShepherdConfig,
    pub config_sources: Vec<ConfigSource>,
    /// Dotted keys (e.g. `"models.root"`) some merged config layer set
    /// explicitly. Carried straight from
    /// `LoadedConfig::explicit_keys` so a caller can
    /// tell "a layer set this key" from "the merged value happens to equal
    /// the default" without re-reading or re-parsing any configuration file.
    pub explicit_keys: BTreeSet<String>,
    pub output_format: OutputFormat,
    pub verbosity: u8,
    runtime: RuntimeBindings,
}

impl core::fmt::Debug for ExecutionContext {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("ExecutionContext")
            .field("workspace_root", &self.workspace_root)
            .field("primary_root", &self.primary_root)
            .field("namespace", &self.namespace)
            .field("user_home", &self.user_home)
            .field("active_harness", &self.active_harness)
            .field("explicit_config", &self.explicit_config)
            .field("config_sources", &self.config_sources)
            .field("explicit_keys", &self.explicit_keys)
            .field("output_format", &self.output_format)
            .field("verbosity", &self.verbosity)
            .finish_non_exhaustive()
    }
}

impl ExecutionContext {
    /// Resolve using production host and runtime boundaries.
    pub fn discover(inputs: ContextInputs) -> Result<Self, ContextError> {
        Self::resolve_with(inputs, &SystemHost, RuntimeBindings::system())
    }

    /// Resolve only for a layout-v5 migration.
    ///
    /// The migration has to read the retired fields it will remove. Every
    /// regular command remains on [`Self::discover`] and therefore rejects
    /// them through the ordinary strict loader.
    pub fn discover_for_layout_v5_migration(inputs: ContextInputs) -> Result<Self, ContextError> {
        Self::resolve_with_loader(inputs, &SystemHost, RuntimeBindings::system(), true)
    }

    /// Resolve with every nondeterministic operation injected.
    pub fn resolve_with(
        inputs: ContextInputs,
        host: &dyn ContextHost,
        runtime: RuntimeBindings,
    ) -> Result<Self, ContextError> {
        Self::resolve_with_loader(inputs, host, runtime, false)
    }

    fn resolve_with_loader(
        inputs: ContextInputs,
        host: &dyn ContextHost,
        runtime: RuntimeBindings,
        layout_v5_migration: bool,
    ) -> Result<Self, ContextError> {
        let (primary_root, workspace_root) = resolve_project_roots(&inputs, host)?;
        let user_home = resolve_user_home(&inputs, &primary_root, host)?;
        let config_context = ConfigContext {
            primary_root: primary_root.clone(),
            user_home: user_home.clone(),
            harness: inputs.active_harness,
        };
        let candidates = loader::candidates(&config_context);
        let explicit_requested = inputs.explicit_config.as_ref().map(|path| {
            if path.is_absolute() {
                path.clone()
            } else {
                primary_root.join(path)
            }
        });

        let explicit_config = if let Some(explicit) = explicit_requested {
            if !candidates
                .iter()
                .any(|candidate| candidate.path == explicit)
            {
                return Err(ContextError::NonCanonicalConfig(explicit));
            }
            let resolved = match host.canonicalize(&explicit) {
                Ok(resolved) => resolved,
                Err(error) if error.kind() == io::ErrorKind::NotFound => {
                    return Err(ContextError::MissingExplicitConfig(explicit));
                }
                Err(source) => {
                    return Err(ContextError::ResolveExplicitConfig {
                        path: explicit,
                        source,
                    });
                }
            };
            if resolved != explicit {
                return Err(ContextError::NonCanonicalCandidate(explicit));
            }
            Some(resolved)
        } else {
            None
        };

        let selected: Vec<PathBuf> = if let Some(explicit) = &explicit_config {
            vec![explicit.clone()]
        } else {
            candidates
                .into_iter()
                .map(|candidate| candidate.path)
                .collect()
        };

        let mut contents = Vec::new();
        for path in selected {
            let canonical = match host.canonicalize(&path) {
                Ok(canonical) if canonical == path => Some(canonical),
                Ok(_) => return Err(ContextError::NonCanonicalCandidate(path)),
                Err(error) if error.kind() == io::ErrorKind::NotFound => None,
                Err(source) => {
                    return Err(ContextError::ReadConfig {
                        path: path.clone(),
                        source,
                    });
                }
            };
            let Some(canonical) = canonical else {
                if explicit_config.is_some() {
                    return Err(ContextError::MissingExplicitConfig(path));
                }
                continue;
            };
            match host
                .read_optional(&canonical)
                .map_err(|source| ContextError::ReadConfig {
                    path: canonical.clone(),
                    source,
                })? {
                Some(contents_value) => contents.push((canonical, contents_value)),
                None if explicit_config.is_some() => {
                    return Err(ContextError::MissingExplicitConfig(canonical));
                }
                None => {}
            }
        }

        let layers = contents
            .iter()
            .map(|(path, contents)| (path.as_path(), contents.as_str()));
        let loaded = if layout_v5_migration {
            loader::load_for_layout_v5_migration(layers)?
        } else {
            loader::load(layers)?
        };
        let paths = loaded.config.resolve_paths(&primary_root)?;
        validate_resolved_project_paths(host, &paths)?;

        Ok(Self {
            workspace_root,
            primary_root,
            namespace: paths.namespace,
            docs_root: paths.docs,
            ctx_root: paths.ctx,
            runs_root: paths.runs,
            registry_path: paths.registry,
            registry_lock_path: paths.registry_lock,
            project_id_path: paths.project_id,
            dups_registry_path: paths.dups_registry,
            user_home,
            active_harness: inputs.active_harness,
            explicit_config,
            config: loaded.config,
            config_sources: loaded.sources,
            explicit_keys: loaded.explicit_keys,
            output_format: inputs.output_format,
            verbosity: inputs.verbosity,
            runtime,
        })
    }

    pub fn now_unix_millis(&self) -> i64 {
        self.runtime.clock.now_unix_millis()
    }

    pub fn next_id(&mut self) -> String {
        self.runtime.identifiers.next_id()
    }

    pub fn read_stdin(&mut self, buffer: &mut String) -> io::Result<usize> {
        self.runtime.io.read_stdin(buffer)
    }

    pub fn write_stdout(&mut self, bytes: &[u8]) -> io::Result<()> {
        self.runtime.io.write_stdout(bytes)
    }

    pub fn write_stderr(&mut self, bytes: &[u8]) -> io::Result<()> {
        self.runtime.io.write_stderr(bytes)
    }
}

fn validate_resolved_project_paths(
    host: &dyn ContextHost,
    paths: &shepherd::settings::ResolvedPaths,
) -> Result<(), ContextError> {
    for (key, path) in [
        ("namespace", paths.namespace.as_path()),
        ("paths.docs", paths.docs.as_path()),
        ("paths.ctx", paths.ctx.as_path()),
        ("paths.runs", paths.runs.as_path()),
        ("registry", paths.registry.as_path()),
        ("registry_lock", paths.registry_lock.as_path()),
        ("project_id", paths.project_id.as_path()),
        ("dups.dups_registry", paths.dups_registry.as_path()),
    ] {
        let file_allowed = matches!(
            key,
            "registry" | "registry_lock" | "project_id" | "dups.dups_registry"
        );
        validate_resolved_project_path(host, &paths.namespace, key, path, file_allowed)?;
    }
    Ok(())
}

fn validate_resolved_project_path(
    host: &dyn ContextHost,
    namespace: &Path,
    key: &'static str,
    path: &Path,
    file_allowed: bool,
) -> Result<(), ContextError> {
    if !path.starts_with(namespace) {
        return Err(ContextError::NonCanonicalProjectPath {
            key,
            path: path.to_path_buf(),
        });
    }

    let mut current = path;
    loop {
        match host.symlink_metadata(current) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(ContextError::NonCanonicalProjectPath {
                    key,
                    path: path.to_path_buf(),
                });
            }
            Ok(metadata) if (!file_allowed || current != path) && !metadata.is_dir() => {
                return Err(ContextError::NonCanonicalProjectPath {
                    key,
                    path: path.to_path_buf(),
                });
            }
            Ok(_) => {}
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(source) => {
                return Err(ContextError::ResolveProjectPath {
                    key,
                    path: path.to_path_buf(),
                    source,
                });
            }
        }
        match host.canonicalize(current) {
            Ok(canonical) if canonical == current => return Ok(()),
            Ok(_) => {
                return Err(ContextError::NonCanonicalProjectPath {
                    key,
                    path: path.to_path_buf(),
                });
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                if current == namespace {
                    return Ok(());
                }
                current =
                    current
                        .parent()
                        .ok_or_else(|| ContextError::NonCanonicalProjectPath {
                            key,
                            path: path.to_path_buf(),
                        })?;
            }
            Err(source) => {
                return Err(ContextError::ResolveProjectPath {
                    key,
                    path: path.to_path_buf(),
                    source,
                });
            }
        }
    }
}

fn resolve_project_roots(
    inputs: &ContextInputs,
    host: &dyn ContextHost,
) -> Result<(PathBuf, PathBuf), ContextError> {
    let workspace = host
        .git_rev_parse(&inputs.start_dir, "--show-toplevel")
        .and_then(|top| host.canonicalize(&top));
    let primary = (|| {
        let top = host.git_rev_parse(&inputs.start_dir, "--show-toplevel")?;
        let common = host.git_rev_parse(&inputs.start_dir, "--git-common-dir")?;
        let common = host.canonicalize(&common)?;
        let git_dir = host.git_rev_parse(&inputs.start_dir, "--git-dir")?;
        let git_dir = host.canonicalize(&git_dir)?;
        let primary = if git_dir == common {
            top
        } else if common.file_name().is_some_and(|name| name == ".git") {
            common.parent().map(Path::to_path_buf).unwrap_or(top)
        } else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "linked worktree common directory cannot identify the primary checkout; provide an explicit primary fallback",
            ));
        };
        host.canonicalize(&primary)
    })();

    match (primary, workspace, &inputs.primary_fallback) {
        (Ok(primary), Ok(workspace), _) => Ok((primary, workspace)),
        (Err(_), Ok(workspace), Some(fallback)) => host
            .canonicalize(fallback)
            .map(|primary| (primary, workspace))
            .map_err(|error| ContextError::Primary(error.to_string())),
        (_, Err(_), Some(fallback)) => host
            .canonicalize(fallback)
            .map(|primary| (primary.clone(), primary))
            .map_err(|error| ContextError::Primary(error.to_string())),
        (Err(error), _, None) | (_, Err(error), None) => {
            Err(ContextError::Primary(error.to_string()))
        }
    }
}

fn resolve_user_home(
    inputs: &ContextInputs,
    primary_root: &Path,
    host: &dyn ContextHost,
) -> Result<Option<PathBuf>, ContextError> {
    let raw = inputs
        .shepherd_home
        .clone()
        .or_else(|| inputs.home_dir.as_ref().map(|home| home.join(".shepherd")));
    let Some(raw) = raw else {
        return Ok(None);
    };
    let path = if raw.is_absolute() {
        raw
    } else {
        primary_root.join(raw)
    };
    let resolved = match host.canonicalize(&path) {
        Ok(canonical) => canonical,
        Err(error) if error.kind() == io::ErrorKind::NotFound => path,
        Err(source) => return Err(ContextError::ResolveUserHome { path, source }),
    };
    let namespace = primary_root.join(".shepherd");
    if resolved.starts_with(&namespace) || namespace.starts_with(&resolved) {
        return Err(ContextError::UserHomeOverlap);
    }
    Ok(Some(resolved))
}

#[derive(Debug)]
struct SystemClock;

impl Clock for SystemClock {
    fn now_unix_millis(&self) -> i64 {
        let millis = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis();
        i64::try_from(millis).unwrap_or(i64::MAX)
    }
}

#[derive(Debug)]
struct SystemIdentifiers;

impl IdentifierSource for SystemIdentifiers {
    fn next_id(&mut self) -> String {
        static NEXT: AtomicU64 = AtomicU64::new(0);
        let ordinal = NEXT.fetch_add(1, Ordering::Relaxed);
        format!("{}-{ordinal}", std::process::id())
    }
}

#[derive(Debug)]
struct SystemIo;

impl IoBoundary for SystemIo {
    fn read_stdin(&mut self, buffer: &mut String) -> io::Result<usize> {
        io::stdin().read_line(buffer)
    }

    fn write_stdout(&mut self, bytes: &[u8]) -> io::Result<()> {
        let mut stdout = io::stdout().lock();
        stdout.write_all(bytes)?;
        stdout.flush()
    }

    fn write_stderr(&mut self, bytes: &[u8]) -> io::Result<()> {
        let mut stderr = io::stderr().lock();
        stderr.write_all(bytes)?;
        stderr.flush()
    }
}