shepherd-cli 6.4.5

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
//! Native layout-v5 project and user-home bootstrap commands.
//!
//! Legacy bootstrap installed environments and wrote retired namespace roots.
//! The canonical CLI owns only typed layout-v5 roots.

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

use shepherd::{
    registry::{OpenMode, Registry},
    settings::ShepherdConfig,
};

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

const PROJECT_DIRECTORIES: &[&str] = &["docs", "ctx", "runs"];
// The user tier owns only direct `shepherd*.toml` candidates. Project-owned
// templates live under `.shepherd/templates`; there is no user-template or
// filesystem-style-profile resolver in the native runtime.
const HOME_DIRECTORIES: &[&str] = &[];
const CONFIG_FILE: &str = "shepherd.toml";

#[derive(
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    clap::Args,
    serde::Deserialize,
    serde::Serialize,
)]
pub struct WaveCInitCmd {
    /// Do not create the canonical project configuration document.
    #[arg(long)]
    pub no_config: bool,
    /// Do not run the read-only native health check after initialization.
    #[arg(long)]
    pub no_doctor: bool,
    /// Also initialize the separately-owned Shepherd user home.
    #[arg(long)]
    pub user: bool,
    /// Authorize filesystem mutation. Without it, init fails closed.
    #[arg(long)]
    pub confirm: bool,
}

#[derive(
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    clap::Args,
    serde::Deserialize,
    serde::Serialize,
)]
#[command(disable_help_subcommand = true)]
pub struct WaveCConfigCmd {
    #[command(subcommand)]
    action: Option<ConfigAction>,
}

#[derive(
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    clap::Subcommand,
    serde::Deserialize,
    serde::Serialize,
)]
enum ConfigAction {
    /// Print the canonical project configuration write path.
    Path,
    /// Print the fully resolved typed configuration.
    Show,
    /// Read one dotted key from the resolved typed configuration.
    Get { key: String },
    /// Create the canonical project configuration if it is absent.
    Init {
        /// Authorize the configuration write.
        #[arg(long)]
        confirm: bool,
    },
}

#[derive(
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    clap::Args,
    serde::Deserialize,
    serde::Serialize,
)]
#[command(disable_help_subcommand = true)]
pub struct WaveCHomeCmd {
    #[command(subcommand)]
    action: Option<HomeAction>,
}

#[derive(
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    clap::Subcommand,
    serde::Deserialize,
    serde::Serialize,
)]
enum HomeAction {
    /// Print the resolved user-home namespace path.
    Which,
    /// Describe the resolved user-home namespace without mutation.
    Show,
    /// Create the canonical user-home directories.
    Init {
        /// Authorize the user-home mutation.
        #[arg(long)]
        confirm: bool,
    },
}

#[derive(
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    clap::Args,
    serde::Deserialize,
    serde::Serialize,
)]
pub struct WaveCDoctorCmd {
    /// Emit one structured health report.
    #[arg(long)]
    json: bool,
}

