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
//! Native JSON boundary for dispatch lifecycle and identity operations.

use std::path::Path;

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

use serde::de::DeserializeOwned;
use shepherd::dispatch::{CapabilityReadiness, DispatchRecord, ProjectId};

use crate::{
    ContextInputs, DispatchService, DispatchStore, ExecutionContext,
    interface::{CliError, CliGlobals},
};

const MAX_REQUEST_BYTES: usize = 1_048_576;
const MALFORMED_JSON_MESSAGE: &str = "request must be one valid RFC 8259 JSON value";

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, clap::Args)]
pub struct DispatchCmd {
    #[command(subcommand)]
    action: DispatchAction,
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, clap::Subcommand)]
enum DispatchAction {
    /// Bind the primary SessionStart identity to the active run.
    BindRoot(BindRootArgs),
    /// Resolve one native hook identity against its durable record.
    Resolve,
    /// Monotonically stop a native subagent and attach an artifact reference.
    Stop,
    /// Start an OS-authenticated provider process and own its broker lifecycle.
    BrokerLaunch,
    /// Accept one broker-authenticated child hook event.
    BrokerChild,
    /// Enter a root-local temporary Planter profile through typed JSON.
    ProfileEnter,
    /// Activate an entered profile after exact installed-bundle attestation.
    ProfileActivate,
    /// Exit an active profile after shared seed verification.
    ProfileExit,
    /// Persistently revoke an entered, active, expired, or crashed profile.
    ProfileRevoke,
    /// Prepare one Native single-use on-demand skill challenge.
    SkillUsePrepare,
    /// Attest exact loaded skill bytes and consume the challenge.
    SkillUseAttest,
    /// Recheck an attested skill against current Native authority and bytes.
    SkillUseVerify,
    /// Persist one Native-attributed review ruling and terminalize rejection four.
    ReviewRuling,
    /// Read-only proof of terminal review prelaunch predicates, not broker attempts.
    ReviewVerifyTerminal,
    /// Authorize one exact-lineage replacement for a malignant child.
    ReviewReplace,
    /// Bind an installed carrier to this native binary before any run exists.
    TransportBind,
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, clap::Args)]
struct BindRootArgs {
    #[arg(long)]
    run: Option<String>,
    // Typed, so clap refuses an unknown mode at parse time and the legacy
    // `planning` spelling is taken by `RootMode`'s own `FromStr` rather than by
    // a normalization step here. Deliberately NOT a `///` comment: clap turns
    // doc comments into help text, and the rationale is for readers, not users.
    /// Root session phase.
    #[arg(long)]
    mode: Option<shepherd::dispatch::RootMode>,
    #[arg(long)]
    confirm: bool,
}

