Skip to main content

spec_driven_docs/landing/
gate.rs

1//! The version gate every command passes before its handler runs.
2//!
3//! Each command, and each action of a command family, carries one class in
4//! [`TABLE`]. A gated class compares the version the target's instance
5//! record names with this binary's own, and runs, warns, or refuses by the
6//! rows the setup spec states, naming the command that fixes a mismatch.
7//! The gate reads the record of any schema, never writes, never moves a
8//! pin, and never runs `init` or `upgrade` by itself.
9//!
10//! SATISFIES setup:every-command-has-a-gate-class
11//! SATISFIES setup:a-gated-command-names-its-fix
12
13use std::fmt::Write as _;
14
15use camino::{Utf8Path, Utf8PathBuf};
16
17use crate::cli::Commands;
18use crate::domain::manifest::{MANIFEST_PATH, Manifest};
19use crate::domain::version::CanonVersion;
20use crate::error::AppError;
21
22/// What the gate holds an action to.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Class {
25    /// Needs no target, or must never fail.
26    Exempt,
27    /// Runs on a target with no instance by design, and before or during an
28    /// upgrade. On an instance, an action that writes follows the writing
29    /// rows.
30    PreLanding,
31    /// `upgrade` alone, which keeps its own checks.
32    Upgrade,
33    /// Reads an instance.
34    ReadOnly,
35    /// Writes an instance when applied; a preview is read-only.
36    Writing,
37}
38
39/// When an action writes the target.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Writes {
42    /// Never.
43    Never,
44    /// Only with `--apply`.
45    WithApply,
46    /// Always, with no flag.
47    Always,
48}
49
50/// Where an action finds its target.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum TargetSource {
53    /// The `--target` argument, `.` meaning the current folder.
54    Flag,
55    /// The current folder.
56    CurrentFolder,
57    /// No target.
58    None,
59}
60
61/// One row of the class table.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct Row {
64    /// The action, as its command path spells it.
65    pub path: &'static str,
66    /// Its class.
67    pub class: Class,
68    /// When it writes the target.
69    pub writes: Writes,
70    /// Where it finds its target.
71    pub target: TargetSource,
72}
73
74const fn row(path: &'static str, class: Class, writes: Writes, target: TargetSource) -> Row {
75    Row {
76        path,
77        class,
78        writes,
79        target,
80    }
81}
82
83/// Every action of the command tree and its class, in one place.
84pub const TABLE: &[Row] = &[
85    row(
86        "init",
87        Class::PreLanding,
88        Writes::WithApply,
89        TargetSource::Flag,
90    ),
91    row("verify", Class::ReadOnly, Writes::Never, TargetSource::Flag),
92    row(
93        "upgrade",
94        Class::Upgrade,
95        Writes::WithApply,
96        TargetSource::Flag,
97    ),
98    row(
99        "gate",
100        Class::ReadOnly,
101        Writes::Never,
102        TargetSource::CurrentFolder,
103    ),
104    row(
105        "hooks",
106        Class::Writing,
107        Writes::WithApply,
108        TargetSource::Flag,
109    ),
110    row(
111        "debt baseline",
112        Class::Writing,
113        Writes::WithApply,
114        TargetSource::Flag,
115    ),
116    row(
117        "debt migrate",
118        Class::Writing,
119        Writes::WithApply,
120        TargetSource::Flag,
121    ),
122    row(
123        "debt tighten",
124        Class::Writing,
125        Writes::WithApply,
126        TargetSource::Flag,
127    ),
128    row(
129        "policy reconcile",
130        Class::Writing,
131        Writes::WithApply,
132        TargetSource::Flag,
133    ),
134    row(
135        "ki list",
136        Class::ReadOnly,
137        Writes::Never,
138        TargetSource::Flag,
139    ),
140    row("docs", Class::Exempt, Writes::Never, TargetSource::None),
141    row("method", Class::Exempt, Writes::Never, TargetSource::None),
142    row("spec", Class::Exempt, Writes::Never, TargetSource::None),
143    row("template", Class::Exempt, Writes::Never, TargetSource::None),
144    row(
145        "skill list",
146        Class::Exempt,
147        Writes::Never,
148        TargetSource::None,
149    ),
150    row(
151        "skill show",
152        Class::Exempt,
153        Writes::Never,
154        TargetSource::None,
155    ),
156    row(
157        "skill install",
158        Class::Exempt,
159        Writes::Never,
160        TargetSource::None,
161    ),
162    row(
163        "skill uninstall",
164        Class::Exempt,
165        Writes::Never,
166        TargetSource::None,
167    ),
168    row(
169        "stage",
170        Class::PreLanding,
171        Writes::Never,
172        TargetSource::Flag,
173    ),
174    row(
175        "stage clean",
176        Class::PreLanding,
177        Writes::Never,
178        TargetSource::None,
179    ),
180    row(
181        "stage compare",
182        Class::PreLanding,
183        Writes::Never,
184        TargetSource::Flag,
185    ),
186    row("status", Class::Exempt, Writes::Never, TargetSource::None),
187    // The setup skill reads the environment report while it plans a
188    // landing, so a preview runs before an instance exists; an apply on an
189    // instance follows the writing rows.
190    row(
191        "env",
192        Class::PreLanding,
193        Writes::WithApply,
194        TargetSource::Flag,
195    ),
196    row("lint", Class::PreLanding, Writes::Never, TargetSource::Flag),
197    row(
198        "lint prove",
199        Class::PreLanding,
200        Writes::Never,
201        TargetSource::Flag,
202    ),
203    row(
204        "migrate inventory",
205        Class::PreLanding,
206        Writes::Never,
207        TargetSource::Flag,
208    ),
209    row(
210        "migrate archive",
211        Class::PreLanding,
212        Writes::WithApply,
213        TargetSource::Flag,
214    ),
215    row(
216        "migrate mark",
217        Class::PreLanding,
218        Writes::Always,
219        TargetSource::Flag,
220    ),
221    row(
222        "migrate status",
223        Class::PreLanding,
224        Writes::Never,
225        TargetSource::Flag,
226    ),
227    row(
228        "migrate close",
229        Class::PreLanding,
230        Writes::WithApply,
231        TargetSource::Flag,
232    ),
233    row(
234        "track status",
235        Class::ReadOnly,
236        Writes::Never,
237        TargetSource::Flag,
238    ),
239    row(
240        "track check",
241        Class::ReadOnly,
242        Writes::Never,
243        TargetSource::Flag,
244    ),
245    row("doctor", Class::Exempt, Writes::Never, TargetSource::None),
246    row(
247        "assess",
248        Class::PreLanding,
249        Writes::Never,
250        TargetSource::Flag,
251    ),
252    row("license", Class::Exempt, Writes::Never, TargetSource::None),
253    row(
254        "self-manifest",
255        Class::Exempt,
256        Writes::Never,
257        TargetSource::None,
258    ),
259    row(
260        "self-depend status",
261        Class::Exempt,
262        Writes::Never,
263        TargetSource::None,
264    ),
265    row(
266        "self-depend add",
267        Class::Exempt,
268        Writes::Never,
269        TargetSource::None,
270    ),
271    row(
272        "self-depend check",
273        Class::Exempt,
274        Writes::Never,
275        TargetSource::None,
276    ),
277    row(
278        "self-depend sync",
279        Class::Exempt,
280        Writes::Never,
281        TargetSource::None,
282    ),
283    row(
284        "self-depend clean",
285        Class::Exempt,
286        Writes::Never,
287        TargetSource::None,
288    ),
289    row(
290        "completions",
291        Class::Exempt,
292        Writes::Never,
293        TargetSource::None,
294    ),
295    row("man", Class::Exempt, Writes::Never, TargetSource::None),
296];
297
298/// The row of one action, by its command path.
299#[must_use]
300pub fn row_of(path: &str) -> Option<&'static Row> {
301    TABLE.iter().find(|row| row.path == path)
302}
303
304/// One parsed invocation, reduced to what the gate reads.
305#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct Invocation {
307    /// The action's command path.
308    pub path: &'static str,
309    /// Whether the invocation asked to write.
310    pub applied: bool,
311    /// The target as the invocation spelled it, where it names one.
312    pub target: Option<Utf8PathBuf>,
313}
314
315fn invocation(path: &'static str, applied: bool, target: Option<&Utf8Path>) -> Invocation {
316    Invocation {
317        path,
318        applied,
319        target: target.map(Utf8Path::to_owned),
320    }
321}
322
323/// Reduce a parsed command to its action, its write request, and its target.
324#[must_use]
325pub fn invocation_of(command: &Commands) -> Invocation {
326    use crate::cli::debt::DebtVerb;
327    use crate::cli::ki::KiCommand;
328    use crate::cli::lint::LintCommand;
329    use crate::cli::migrate::MigrateCommand;
330    use crate::cli::policy::PolicyVerb;
331    use crate::cli::self_depend::SelfDependCommand;
332    use crate::cli::skill::SkillCommand;
333    use crate::cli::stage::StageCommand;
334    use crate::cli::track::TrackCommand;
335
336    match command {
337        Commands::Init(args) => {
338            // A landing from a stage lands in the folder it runs from,
339            // unless it names its target.
340            let target = args
341                .target
342                .clone()
343                .or_else(|| args.stage.as_ref().map(|_| Utf8PathBuf::from(".")));
344            invocation("init", args.apply, target.as_deref())
345        }
346        Commands::Verify(args) => invocation("verify", false, Some(&args.target)),
347        Commands::Upgrade(args) => invocation("upgrade", false, Some(&args.target)),
348        Commands::Gate(args) => {
349            if args.id.is_some() {
350                invocation("gate", false, Some(Utf8Path::new(".")))
351            } else {
352                // Listing and explaining read the registry alone.
353                invocation("gate", false, None)
354            }
355        }
356        Commands::Hooks(args) => invocation("hooks", args.apply, Some(Utf8Path::new(&args.target))),
357        Commands::Debt(args) => match &args.verb {
358            DebtVerb::Baseline(verb) => invocation("debt baseline", verb.apply, Some(&verb.target)),
359            DebtVerb::Migrate(verb) => invocation("debt migrate", verb.apply, Some(&verb.target)),
360            DebtVerb::Tighten(verb) => invocation("debt tighten", verb.apply, Some(&verb.target)),
361        },
362        Commands::Policy(args) => match &args.verb {
363            PolicyVerb::Reconcile(verb) => {
364                invocation("policy reconcile", verb.apply, Some(&verb.target))
365            }
366        },
367        Commands::Ki(args) => match &args.command {
368            KiCommand::List(list) => invocation("ki list", false, Some(&list.target)),
369        },
370        Commands::Docs(_) => invocation("docs", false, None),
371        Commands::Method(_) => invocation("method", false, None),
372        Commands::Spec(_) => invocation("spec", false, None),
373        Commands::Template(_) => invocation("template", false, None),
374        Commands::Skill(args) => match &args.command {
375            SkillCommand::List => invocation("skill list", false, None),
376            SkillCommand::Show(_) => invocation("skill show", false, None),
377            SkillCommand::Install(_) => invocation("skill install", false, None),
378            SkillCommand::Uninstall(_) => invocation("skill uninstall", false, None),
379        },
380        Commands::Stage(args) => match &args.command {
381            None => invocation("stage", false, Some(&args.target)),
382            Some(StageCommand::Clean(_)) => invocation("stage clean", false, None),
383            Some(StageCommand::Compare(compare)) => {
384                invocation("stage compare", false, Some(&compare.target))
385            }
386        },
387        Commands::Status(_) => invocation("status", false, None),
388        Commands::Env(args) => invocation("env", args.apply.is_some(), Some(&args.target)),
389        Commands::Lint(args) => match &args.command {
390            None => invocation("lint", false, Some(&args.target)),
391            Some(LintCommand::Prove(prove)) => invocation("lint prove", false, Some(&prove.target)),
392        },
393        Commands::Migrate(args) => match &args.command {
394            MigrateCommand::Inventory(verb) => {
395                invocation("migrate inventory", false, Some(&verb.target))
396            }
397            MigrateCommand::Archive(verb) => {
398                invocation("migrate archive", verb.apply, Some(&verb.target))
399            }
400            MigrateCommand::Mark(verb) => invocation("migrate mark", true, Some(&verb.target)),
401            MigrateCommand::Status(verb) => invocation("migrate status", false, Some(&verb.target)),
402            MigrateCommand::Close(verb) => {
403                invocation("migrate close", verb.apply, Some(&verb.target))
404            }
405        },
406        Commands::Track(args) => match &args.command {
407            TrackCommand::Status(verb) => invocation("track status", false, Some(&verb.target)),
408            TrackCommand::Check(verb) => invocation("track check", false, Some(&verb.target)),
409        },
410        Commands::Doctor(_) => invocation("doctor", false, None),
411        Commands::Assess(args) => invocation("assess", false, Some(&args.target)),
412        Commands::License(_) => invocation("license", false, None),
413        Commands::SelfManifest => invocation("self-manifest", false, None),
414        Commands::SelfDepend(args) => match &args.command {
415            SelfDependCommand::Status(_) => invocation("self-depend status", false, None),
416            SelfDependCommand::Add(_) => invocation("self-depend add", false, None),
417            SelfDependCommand::Check(_) => invocation("self-depend check", false, None),
418            SelfDependCommand::Sync(_) => invocation("self-depend sync", false, None),
419            SelfDependCommand::Clean(_) => invocation("self-depend clean", false, None),
420        },
421        Commands::Completions(_) => invocation("completions", false, None),
422        Commands::Man => invocation("man", false, None),
423    }
424}
425
426/// What the gate decided for a check that lets the handler run.
427#[derive(Debug, Clone, PartialEq, Eq)]
428pub enum Passed {
429    /// Nothing to say.
430    Quiet,
431    /// One line for stderr; the command keeps its own exit code.
432    Warn(String),
433}
434
435/// What one instance record says about its version, read from any schema.
436#[derive(Debug, Clone, PartialEq, Eq)]
437pub struct Recorded {
438    /// The release that wrote the record.
439    pub version: CanonVersion,
440    /// The record's schema, where it is older than this binary's.
441    pub older_schema: Option<u32>,
442}
443
444/// Read the version an instance record names, whatever its schema.
445///
446/// `None` where the target holds no record. A record that cannot be read
447/// at all is left to the handler, which reports it.
448#[must_use]
449pub fn recorded(target: &Utf8Path) -> Option<Result<Recorded, String>> {
450    let path = target.join(MANIFEST_PATH);
451    if !path.is_file() {
452        return None;
453    }
454    let text = match std::fs::read_to_string(&path) {
455        Ok(text) => text,
456        Err(error) => return Some(Err(error.to_string())),
457    };
458    Some(
459        Manifest::parse_any(&text)
460            .map(|(manifest, older_schema)| Recorded {
461                version: manifest.canon_version,
462                older_schema,
463            })
464            .map_err(|error| error.to_string()),
465    )
466}
467
468/// The text that names the setup skill reader beside `sdd init`.
469const NO_INSTANCE: &str = "This repository has no spec-driven-docs instance. Run `sdd init` to land it. Read the setup skill with `sdd skill show sdd-setup`, and each file it names with `sdd skill show sdd-setup --file <path>`.";
470
471/// The version a pin at `target` names, where a manager file pins this tool.
472fn pinned(target: &Utf8Path) -> Option<String> {
473    crate::self_depend::manager::detect(target)
474        .into_iter()
475        .find_map(|detected| detected.pin.map(|pin| pin.version.to_string()))
476}
477
478/// Whether `left` names an older release than `right`.
479fn older(left: &str, right: &str) -> bool {
480    let parse = |version: &str| -> Option<Vec<u64>> {
481        version
482            .split('.')
483            .map(|part| part.parse().ok())
484            .collect::<Option<Vec<u64>>>()
485    };
486    matches!((parse(left), parse(right)), (Some(a), Some(b)) if a < b)
487}
488
489/// Hold one action to the version of its target's instance.
490///
491/// # Errors
492///
493/// [`AppError::Refused`] naming the command that fixes the mismatch, by
494/// the rows of `setup:a-gated-command-names-its-fix`.
495pub fn require_aligned(row: &Row, applied: bool, target: &Utf8Path) -> Result<Passed, AppError> {
496    let writes = match row.writes {
497        Writes::Never => false,
498        Writes::WithApply => applied,
499        Writes::Always => true,
500    };
501    let Some(record) = recorded(target) else {
502        return match row.class {
503            Class::ReadOnly | Class::Writing => Err(AppError::Refused(format!(
504                "{NO_INSTANCE} (setup:a-gated-command-names-its-fix)"
505            ))),
506            Class::Exempt | Class::PreLanding | Class::Upgrade => Ok(Passed::Quiet),
507        };
508    };
509    let effective = match (row.class, writes) {
510        (Class::Exempt | Class::Upgrade, _) | (Class::PreLanding, false) => {
511            return Ok(Passed::Quiet);
512        }
513        (Class::PreLanding | Class::Writing | Class::ReadOnly, true) => Class::Writing,
514        (Class::ReadOnly | Class::Writing, false) => Class::ReadOnly,
515    };
516    // A record nobody can read is the handler's to report.
517    let Ok(record) = record else {
518        return Ok(Passed::Quiet);
519    };
520    let binary = CanonVersion::current().to_string();
521    let instance = record.version.to_string();
522    if older(&binary, &instance) {
523        let mut text = format!(
524            "The instance is at sdd {instance} and this sdd is {binary}, which is older. Run the sdd of this project's environment, for example `direnv exec . sdd ...`."
525        );
526        if let Some(pin) = pinned(target).filter(|pin| older(pin, &instance)) {
527            let _ = write!(text, " The pin names {pin}. Move it to {instance}.");
528        }
529        return Err(AppError::Refused(format!(
530            "{text} (setup:a-gated-command-names-its-fix)"
531        )));
532    }
533    if older(&instance, &binary) || record.older_schema.is_some() {
534        let schema = record
535            .older_schema
536            .map(|schema| format!(", recorded in schema {schema},"))
537            .unwrap_or_default();
538        if effective == Class::Writing {
539            return Err(AppError::Refused(format!(
540                "The instance is at sdd {instance}{schema} and this sdd is {binary}. Run `sdd upgrade` to move the instance, then run this command again. (setup:a-gated-command-names-its-fix)"
541            )));
542        }
543        return Ok(Passed::Warn(format!(
544            "warning: the instance is at sdd {instance}{schema} and this sdd is {binary}; run `sdd upgrade` (setup:a-gated-command-names-its-fix)"
545        )));
546    }
547    Ok(Passed::Quiet)
548}
549
550/// Gate one parsed command before its handler runs.
551///
552/// The warning of a passing read goes to stderr, so it never enters a JSON
553/// body on stdout.
554///
555/// # Errors
556///
557/// Whatever [`require_aligned`] refuses.
558pub fn gate(command: &Commands, cwd: &Utf8Path) -> Result<(), AppError> {
559    let invocation = invocation_of(command);
560    let Some(row) = row_of(invocation.path) else {
561        return Ok(());
562    };
563    let Some(target) = invocation.target else {
564        return Ok(());
565    };
566    if row.class == Class::Exempt || row.target == TargetSource::None {
567        return Ok(());
568    }
569    let target = if target.is_absolute() {
570        target
571    } else if target == "." {
572        cwd.to_owned()
573    } else {
574        cwd.join(target)
575    };
576    // A target that is no folder is the handler's to refuse.
577    if !target.is_dir() {
578        return Ok(());
579    }
580    if let Passed::Warn(line) = require_aligned(row, invocation.applied, &target)? {
581        eprintln!("{line}");
582    }
583    Ok(())
584}