impl WaveCInitCmd {
    pub(crate) fn run(self, globals: CliGlobals) -> Result<(), CliError> {
        if !self.confirm {
            return Err(CliError::message_with_code(
                "init is mutating; re-run with --confirm",
                2,
            ));
        }
        let mut context = context(globals)?;
        initialize_project(&context, !self.no_config)?;
        if self.user {
            initialize_home(&context)?;
        }
        let report = health_report(&context);
        if !self.no_doctor && !report.ok {
            write(&mut context, report.render_text())?;
            return Err(CliError::reported_with_code(3));
        }
        let output = format!(
            "initialized layout-v5 namespace: {}\nregistry: {}",
            context.namespace.display(),
            context.registry_path.display()
        );
        write(&mut context, output)
    }
}
impl WaveCConfigCmd {
    pub(crate) fn run(self, globals: CliGlobals) -> Result<(), CliError> {
        let mut context = context(globals)?;
        match self.action {
            Some(ConfigAction::Path) => {
                let output = config_path(&context).display().to_string();
                write(&mut context, output)
            }
            Some(ConfigAction::Show) => {
                let text = serde_json::to_string_pretty(&context.config).map_err(|error| {
                    CliError::message(format!("cannot encode typed config: {error}"))
                })?;
                write(&mut context, text)
            }
            Some(ConfigAction::Get { key }) => {
                let output = typed_config_value(&context.config, &key)?;
                write(&mut context, output)
            }
            Some(ConfigAction::Init { confirm }) => {
                if !confirm {
                    return Err(CliError::message_with_code(
                        "config init is mutating; re-run with --confirm",
                        2,
                    ));
                }
                initialize_project_config(&context)?;
                let output = format!("initialized config: {}", config_path(&context).display());
                write(&mut context, output)
            }
            None => write(&mut context, "shepherd config <path|show|get|init>".into()),
        }
    }
}
impl WaveCHomeCmd {
    pub(crate) fn run(self, globals: CliGlobals) -> Result<(), CliError> {
        let mut context = context(globals)?;
        let home = required_user_home(&context)?.to_path_buf();
        match self.action {
            Some(HomeAction::Which) => write(&mut context, home.display().to_string()),
            Some(HomeAction::Show) => write(&mut context, format!("home: {}", home.display())),
            Some(HomeAction::Init { confirm }) => {
                if !confirm {
                    return Err(CliError::message_with_code(
                        "home init is mutating; re-run with --confirm",
                        2,
                    ));
                }
                initialize_home(&context)?;
                write(
                    &mut context,
                    format!("initialized shepherd home: {}", home.display()),
                )
            }
            None => write(&mut context, "shepherd home <which|show|init>".into()),
        }
    }
}
impl WaveCDoctorCmd {
    pub(crate) fn run(self, globals: CliGlobals) -> Result<(), CliError> {
        let mut context = context(globals)?;
        let report = health_report(&context);
        if self.json {
            let text = serde_json::to_string_pretty(&report).map_err(|error| {
                CliError::message(format!("cannot encode doctor report: {error}"))
            })?;
            write(&mut context, text)?;
        } else {
            write(&mut context, report.render_text())?;
        }
        if report.ok {
            Ok(())
        } else {
            Err(CliError::reported_with_code(3))
        }
    }
}
fn context(globals: CliGlobals) -> Result<ExecutionContext, CliError> {
    let cwd = std::env::current_dir().map_err(|error| CliError::message(error.to_string()))?;
    let mut inputs = ContextInputs::from_environment(cwd)
        .map_err(|error| CliError::message(error.to_string()))?;
    inputs.explicit_config = globals.config;
    inputs.verbosity = globals.verbosity;
    ExecutionContext::discover(inputs).map_err(|error| CliError::message(error.to_string()))
}

fn config_path(context: &ExecutionContext) -> PathBuf {
    context.namespace.join(CONFIG_FILE)
}

fn required_user_home(context: &ExecutionContext) -> Result<&Path, CliError> {
    context.user_home.as_deref().ok_or_else(|| {
        CliError::message_with_code(
            "cannot resolve shepherd user home; set SHEPHERD_HOME or HOME",
            2,
        )
    })
}

fn initialize_project(context: &ExecutionContext, write_config: bool) -> Result<(), CliError> {
    ensure_directory_tree(&context.primary_root, ".shepherd", PROJECT_DIRECTORIES)?;
    if write_config {
        initialize_project_config(context)?;
    }
    Registry::open_migrated(&context.registry_path)
        .map_err(|error| CliError::message(format!("cannot initialize typed registry: {error}")))?;
    Ok(())
}

fn initialize_project_config(context: &ExecutionContext) -> Result<(), CliError> {
    // An empty document is valid: the one typed schema loader materializes
    // every default, without a copied default table drifting from the schema.
    let contents = b"# Shepherd layout-v5 project configuration.\n# Defaults are supplied by the typed schema.\n";
    write_no_clobber(&context.primary_root, ".shepherd/shepherd.toml", contents)
}