impl DispatchCmd {
    pub(crate) fn run(self, globals: CliGlobals) -> Result<(), CliError> {
        let cwd = std::env::current_dir().map_err(|error| {
            CliError::message(format!("cannot resolve current directory: {error}"))
        })?;
        let mut inputs = ContextInputs::from_environment(cwd)
            .map_err(|error| CliError::message(error.to_string()))?;
        inputs.explicit_config = globals.config;
        inputs.verbosity = globals.verbosity;
        let mut context = ExecutionContext::discover(inputs)
            .map_err(|error| CliError::message(error.to_string()))?;
        // A package binding exists precisely when no project has been
        // scaffolded yet, so it is answered before the project identity
        // document every other dispatch operation requires.
        if matches!(self.action, DispatchAction::TransportBind) {
            let request = read_request(&mut context)?;
            let response = super::transport_bind::bind(&context, request)?;
            return write_response(&mut context, &response);
        }

        let project_id = read_project_id(&context.project_id_path)?;
        let service = DispatchService::with_context(
            DispatchStore::new(&context.runs_root),
            project_id,
            &context.workspace_root,
            &context.registry_path,
        );
        let now = context.now_unix_millis();

        match self.action {
            DispatchAction::BindRoot(arguments)
                if arguments.run.is_some() || arguments.mode.is_some() || arguments.confirm =>
            {
                let run = arguments.run.ok_or_else(|| {
                    CliError::message("bind-root bootstrap requires --run, --mode, and --confirm")
                })?;
                let mode = arguments.mode.ok_or_else(|| {
                    CliError::message("bind-root bootstrap requires --run, --mode, and --confirm")
                })?;
                if !arguments.confirm {
                    return Err(CliError::message(
                        "bind-root bootstrap is mutating; re-run with --confirm",
                    ));
                }
                let run = service
                    .confirm_root_bootstrap(&run, mode)
                    .map_err(service_error)?;
                write_response(
                    &mut context,
                    &serde_json::json!({
                        "schema": "shepherd.root-bootstrap-confirmation/1",
                        "run": run,
                        "mode": mode,
                        "confirmed": true,
                    }),
                )
            }
            DispatchAction::BindRoot(_) => {
                let response = service
                    .bind_root(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::Resolve => {
                let response = service
                    .resolve(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_resolution_response(&mut context, &response)
            }
            DispatchAction::Stop => {
                let response = service
                    .stop(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_record_response(&mut context, &response)
            }
            DispatchAction::BrokerLaunch => super::native_broker::run_launch(context),
            DispatchAction::BrokerChild => super::native_broker::run_child(context),
            DispatchAction::ProfileEnter => {
                let response = service
                    .profile_enter(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::ProfileActivate => {
                let response = service
                    .profile_activate(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::ProfileExit => {
                let response = service
                    .profile_exit(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::ProfileRevoke => {
                let response = service
                    .profile_revoke(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::SkillUsePrepare => {
                let response = service
                    .skill_use_prepare(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::SkillUseAttest => {
                let response = service
                    .skill_use_attest(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::SkillUseVerify => {
                let response = service
                    .skill_use_verify(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::ReviewRuling => {
                let response = service
                    .review_ruling(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::ReviewVerifyTerminal => {
                let response = service
                    .review_verify_terminal(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
            DispatchAction::TransportBind => Err(CliError::message(
                "transport-bind is answered before project identity resolution",
            )),
            DispatchAction::ReviewReplace => {
                let response = service
                    .review_replace(read_request(&mut context)?, now)
                    .map_err(service_error)?;
                write_response(&mut context, &response)
            }
        }
    }
}

fn read_request<T: DeserializeOwned>(context: &mut ExecutionContext) -> Result<T, CliError> {
    parse_request(&read_stdin(context)?)
}

fn read_stdin(context: &mut ExecutionContext) -> Result<String, CliError> {
    let mut input = String::new();
    loop {
        let before = input.len();
        let read = context
            .read_stdin(&mut input)
            .map_err(|error| CliError::message(format!("cannot read stdin: {error}")))?;
        if input.len() > MAX_REQUEST_BYTES {
            return Err(CliError::message(format!(
                "dispatch request exceeds {MAX_REQUEST_BYTES}-byte limit"
            )));
        }
        if read == 0 {
            break;
        }
        if input.len() == before {
            return Err(CliError::message(
                "stdin boundary reported bytes without appending input",
            ));
        }
    }
    Ok(input)
}

fn parse_request<T: DeserializeOwned>(input: &str) -> Result<T, CliError> {
    serde_json::from_str(input).map_err(|error| {
        CliError::message(match error.classify() {
            serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {
                MALFORMED_JSON_MESSAGE.to_string()
            }
            _ => format!("request is valid JSON but does not match the dispatch schema: {error}"),
        })
    })
}

fn write_response<T: serde::Serialize>(
    context: &mut ExecutionContext,
    response: &T,
) -> Result<(), CliError> {
    let mut bytes = serde_json::to_vec(response)
        .map_err(|error| CliError::message(format!("cannot encode stdout: {error}")))?;
    bytes.push(b'\n');
    context
        .write_stdout(&bytes)
        .map_err(|error| CliError::message(format!("cannot write stdout: {error}")))
}

fn readiness_label(readiness: CapabilityReadiness) -> &'static str {
    match readiness {
        CapabilityReadiness::Ready => "ready",
        CapabilityReadiness::Degraded => "degraded",
        CapabilityReadiness::Blocked => "blocked",
    }
}

fn insert_readiness(value: &mut serde_json::Value, readiness: CapabilityReadiness) {
    if let Some(capabilities) = value
        .as_object_mut()
        .and_then(|object| object.get_mut("capabilities"))
        .and_then(serde_json::Value::as_object_mut)
    {
        capabilities.insert(
            "readiness".into(),
            serde_json::Value::String(readiness_label(readiness).into()),
        );
    }
}

fn write_record_response(
    context: &mut ExecutionContext,
    response: &DispatchRecord,
) -> Result<(), CliError> {
    let mut value = serde_json::to_value(response).map_err(|error| {
        CliError::message(format!("cannot serialize dispatch response: {error}"))
    })?;
    insert_readiness(&mut value, response.capabilities.readiness());
    write_response(context, &value)
}

fn write_resolution_response(
    context: &mut ExecutionContext,
    response: &crate::DispatchResolution,
) -> Result<(), CliError> {
    let mut value = serde_json::to_value(response).map_err(|error| {
        CliError::message(format!("cannot serialize dispatch response: {error}"))
    })?;
    if let Some(capabilities) = &response.capabilities {
        insert_readiness(&mut value, capabilities.readiness());
    }
    write_response(context, &value)
}

fn service_error(error: crate::DispatchServiceError) -> CliError {
    CliError::message(error.to_string())
}

/// Distinguishes which artifact a `NOFOLLOW`-guarded read names, so the
/// remediation text can differ by subject: `shepherd init` mints exactly
/// one artifact, `.shepherd/project.json`, and nothing else. Pointing an
/// ordinary missing file back at `init` is as wrong as pointing a missing
/// identity file anywhere else.
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    PartialEq,
    strum::AsRefStr,
    strum::Display,
    strum::EnumCount,
    strum::EnumIs,
    strum::EnumString,
    strum::IntoStaticStr,
    strum::VariantNames,
)]
#[strum(ascii_case_insensitive, serialize_all = "snake_case")]
pub(crate) enum ReadSubject {
    /// `.shepherd/project.json`, the one artifact `shepherd init` creates.
    ProjectIdentity,
    /// Any other regular file read through the same descriptor-safe path.
    File,
}

impl ReadSubject {
    /// Rendered by both classifiers. It used to be unix-only, which is why it
    /// carried a `dead_code` expectation; the non-unix reader now produces the
    /// same labelled messages, so the item is live everywhere.
    fn open_label(self) -> &'static str {
        match self {
            Self::ProjectIdentity => "project identity ",
            Self::File => "",
        }
    }

    /// The message a caller anywhere in the crate should surface for a
    /// `NOFOLLOW`-guarded read whose target is simply absent.
    pub(crate) fn not_found_message(self, path: &Path) -> String {
        match self {
            Self::ProjectIdentity => format!(
                "project not scaffolded — run `shepherd init --confirm`: {}",
                path.display()
            ),
            Self::File => format!("no such file: {}", path.display()),
        }
    }

    /// The message a caller anywhere in the crate should surface for a
    /// `NOFOLLOW`-guarded read whose target exists but is not a regular file.
    pub(crate) fn not_a_regular_file_message(self, path: &Path) -> String {
        match self {
            Self::ProjectIdentity => {
                format!("project identity is not a regular file: {}", path.display())
            }
            Self::File => format!("not a regular file: {}", path.display()),
        }
    }

    /// The message a caller anywhere in the crate should surface for a
    /// `NOFOLLOW`-guarded read whose target is larger than the caller's cap.
    ///
    /// Split by subject like the other two, and for the same reason: the
    /// identity reader has always said "project identity exceeds ..." and the
    /// generic reader "file exceeds ...". Collapsing four readers into one
    /// must not quietly rewrite either operator-facing string, and the only
    /// way to keep both is to let the subject own the wording. `open_label`
    /// cannot serve here -- it yields the empty string for `File`, which
    /// would render "exceeds 64-byte limit" with no noun at all.
    pub(crate) fn over_limit_message(self, path: &Path, limit: u64) -> String {
        match self {
            Self::ProjectIdentity => format!(
                "project identity exceeds {limit}-byte limit: {}",
                path.display()
            ),
            Self::File => format!("file exceeds {limit}-byte limit: {}", path.display()),
        }
    }
}

/// Classifies a `NOFOLLOW`-guarded `open` failure by its real errno rather
/// than assuming every failure is a refused symlink. `ENOENT` (plain
/// absence) and `ELOOP`/refused-`NOFOLLOW` (an actual symlink) are
/// different failures with different remediations, and conflating them
/// sends operators chasing a security incident that a `find -type l`
/// already rules out.
#[cfg(unix)]
pub(crate) fn classify_nofollow_open_error(
    subject: ReadSubject,
    path: &Path,
    error: rustix::io::Errno,
) -> CliError {
    use rustix::io::Errno;

    match error {
        Errno::NOENT => CliError::message(subject.not_found_message(path)),
        Errno::ISDIR => CliError::message(subject.not_a_regular_file_message(path)),
        Errno::LOOP => CliError::message(format!(
            "cannot open {}{} without following symlinks: {error}",
            subject.open_label(),
            path.display()
        )),
        other => CliError::message(format!(
            "cannot open {}{}: {other}",
            subject.open_label(),
            path.display()
        )),
    }
}

pub(crate) fn read_project_id(path: &Path) -> Result<ProjectId, CliError> {
    let bytes = read_regular_refusing_links(
        ReadSubject::ProjectIdentity,
        path,
        u64::try_from(MAX_REQUEST_BYTES).expect("identity limit fits in u64"),
    )?;
    let document: serde_json::Value = serde_json::from_slice(&bytes).map_err(|error| {
        CliError::message(format!(
            "invalid project identity document {}: {error}",
            path.display()
        ))
    })?;
    let id = document
        .as_object()
        .and_then(|object| object.get("id"))
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| {
            CliError::message(format!(
                "invalid project identity document {}: field `id` must be a string",
                path.display()
            ))
        })?;
    ProjectId::new(id).map_err(|error| CliError::message(error.to_string()))
}

/// Read at most `limit` bytes of an existing regular file without following a
/// link at any component, labelling every failure by `subject`.
///
/// THIS IS THE ONE CLI-LAYER READER. It used to be four: a `#[cfg(unix)]` /
/// `#[cfg(not(unix))]` pair here and a second pair in `cmd::knowledge`. The
/// fork was not cosmetic. `knowledge.rs`'s non-unix twin checked
/// `symlink_metadata` on the LEAF and then opened with a plain
/// `fs::File::open`, so it never performed the reparse-point component walk
/// `crate::safe_fs` exists to provide -- on Windows a junction anywhere ABOVE
/// the file was followed, and nothing observed it because that half of the
/// crate had never been exercised on Windows (#321). One body means a platform
/// arm cannot silently lose a guarantee the other arm has.
///
/// `subject` is a parameter rather than a fifth copy because the operator-
/// facing wording is the only thing that ever differed between the two pairs,
/// and [`ReadSubject`] already owned that wording.
///
/// The name is deliberately its own, and not shared with either neighbour it
/// could have been confused for. `crate::safe_fs::read_regular_nofollow` is
/// the non-unix `io::Result` primitive this delegates to, with eight other
/// callers of its own; `context.rs`'s `read_bounded_regular` reads from a
/// descriptor a caller already anchored, and takes no path at all. Three
/// distinct signatures are three functions. Handing two of them the same name
/// is precisely what made four copies of THIS one look interchangeable, and
/// let one of them quietly ship without the component walk.
pub(crate) fn read_regular_refusing_links(
    subject: ReadSubject,
    path: &Path,
    limit: u64,
) -> Result<Vec<u8>, CliError> {
    #[cfg(unix)]
    {
        use std::fs::File;

        use rustix::fs::{FileType, Mode, OFlags, fstat, open};

        let descriptor = open(
            path,
            OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
            Mode::empty(),
        )
        .map_err(|error| classify_nofollow_open_error(subject, path, error))?;
        let stat = fstat(&descriptor).map_err(|error| {
            CliError::message(format!(
                "cannot inspect {}{}: {error}",
                subject.open_label(),
                path.display()
            ))
        })?;
        // `O_NOFOLLOW` refuses a symlinked LEAF; it says nothing about the
        // kind of what it did open. A directory opens fine read-only, so the
        // regular-file check is a separate assertion, not a consequence.
        if !FileType::from_raw_mode(stat.st_mode).is_file() {
            return Err(CliError::message(subject.not_a_regular_file_message(path)));
        }
        let mut bytes = Vec::new();
        // Read limit + 1 so an over-limit file is detected rather than
        // truncated into a document that parses and is wrong.
        File::from(descriptor)
            .take(limit.saturating_add(1))
            .read_to_end(&mut bytes)
            .map_err(|error| {
                CliError::message(format!(
                    "cannot read {}{}: {error}",
                    subject.open_label(),
                    path.display()
                ))
            })?;
        if bytes.len() as u64 > limit {
            return Err(CliError::message(subject.over_limit_message(path, limit)));
        }
        Ok(bytes)
    }
    #[cfg(not(unix))]
    {
        use std::io::ErrorKind;

        crate::safe_fs::read_regular_nofollow(path, limit).map_err(|error| match error.kind() {
            ErrorKind::NotFound => CliError::message(subject.not_found_message(path)),
            // safe_fs raises two different `InvalidInput` refusals -- a
            // non-regular file and a refused link -- and `io::Error` carries
            // no structured reason across the boundary. The discriminator is
            // the prefix safe_fs itself exports, so there is exactly one
            // literal for the two sides to agree on.
            ErrorKind::InvalidInput
                if error
                    .to_string()
                    .starts_with(crate::safe_fs::NOT_REGULAR_PREFIX) =>
            {
                CliError::message(subject.not_a_regular_file_message(path))
            }
            ErrorKind::InvalidInput => CliError::message(format!(
                "cannot open {}{} without following symlinks: {error}",
                subject.open_label(),
                path.display()
            )),
            ErrorKind::InvalidData => CliError::message(subject.over_limit_message(path, limit)),
            _ => CliError::message(format!(
                "cannot read {}{}: {error}",
                subject.open_label(),
                path.display()
            )),
        })
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs, io,
        path::PathBuf,
        sync::{Arc, Mutex},
    };

    use crate::{
        Clock, ContextInputs, ExecutionContext, IdentifierSource, IoBoundary, RuntimeBindings,
        SystemHost,
    };

    use super::{ReadSubject, read_regular_refusing_links, read_request, write_response};
    // Named only by the unix reader test's message-extracting closure. CI runs
    // with `-D warnings`, so an ungated import here is a hard Windows failure
    // that a macOS-only check never sees.
    #[cfg(unix)]
    use crate::interface::CliError;

    #[test]
    fn terminal_review_verifier_accepts_only_the_typed_stdin_surface() {
        use clap::Parser;
        assert!(
            crate::ShepherdCli::try_parse_from(["shepherd", "dispatch", "review-verify-terminal",])
                .is_ok()
        );
        for option in ["--resume", "--launch", "--force", "--skip-custody"] {
            assert!(
                crate::ShepherdCli::try_parse_from([
                    "shepherd",
                    "dispatch",
                    "review-verify-terminal",
                    option,
                ])
                .is_err(),
                "read-only verifier must not expose {option}"
            );
        }
        let request = serde_json::json!({
            "schema": "shepherd.review-terminal-verification-request/1", "run": "v657",
            "harness": "codex", "root_session_id": "root", "subject_agent_id": "subject",
            "subject_session_id": "session", "task_generation": 1, "task_sha256": "a".repeat(64),
            "pending_launch_id_hash": "b".repeat(64), "skip_custody": true,
        });
        assert!(
            serde_json::from_value::<crate::dispatch_service::ReviewTerminalVerificationRequest>(
                request
            )
            .is_err()
        );
    }
    // Both callers are `#[cfg(unix)]`: they build a real symlink and let the
    // kernel produce a real ELOOP, which Windows cannot do.
    #[cfg(unix)]
    use super::read_project_id;

    #[derive(Debug)]
    struct FixedClock;

    impl Clock for FixedClock {
        fn now_unix_millis(&self) -> i64 {
            1_000
        }
    }

    #[derive(Debug)]
    struct FixedIds;

    impl IdentifierSource for FixedIds {
        fn next_id(&mut self) -> String {
            "fixed-id".into()
        }
    }

    #[derive(Debug)]
    struct FixedIo {
        input: String,
        consumed: bool,
        stdout: Arc<Mutex<Vec<u8>>>,
    }

    impl IoBoundary for FixedIo {
        fn read_stdin(&mut self, buffer: &mut String) -> io::Result<usize> {
            if self.consumed {
                return Ok(0);
            }
            buffer.push_str(&self.input);
            self.consumed = true;
            Ok(self.input.len())
        }

        fn write_stdout(&mut self, bytes: &[u8]) -> io::Result<()> {
            self.stdout
                .lock()
                .expect("stdout lock")
                .extend_from_slice(bytes);
            Ok(())
        }

        fn write_stderr(&mut self, _bytes: &[u8]) -> io::Result<()> {
            Ok(())
        }
    }

    fn context(input: &str) -> (ExecutionContext, Arc<Mutex<Vec<u8>>>, PathBuf) {
        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let root = std::env::temp_dir().join(format!(
            "shepherd-dispatch-io-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
        ));
        fs::create_dir_all(&root).expect("create fixture");
        let stdout = Arc::new(Mutex::new(Vec::new()));
        let runtime = RuntimeBindings::new(
            Box::new(FixedClock),
            Box::new(FixedIds),
            Box::new(FixedIo {
                input: input.into(),
                consumed: false,
                stdout: Arc::clone(&stdout),
            }),
        );
        let context = ExecutionContext::resolve_with(
            ContextInputs {
                start_dir: root.clone(),
                primary_fallback: Some(root.clone()),
                ..ContextInputs::default()
            },
            &SystemHost,
            runtime,
        )
        .expect("resolve context");
        (context, stdout, root)
    }

    // GE2 (unit level): `.shepherd/project.json` sits behind
    // `context::validate_resolved_project_paths`, which already refuses any
    // symlink at that exact leaf path before `ExecutionContext::discover`
    // ever returns (see `crates/cli/src/context.rs::validate_resolved_project_path`).
    // That means dispatch.rs's own `NOFOLLOW` refusal for the project
    // identity subject cannot be exercised end to end through the CLI: the
    // earlier, unrelated guard always wins the race. It CAN be exercised
    // directly, since `read_project_id` and its NOFOLLOW open never go
    // through `ExecutionContext` at all — they take a bare path. This test
    // constructs a real symlink and lets the kernel produce a real `ELOOP`,
    // satisfying the "no hand-built errno" rule while proving the exact
    // code this lane changed.
    #[cfg(unix)]
    #[test]
    fn read_project_id_refuses_a_symlinked_identity_with_the_security_wording() {
        use std::{
            os::unix::fs::symlink,
            time::{SystemTime, UNIX_EPOCH},
        };

        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock")
            .as_nanos();
        let root =
            std::env::temp_dir().join(format!("shepherd-dispatch-identity-symlink-{suffix}"));
        fs::create_dir_all(&root).expect("fixture");
        let target = root.join("identity-target.json");
        fs::write(&target, br#"{"id":"018f47ce-72d7-7f64-9eb1-2f651d521c2a"}"#)
            .expect("identity target");
        let link = root.join("project.json");
        symlink(&target, &link).expect("symlink identity");

        let error = read_project_id(&link).expect_err("symlinked identity must be refused");
        let message = error.message_text().expect("error carries a message");
        assert!(
            message.contains("without following symlinks"),
            "message={message}"
        );
        assert!(message.contains("project identity"), "message={message}");
        assert!(!message.contains("not scaffolded"), "message={message}");
        fs::remove_dir_all(root).expect("cleanup");
    }

    // GE1 (unit level companion): the same function on a plainly absent path
    // must not repeat the symlink wording, and must name the real
    // remediation. Reproduced end to end in `tests/dispatch_cli.rs`; this
    // pins the same behaviour directly against `read_project_id`.
    #[cfg(unix)]
    #[test]
    fn read_project_id_reports_absence_as_not_scaffolded() {
        let root = std::env::temp_dir().join(format!(
            "shepherd-dispatch-identity-absent-{}",
            std::process::id()
        ));
        fs::create_dir_all(&root).expect("fixture");
        let absent = root.join("project.json");

        let error = read_project_id(&absent).expect_err("absent identity must be refused");
        let message = error.message_text().expect("error carries a message");
        assert!(
            message.contains("project not scaffolded"),
            "message={message}"
        );
        // The remediation must be runnable as printed. `init` is gated behind
        // `--confirm` (see `InitCmd::run`), so a bare `shepherd init`
        // exits 2 and scaffolds nothing -- the operator following this message
        // ends up exactly where they started.
        assert!(
            message.contains("shepherd init --confirm"),
            "remediation must carry the authorization flag: message={message}"
        );
        assert!(
            !message.contains("without following symlinks"),
            "message={message}"
        );
        fs::remove_dir_all(root).expect("cleanup");
    }

    #[test]
    fn read_subject_labels_only_project_identity() {
        assert_eq!(
            ReadSubject::ProjectIdentity.open_label(),
            "project identity "
        );
        assert_eq!(ReadSubject::File.open_label(), "");
    }

    /// The consolidated reader, exercised through BOTH subjects at once.
    ///
    /// The two tests above it reach the same code, but only ever through
    /// `read_project_id`, which pins one subject and one limit. Four readers
    /// could disagree without either of them noticing; one reader is only
    /// worth having if the subject parameter is what actually varies, so this
    /// varies it. The wording is asserted exactly, not by `contains`, because
    /// both spellings are load-bearing downstream: `tests/dispatch_cli.rs`
    /// keys on the labelled identity text and `tests/wave_f_knowledge.rs`
    /// greps stderr for the unlabelled `File` text.
    #[cfg(unix)]
    #[test]
    fn the_bounded_reader_refuses_links_and_non_regular_files() {
        use std::os::unix::fs::symlink;

        let root = std::env::temp_dir().join(format!(
            "shepherd-dispatch-bounded-reader-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).expect("fixture");
        let target = root.join("doc.json");
        let link = root.join("link.json");
        let directory = root.join("nested");
        let absent = root.join("absent.json");
        fs::write(&target, b"bounded").expect("target");
        symlink(&target, &link).expect("symlink");
        fs::create_dir(&directory).expect("directory");

        let text = |result: Result<Vec<u8>, CliError>| -> String {
            result
                .expect_err("must be refused")
                .message_text()
                .expect("refusal carries a message")
                .to_owned()
        };

        // A regular file at and under the cap reads; one byte over is refused
        // rather than truncated into a document that would parse and be wrong.
        assert_eq!(
            read_regular_refusing_links(ReadSubject::File, &target, 7).expect("at the cap"),
            b"bounded"
        );
        assert_eq!(
            text(read_regular_refusing_links(ReadSubject::File, &target, 6)),
            format!("file exceeds 6-byte limit: {}", target.display())
        );
        assert_eq!(
            text(read_regular_refusing_links(
                ReadSubject::ProjectIdentity,
                &target,
                6
            )),
            format!(
                "project identity exceeds 6-byte limit: {}",
                target.display()
            )
        );

        // A symlink is refused, and the refusal says WHY -- conflating it with
        // absence is what sends an operator hunting a security incident that a
        // `find -type l` already rules out.
        for subject in [ReadSubject::File, ReadSubject::ProjectIdentity] {
            let message = text(read_regular_refusing_links(subject, &link, 64));
            assert!(
                message.contains("without following symlinks"),
                "subject={subject} message={message}"
            );
            assert!(
                message.contains(&link.display().to_string()),
                "subject={subject} message={message}"
            );
        }

        // O_NOFOLLOW refuses a symlinked leaf; it says nothing about the kind
        // of what it did open, and a directory opens read-only just fine. The
        // regular-file assertion is separate, so this is separate too.
        assert_eq!(
            text(read_regular_refusing_links(
                ReadSubject::File,
                &directory,
                64
            )),
            format!("not a regular file: {}", directory.display())
        );
        assert_eq!(
            text(read_regular_refusing_links(
                ReadSubject::ProjectIdentity,
                &directory,
                64
            )),
            format!(
                "project identity is not a regular file: {}",
                directory.display()
            )
        );

        assert_eq!(
            text(read_regular_refusing_links(ReadSubject::File, &absent, 64)),
            format!("no such file: {}", absent.display())
        );
        assert!(
            text(read_regular_refusing_links(
                ReadSubject::ProjectIdentity,
                &absent,
                64
            ))
            .contains("project not scaffolded"),
        );

        fs::remove_dir_all(root).expect("cleanup");
    }

    /// The hole this collapse actually closed, asserted where it exists.
    ///
    /// `cmd::knowledge`'s deleted `#[cfg(not(unix))]` twin checked
    /// `symlink_metadata` on the LEAF and then opened with a plain
    /// `fs::File::open`, so it never reached `safe_fs`'s reparse-point
    /// component walk: a junction on any ANCESTOR of a knowledge file was
    /// followed. This asserts the one remaining body refuses that. It compiles
    /// on every non-unix target and runs on Windows, which needs Developer
    /// Mode or elevation to create a link -- so it SKIPS loudly rather than
    /// passing quietly when it cannot build the fixture.
    #[cfg(not(unix))]
    #[test]
    fn an_ancestor_link_is_refused_on_non_unix() {
        let root = std::env::temp_dir().join(format!(
            "shepherd-dispatch-ancestor-link-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).expect("fixture");
        let real = root.join("real");
        fs::create_dir(&real).expect("real directory");
        let secret = real.join("secret.json");
        fs::write(&secret, b"{}").expect("write");
        let link = root.join("link");

        #[cfg(windows)]
        let created = std::os::windows::fs::symlink_dir(&real, &link).is_ok();
        #[cfg(not(windows))]
        let created = false;

        if !created {
            eprintln!("skipped: this environment cannot create a directory link");
            fs::remove_dir_all(root).expect("cleanup");
            return;
        }

        // The leaf here is a perfectly ordinary regular file. Only the walk
        // over its ancestors can catch this, which is exactly the guarantee
        // the deleted twin did not have.
        let message = read_regular_refusing_links(ReadSubject::File, &link.join("secret.json"), 64)
            .expect_err("an ancestor link must be refused")
            .message_text()
            .expect("refusal carries a message")
            .to_owned();
        assert!(
            message.contains("without following symlinks"),
            "message={message}"
        );
        assert!(
            !message.contains("not a regular file"),
            "an ancestor link must not be reported as a wrong file type: message={message}"
        );

        fs::remove_dir_all(root).expect("cleanup");
    }

    #[test]
    fn dispatch_json_uses_the_execution_context_io_boundary() {
        let (mut context, stdout, root) = context("{\n  \"value\": 7\n}\n");
        let request: serde_json::Value = read_request(&mut context).expect("read request");
        assert_eq!(request, serde_json::json!({"value": 7}));
        write_response(&mut context, &serde_json::json!({"ok": true})).expect("write response");
        assert_eq!(&*stdout.lock().expect("stdout lock"), b"{\"ok\":true}\n");
        fs::remove_dir_all(root).expect("remove fixture");
    }

    #[test]
    fn dispatch_json_rejects_trailing_values_after_reading_to_eof() {
        let (mut context, _stdout, root) = context("{}\n{\"second\":true}\n");
        let error = read_request::<serde_json::Value>(&mut context).expect_err("trailing value");
        assert_eq!(error.message_text(), Some(super::MALFORMED_JSON_MESSAGE));
        fs::remove_dir_all(root).expect("remove fixture");
    }

    #[test]
    fn dispatch_json_applies_the_limit_to_the_total_input() {
        let oversized = format!("\"{}\"", "x".repeat(super::MAX_REQUEST_BYTES));
        let (mut context, _stdout, root) = context(&oversized);
        let error = read_request::<serde_json::Value>(&mut context).expect_err("oversized input");
        assert!(
            error
                .message_text()
                .is_some_and(|message| message.contains("exceeds"))
        );
        fs::remove_dir_all(root).expect("remove fixture");
    }
}