fn initialize_home(context: &ExecutionContext) -> Result<(), CliError> {
    let home = required_user_home(context)?;
    let parent = home
        .parent()
        .ok_or_else(|| CliError::message("shepherd user home has no parent"))?;
    let parent = std::fs::canonicalize(parent).map_err(|error| {
        CliError::message(format!(
            "cannot resolve shepherd user-home parent {}: {error}",
            parent.display()
        ))
    })?;
    let name = home
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| CliError::message("shepherd user home has no UTF-8 final component"))?;
    ensure_directory_tree(&parent, name, HOME_DIRECTORIES)
}

fn typed_config_value(config: &ShepherdConfig, key: &str) -> Result<String, CliError> {
    if key.is_empty() || key.split('.').any(|part| part.is_empty()) {
        return Err(CliError::message_with_code(
            "config key must be a dotted typed key",
            2,
        ));
    }
    let mut current = toml::Value::try_from(config)
        .map_err(|error| CliError::message(format!("cannot inspect typed config: {error}")))?;
    for part in key.split('.') {
        current = current.get(part).cloned().ok_or_else(|| {
            CliError::message_with_code(format!("unknown typed config key: {key}"), 2)
        })?;
    }
    match current {
        toml::Value::String(value) => Ok(value),
        value => serde_json::to_string(&value).map_err(|error| {
            CliError::message(format!("cannot encode typed config value: {error}"))
        }),
    }
}

#[derive(serde::Serialize)]
struct DoctorReport {
    primary_root: PathBuf,
    namespace: PathBuf,
    docs: PathBuf,
    ctx: PathBuf,
    runs: PathBuf,
    registry: PathBuf,
    config_sources: Vec<PathBuf>,
    registry_schema: Option<u32>,
    findings: Vec<String>,
    ok: bool,
}

impl DoctorReport {
    fn render_text(&self) -> String {
        let mut output = format!(
            "primary: {}\nnamespace: {}\ndocs: {}\nctx: {}\nruns: {}\nregistry: {}\nstatus: {}",
            self.primary_root.display(),
            self.namespace.display(),
            self.docs.display(),
            self.ctx.display(),
            self.runs.display(),
            self.registry.display(),
            if self.ok { "ok" } else { "failed" }
        );
        for finding in &self.findings {
            output.push_str("\nissue: ");
            output.push_str(finding);
        }
        output
    }
}

fn health_report(context: &ExecutionContext) -> DoctorReport {
    let mut findings = Vec::new();
    for (label, path) in [
        ("namespace", &context.namespace),
        ("docs", &context.docs_root),
        ("ctx", &context.ctx_root),
        ("runs", &context.runs_root),
    ] {
        if !path.is_dir() {
            findings.push(format!("{label} directory is absent: {}", path.display()));
        }
    }
    let registry_schema = match Registry::open(&context.registry_path, OpenMode::ReadOnly) {
        Ok(registry) => match registry.schema_version() {
            Ok(version) => Some(version),
            Err(error) => {
                findings.push(format!("cannot read registry schema: {error}"));
                None
            }
        },
        Err(error) => {
            findings.push(format!("cannot open registry read-only: {error}"));
            None
        }
    };
    DoctorReport {
        primary_root: context.primary_root.clone(),
        namespace: context.namespace.clone(),
        docs: context.docs_root.clone(),
        ctx: context.ctx_root.clone(),
        runs: context.runs_root.clone(),
        registry: context.registry_path.clone(),
        config_sources: context
            .config_sources
            .iter()
            .map(|source| source.path.clone())
            .collect(),
        registry_schema,
        ok: findings.is_empty(),
        findings,
    }
}

fn write(context: &mut ExecutionContext, text: String) -> Result<(), CliError> {
    context
        .write_stdout(format!("{text}\n").as_bytes())
        .map_err(|error| CliError::message(format!("cannot write stdout: {error}")))
}

#[cfg(unix)]
fn ensure_directory_tree(
    anchor: &Path,
    root_name: &str,
    children: &[&str],
) -> Result<(), CliError> {
    let anchor_fd = descriptor::open_root(anchor)?;
    let directory = descriptor::open_directory(&anchor_fd, root_name, true)?;
    for child in children {
        let _ = descriptor::open_directory(&directory, child, true)?;
    }
    Ok(())
}

#[cfg(not(unix))]
fn ensure_directory_tree(_anchor: &Path, _root: &str, _children: &[&str]) -> Result<(), CliError> {
    Err(CliError::message(
        "descriptor-safe bootstrap mutation is unavailable on this platform",
    ))
}

#[cfg(unix)]
fn write_no_clobber(anchor: &Path, relative: &str, bytes: &[u8]) -> Result<(), CliError> {
    descriptor::write_no_clobber(anchor, relative, bytes)
}

#[cfg(not(unix))]
fn write_no_clobber(_anchor: &Path, _relative: &str, _bytes: &[u8]) -> Result<(), CliError> {
    Err(CliError::message(
        "descriptor-safe bootstrap mutation is unavailable on this platform",
    ))
}

#[cfg(unix)]
mod descriptor {
    use std::{
        fs::File,
        io::Write,
        os::fd::OwnedFd,
        path::{Component, Path},
        sync::atomic::{AtomicU64, Ordering},
    };

    use rustix::fs::{AtFlags, Mode, OFlags, linkat, mkdirat, open, openat, unlinkat};

    use crate::interface::CliError;

    static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

    pub(super) fn open_root(path: &Path) -> Result<OwnedFd, CliError> {
        let mut descriptor = open(
            "/",
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
            Mode::empty(),
        )
        .map_err(|error| CliError::message(format!("cannot open filesystem root: {error}")))?;
        for component in path.components() {
            let Component::Normal(part) = component else {
                continue;
            };
            descriptor = openat(
                &descriptor,
                part,
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
                Mode::empty(),
            )
            .map_err(|error| {
                CliError::message(format!(
                    "cannot open bootstrap path {} without following links: {error}",
                    path.display()
                ))
            })?;
        }
        Ok(descriptor)
    }

    pub(super) fn open_directory(
        parent: &OwnedFd,
        name: &str,
        create: bool,
    ) -> Result<OwnedFd, CliError> {
        let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW;
        match openat(parent, name, flags, Mode::empty()) {
            Ok(directory) => Ok(directory),
            Err(error) if create && error == rustix::io::Errno::NOENT => {
                match mkdirat(parent, name, Mode::from_raw_mode(0o755)) {
                    Ok(()) | Err(rustix::io::Errno::EXIST) => {}
                    Err(error) => {
                        return Err(CliError::message(format!(
                            "cannot create bootstrap directory `{name}`: {error}"
                        )));
                    }
                }
                openat(parent, name, flags, Mode::empty()).map_err(|error| {
                    CliError::message(format!(
                        "cannot open bootstrap directory `{name}` without following links: {error}"
                    ))
                })
            }
            Err(error) => Err(CliError::message(format!(
                "cannot open bootstrap directory `{name}` without following links: {error}"
            ))),
        }
    }

    pub(super) fn write_no_clobber(
        anchor: &Path,
        relative: &str,
        bytes: &[u8],
    ) -> Result<(), CliError> {
        let (parent, name) = parent_and_name(anchor, relative)?;
        let nonce = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
        let temporary = format!(".{name}.shepherd.tmp.{}.{nonce}", std::process::id());
        let descriptor = openat(
            &parent,
            &temporary,
            OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
            Mode::from_raw_mode(0o644),
        )
        .map_err(|error| {
            CliError::message(format!("cannot create `{relative}` atomically: {error}"))
        })?;
        let mut file = File::from(descriptor);
        let result = (|| {
            file.write_all(bytes).map_err(|error| {
                CliError::message(format!("cannot write `{relative}`: {error}"))
            })?;
            file.sync_all()
                .map_err(|error| CliError::message(format!("cannot sync `{relative}`: {error}")))?;
            let published = match linkat(&parent, &temporary, &parent, &name, AtFlags::empty()) {
                Ok(()) => true,
                Err(error) if error == rustix::io::Errno::EXIST => false,
                Err(error) => {
                    return Err(CliError::message(format!(
                        "cannot publish `{relative}` without replacing an existing file: {error}"
                    )));
                }
            };
            unlinkat(&parent, &temporary, AtFlags::empty()).map_err(|error| {
                CliError::message(format!(
                    "cannot remove `{relative}` temporary file: {error}"
                ))
            })?;
            if !published {
                return Ok(());
            }
            File::from(
                openat(
                    &parent,
                    ".",
                    OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
                    Mode::empty(),
                )
                .map_err(|error| {
                    CliError::message(format!("cannot reopen bootstrap directory: {error}"))
                })?,
            )
            .sync_all()
            .map_err(|error| CliError::message(format!("cannot sync bootstrap directory: {error}")))
        })();
        if result.is_err() {
            let _ = unlinkat(&parent, &temporary, AtFlags::empty());
        }
        result
    }

    fn parent_and_name(anchor: &Path, relative: &str) -> Result<(OwnedFd, String), CliError> {
        let relative = Path::new(relative);
        if relative.is_absolute()
            || relative
                .components()
                .any(|part| !matches!(part, Component::Normal(_)))
        {
            return Err(CliError::message(
                "bootstrap file path is not a safe relative path",
            ));
        }
        let mut parts = relative.components();
        let name = parts
            .next_back()
            .and_then(|part| match part {
                Component::Normal(name) => name.to_str(),
                _ => None,
            })
            .ok_or_else(|| CliError::message("bootstrap file path has no valid name"))?
            .to_owned();
        let mut directory = open_root(anchor)?;
        for part in parts {
            let Component::Normal(part) = part else {
                unreachable!("validated component")
            };
            directory = open_directory(
                &directory,
                part.to_str()
                    .ok_or_else(|| CliError::message("bootstrap path is not UTF-8"))?,
                true,
            )?;
        }
        Ok((directory, name))
    }
}

#[cfg(all(test, unix))]
mod tests {
    use std::{
        fs,
        sync::{Arc, Barrier},
        thread,
        time::{SystemTime, UNIX_EPOCH},
    };

    use super::descriptor;

    #[test]
    fn no_clobber_publication_keeps_one_racing_writer_and_leaves_no_temp() {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock is after epoch")
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "shepherd-wave-c-bootstrap-race-{}-{nonce:x}",
            std::process::id()
        ));
        fs::create_dir_all(root.join(".shepherd")).expect("create fixture namespace");
        let root = fs::canonicalize(root).expect("canonicalize fixture root");
        let barrier = Arc::new(Barrier::new(3));
        let mut writers = Vec::new();
        for bytes in [b"first\n".as_slice(), b"second\n".as_slice()] {
            let root = root.clone();
            let barrier = Arc::clone(&barrier);
            writers.push(thread::spawn(move || {
                barrier.wait();
                descriptor::write_no_clobber(&root, ".shepherd/shepherd.toml", bytes)
            }));
        }
        barrier.wait();
        for writer in writers {
            writer
                .join()
                .expect("writer thread must not panic")
                .expect("descriptor publication must succeed");
        }
        let published = fs::read(root.join(".shepherd/shepherd.toml")).expect("read publication");
        assert!(matches!(published.as_slice(), b"first\n" | b"second\n"));
        assert!(
            fs::read_dir(root.join(".shepherd"))
                .expect("read namespace")
                .all(|entry| !entry
                    .expect("directory entry")
                    .file_name()
                    .to_string_lossy()
                    .contains(".shepherd.tmp.")),
            "atomic no-clobber publication must clean temporary files"
        );
        fs::remove_dir_all(root).expect("remove fixture");
    }
}