Skip to main content

spec_driven_docs/domain/
instance_config.rs

1//! What a project declares about the files its gates judge.
2//!
3//! One hand-edited file, `.spec-driven-docs/config.yaml`, states which paths
4//! no delivered gate judges and which filters each named gate takes. The
5//! managed pre-commit block is rendered from it, so the block stays wholly
6//! owned by `sdd` and an upgrade never meets a project's edit.
7//!
8//! # The two keys are named apart
9//!
10//! `ESLint`'s flat config overloads one `ignores` key whose meaning changes
11//! with what else sits beside it, and it is a documented, repeated source of
12//! user confusion. `reserved` and `gates` mean one thing each.
13//!
14//! # The composition algorithm
15//!
16//! Four layers, in this order, and one function implements it:
17//!
18//! ```text
19//! layer 1  registry   the row's include and exclude in GATES
20//! layer 2  project    the gates: entry for that gate
21//! layer 3  flag       --include and --exclude on the command line
22//! layer 4  reserved   the reserved: list, as excludes only
23//! ```
24//!
25//! Per field, a later layer extends rather than replaces, with one stated
26//! exception: a project `include` list replaces the registry `include` list.
27//! A registry include is a whitelist, so extending it can only widen what a
28//! gate judges, which is the opposite of what a project asking for `include`
29//! wants. Every `exclude` layer extends, and `reserved` is last, so nothing
30//! reopens it. No layer can reopen an exclusion at all, because the grammar
31//! carries no negation: `crate::domain::path_filter` refuses a leading `!`.
32//!
33//! # The writing style is the project's to select
34//!
35//! `writing_style` states where the writing convention comes from: this
36//! convention's chapter, a document of the project's own, or none. The
37//! managed documentation block routes authors to the selection, and `none`
38//! installs no route and imposes no conversion obligation. The combination
39//! is validated, not just the field: `project` without a `path` names
40//! nothing, and a `path` beside another source is a value nothing reads,
41//! which is a value that drifts.
42//!
43//! # A host install is a decision the repository records
44//!
45//! `acquisition` records that the project obtains `sdd` from each host's own
46//! install rather than from a manager file, and the lowest version a host
47//! needs. A manager file records its pin itself, so the key exists only for
48//! the one method that leaves no file behind.
49
50use std::collections::BTreeMap;
51
52use camino::Utf8Path;
53use serde::{Deserialize, Serialize};
54
55use crate::domain::gate_id::GateId;
56use crate::domain::path_filter::{Layer, PathFilter, PathFilterError, Pattern};
57
58pub use crate::domain::paths::CONFIG_PATH;
59
60/// The filters one named gate takes.
61#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
62#[serde(deny_unknown_fields)]
63pub struct GateFilters {
64    /// Replaces the registry's include list for this gate.
65    #[serde(default)]
66    pub include: Vec<String>,
67    /// Extends the registry's exclude list for this gate.
68    #[serde(default)]
69    pub exclude: Vec<String>,
70}
71
72/// Where a project's writing style comes from.
73#[derive(Debug, Default, Clone, Copy, Deserialize, PartialEq, Eq)]
74#[serde(rename_all = "lowercase")]
75pub enum WritingSource {
76    /// This convention's chapter, served by `sdd method writing-style`.
77    #[default]
78    Builtin,
79    /// A document of the project's own, named by `path`.
80    Project,
81    /// No route and no conversion obligation.
82    None,
83}
84
85/// The writing-style selection as written.
86#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
87#[serde(deny_unknown_fields)]
88pub struct WritingStyle {
89    /// Which source.
90    #[serde(default)]
91    pub source: WritingSource,
92    /// The project's own document, relative to the repository root, where
93    /// the source is `project`.
94    #[serde(default)]
95    pub path: Option<String>,
96}
97
98impl WritingStyle {
99    /// Read the `--writing-style` argument: `builtin`, `none`, or
100    /// `project:<path>`.
101    ///
102    /// # Errors
103    ///
104    /// [`ConfigError::WritingStyle`] for any other form, or a path the
105    /// selection refuses.
106    pub fn parse_flag(value: &str) -> Result<Self, ConfigError> {
107        let selection = match value.trim() {
108            "builtin" => Self::default(),
109            "none" => Self {
110                source: WritingSource::None,
111                path: None,
112            },
113            other => match other.strip_prefix("project:") {
114                Some(path) => Self {
115                    source: WritingSource::Project,
116                    path: Some(path.trim().to_string()),
117                },
118                None => {
119                    return Err(ConfigError::WritingStyle(format!(
120                        "`{other}` is not a selection; write `builtin`, `none`, or `project:<path>`"
121                    )));
122                }
123            },
124        };
125        selection.check()?;
126        Ok(selection)
127    }
128
129    /// Hold the combination, not just each field.
130    fn check(&self) -> Result<(), ConfigError> {
131        match (self.source, self.path.as_deref()) {
132            (WritingSource::Project, None | Some("")) => Err(ConfigError::WritingStyle(
133                "`source: project` names no `path`".to_string(),
134            )),
135            (WritingSource::Builtin | WritingSource::None, Some(path)) if !path.is_empty() => {
136                Err(ConfigError::WritingStyle(format!(
137                    "`path: {path}` is set and the source is not `project`, so nothing reads it"
138                )))
139            }
140            (WritingSource::Project, Some(path)) => {
141                let candidate = Utf8Path::new(path);
142                if candidate.is_absolute() {
143                    return Err(ConfigError::WritingStyle(format!(
144                        "`path: {path}` is absolute; name the document relative to the repository"
145                    )));
146                }
147                if candidate.components().any(|part| part.as_str() == "..") {
148                    return Err(ConfigError::WritingStyle(format!(
149                        "`path: {path}` leaves the repository"
150                    )));
151                }
152                Ok(())
153            }
154            _ => Ok(()),
155        }
156    }
157
158    /// The document authors are routed to, relative to the repository, or
159    /// `None` where the selection installs no route.
160    #[must_use]
161    pub fn route(&self) -> Option<String> {
162        match self.source {
163            WritingSource::Builtin => Some("`sdd method writing-style`".to_string()),
164            WritingSource::Project => self.path.as_ref().map(|path| format!("`{path}`")),
165            WritingSource::None => None,
166        }
167    }
168
169    /// The selection as the declaration file spells it.
170    #[must_use]
171    pub fn render(&self) -> String {
172        let source = match self.source {
173            WritingSource::Builtin => "builtin",
174            WritingSource::Project => "project",
175            WritingSource::None => "none",
176        };
177        let path = self
178            .path
179            .as_deref()
180            .filter(|path| !path.is_empty())
181            .map_or_else(|| "null".to_string(), quoted);
182        format!("writing_style:\n  source: {source}\n  path: {path}\n")
183    }
184}
185
186/// Where every host obtains `sdd`, where no manager file records it.
187#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
188#[serde(rename_all = "lowercase")]
189pub enum AcquisitionSource {
190    /// Each host installs `sdd` itself, at the minimum version or newer.
191    Host,
192}
193
194/// The acquisition decision as written.
195#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
196#[serde(deny_unknown_fields)]
197pub struct Acquisition {
198    /// How every host obtains the binary.
199    pub source: AcquisitionSource,
200    /// The lowest release a host may run against this repository.
201    pub minimum: String,
202}
203
204impl Acquisition {
205    /// A host decision whose minimum is this binary's own release.
206    #[must_use]
207    pub fn host_at_this_release() -> Self {
208        Self {
209            source: AcquisitionSource::Host,
210            minimum: crate::domain::version::CanonVersion::current().to_string(),
211        }
212    }
213
214    /// Hold the minimum to a release version.
215    fn check(&self) -> Result<(), ConfigError> {
216        self.minimum
217            .parse::<crate::domain::version::CanonVersion>()
218            .map(|_| ())
219            .map_err(|_| {
220                ConfigError::Acquisition(format!(
221                    "`minimum: {}` is not a release version such as `0.13.2`",
222                    self.minimum
223                ))
224            })
225    }
226
227    /// The decision as the declaration file spells it.
228    #[must_use]
229    pub fn render(&self) -> String {
230        let source = match self.source {
231            AcquisitionSource::Host => "host",
232        };
233        format!(
234            "acquisition:\n  source: {source}\n  minimum: {}\n",
235            quoted(&self.minimum)
236        )
237    }
238}
239
240/// The declaration as written.
241#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
242#[serde(deny_unknown_fields)]
243pub struct InstanceConfig {
244    /// Paths no delivered gate judges. Another tool owns these.
245    ///
246    /// The list covers the gates `sdd` delivers. The Markdown linter reads
247    /// its scope from the `ignores` of its own configuration, so a Markdown
248    /// path it must skip goes in the root `.markdownlint-cli2.jsonc`.
249    #[serde(default)]
250    pub reserved: Vec<String>,
251    /// Per-gate filters, keyed by gate id. A gate not named here takes its
252    /// registry default.
253    #[serde(default)]
254    pub gates: BTreeMap<String, GateFilters>,
255    /// Where the writing style comes from. Absent, the convention's own
256    /// chapter.
257    #[serde(default)]
258    pub writing_style: WritingStyle,
259    /// How every host obtains `sdd`, where no manager file records it.
260    /// Absent, the repository has recorded no host decision.
261    #[serde(default)]
262    pub acquisition: Option<Acquisition>,
263    /// The migration the repository holds open, by the id of its workspace
264    /// under this tool's state root. Absent, no migration is open.
265    #[serde(default)]
266    pub migration: Option<String>,
267}
268
269/// A declaration that does not parse, or that names something no gate has.
270#[derive(Debug, thiserror::Error)]
271pub enum ConfigError {
272    /// The file is not YAML of this shape.
273    #[error("{CONFIG_PATH} does not parse: {0}")]
274    Shape(String),
275    /// A `gates:` key is not a delivered gate id.
276    #[error(
277        "{CONFIG_PATH} names the gate `{0}`, which this version does not deliver: `sdd gate --list` names every one"
278    )]
279    UnknownGate(String),
280    /// A pattern the filter grammar refuses.
281    #[error("{CONFIG_PATH}: {0}")]
282    Pattern(#[from] PathFilterError),
283    /// A writing-style selection whose fields do not agree.
284    #[error("{CONFIG_PATH}: writing_style: {0}")]
285    WritingStyle(String),
286    /// An acquisition decision this version cannot read.
287    #[error("{CONFIG_PATH}: acquisition: {0}")]
288    Acquisition(String),
289    /// A migration id this version cannot read.
290    #[error(
291        "{CONFIG_PATH}: migration: `{0}` is not a migration id such as `20261009T213000Z` or `20261009T213000Z-2` (setup:an-open-migration-is-declared)"
292    )]
293    Migration(String),
294}
295
296impl InstanceConfig {
297    /// Parse a declaration.
298    ///
299    /// # Errors
300    ///
301    /// [`ConfigError::Shape`] when the text is not a declaration, and
302    /// [`ConfigError::UnknownGate`] when a `gates:` key names no delivered
303    /// gate. Neither falls back to the default: a filter that quietly stops
304    /// applying is worse than one that fails loudly.
305    pub fn parse(text: &str) -> Result<Self, ConfigError> {
306        let parsed: Self =
307            yaml_serde::from_str(text).map_err(|error| ConfigError::Shape(error.to_string()))?;
308        for key in parsed.gates.keys() {
309            if resolve_id(key).is_none() {
310                return Err(ConfigError::UnknownGate(key.clone()));
311            }
312        }
313        // Compile every pattern here, at the one boundary, rather than
314        // where a gate runs. A malformed pattern that reached `render_block`
315        // would be written into the managed block and blessed by `verify`,
316        // then fail separately from every gate that ran.
317        parsed.check_patterns()?;
318        parsed.writing_style.check()?;
319        if let Some(acquisition) = &parsed.acquisition {
320            acquisition.check()?;
321        }
322        if let Some(id) = &parsed.migration
323            && !is_migration_id(id)
324        {
325            return Err(ConfigError::Migration(id.clone()));
326        }
327        Ok(parsed)
328    }
329
330    /// Read the declaration an instance carries.
331    ///
332    /// A missing file is the empty declaration and never an error: an
333    /// instance that declares nothing is a valid instance.
334    ///
335    /// # Errors
336    ///
337    /// See [`Self::parse`]. An unreadable file that exists is a shape error
338    /// rather than a silent default.
339    pub fn read(repo_root: &Utf8Path) -> Result<Self, ConfigError> {
340        let path = repo_root.join(CONFIG_PATH);
341        match std::fs::read_to_string(&path) {
342            Ok(text) => Self::parse(&text),
343            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
344            Err(error) => Err(ConfigError::Shape(error.to_string())),
345        }
346    }
347
348    /// Compile every declared pattern, so a bad one fails once and here.
349    ///
350    /// # Errors
351    ///
352    /// [`ConfigError::Pattern`] naming the pattern the grammar refuses.
353    fn check_patterns(&self) -> Result<(), ConfigError> {
354        let every = self.reserved.iter().chain(
355            self.gates
356                .values()
357                .flat_map(|filters| filters.include.iter().chain(&filters.exclude)),
358        );
359        for glob in every {
360            PathFilter::build(Vec::new(), vec![Pattern::new(glob.clone(), Layer::Project)])?;
361        }
362        Ok(())
363    }
364
365    /// This gate's declared filters, if the project named it.
366    #[must_use]
367    pub fn for_gate(&self, id: GateId) -> Option<&GateFilters> {
368        self.gates.get(&id.to_string())
369    }
370}
371
372/// Map a `gates:` key onto a delivered gate.
373fn resolve_id(key: &str) -> Option<GateId> {
374    GateId::ALL.iter().copied().find(|id| id.to_string() == key)
375}
376
377/// Build one gate's filter from every layer.
378///
379/// `registry_include` and `registry_exclude` arrive already templated
380/// against the instance's documentation root, because the root is the
381/// caller's to resolve.
382///
383/// # Errors
384///
385/// [`ConfigError::Pattern`] naming the pattern the grammar refuses.
386pub fn resolve(
387    registry_include: &[String],
388    registry_exclude: &[String],
389    declared: Option<&GateFilters>,
390    flag_include: &[String],
391    flag_exclude: &[String],
392    reserved: &[String],
393) -> Result<PathFilter, ConfigError> {
394    // A project include replaces the registry include; extending a
395    // whitelist could only widen what the gate judges.
396    let includes: Vec<Pattern> = declared.filter(|d| !d.include.is_empty()).map_or_else(
397        || {
398            registry_include
399                .iter()
400                .map(|glob| Pattern::new(glob.clone(), Layer::Registry))
401                .collect()
402        },
403        |declared| {
404            declared
405                .include
406                .iter()
407                .map(|glob| Pattern::new(glob.clone(), Layer::Project))
408                .collect()
409        },
410    );
411    let includes = includes
412        .into_iter()
413        .chain(
414            flag_include
415                .iter()
416                .map(|glob| Pattern::new(glob.clone(), Layer::Flag)),
417        )
418        .collect();
419
420    // Every exclude layer extends, and `reserved` is last so nothing that
421    // follows can reopen it.
422    let excludes: Vec<Pattern> = registry_exclude
423        .iter()
424        .map(|glob| Pattern::new(glob.clone(), Layer::Registry))
425        .chain(
426            declared
427                .into_iter()
428                .flat_map(|d| &d.exclude)
429                .map(|glob| Pattern::new(glob.clone(), Layer::Project)),
430        )
431        .chain(
432            flag_exclude
433                .iter()
434                .map(|glob| Pattern::new(glob.clone(), Layer::Flag)),
435        )
436        .chain(
437            reserved
438                .iter()
439                .map(|glob| Pattern::new(glob.clone(), Layer::Reserved)),
440        )
441        .collect();
442
443    Ok(PathFilter::build(includes, excludes)?)
444}
445
446/// One glob as a YAML scalar that reads back as itself.
447///
448/// A glob and YAML disagree about several leading characters: `*` opens an
449/// alias, `[` and `{` open a flow collection, and `#` opens a comment. The
450/// filter grammar accepts `**/generated.md`, so writing it bare would
451/// produce a file the next read refuses. Single quotes make every glob a
452/// scalar, with an apostrophe doubled.
453fn quoted(glob: &str) -> String {
454    format!("'{}'", glob.replace('\'', "''"))
455}
456
457/// Record a writing-style selection in a declaration, keeping every comment.
458///
459/// The `writing_style:` key and its indented children are replaced as a
460/// block; a declaration written before the key existed gets it appended.
461#[must_use]
462pub fn with_writing_style(text: &str, selection: &WritingStyle) -> String {
463    with_block(
464        text,
465        "writing_style:",
466        &selection.render(),
467        "# Where the writing style comes from: `builtin` routes authors to\n\
468         # `sdd method writing-style`, `project` routes them to the document\n\
469         # `path` names, and `none` installs no route and imposes no conversion\n\
470         # obligation.\n",
471    )
472}
473
474/// Record an acquisition decision in a declaration, keeping every comment.
475///
476/// SATISFIES acquisition:a-host-install-is-a-recorded-decision
477#[must_use]
478pub fn with_acquisition(text: &str, decision: &Acquisition) -> String {
479    with_block(
480        text,
481        "acquisition:",
482        &decision.render(),
483        "# How every host obtains sdd. `source: host` means each host installs\n\
484         # it itself, at `minimum` or newer, because no manager file records a\n\
485         # pin for this repository.\n",
486    )
487}
488
489/// Whether `id` is a migration id: the UTC stamp `%Y%m%dT%H%M%SZ` a run
490/// names its workspace by, with `-<n>` for the `n`th run in one second.
491///
492/// The exact form is what keeps an id one path segment inside the state
493/// root, so `..` or a separator can never reach the workspace path.
494#[must_use]
495pub fn is_migration_id(id: &str) -> bool {
496    let (stamp, counter) = id
497        .split_once('-')
498        .map_or((id, None), |(stamp, n)| (stamp, Some(n)));
499    let bytes = stamp.as_bytes();
500    let digits = |range: std::ops::Range<usize>| bytes[range].iter().all(u8::is_ascii_digit);
501    let stamped =
502        bytes.len() == 16 && digits(0..8) && bytes[8] == b'T' && digits(9..15) && bytes[15] == b'Z';
503    let numbered = counter.is_none_or(|n| {
504        !n.is_empty()
505            && !n.starts_with('0')
506            && n.bytes().all(|b| b.is_ascii_digit())
507            && n.parse::<u32>().is_ok_and(|n| n >= 2)
508    });
509    stamped && numbered
510}
511
512/// The comment `with_migration` writes above the key.
513const MIGRATION_COMMENT: &str = "# The migration this repository holds open. Its archive and registry\n\
514     # live under this id in the state root of sdd, and `sdd migrate close`\n\
515     # removes this key.\n";
516
517/// Record an open migration in a declaration, keeping every comment.
518///
519/// SATISFIES setup:an-open-migration-is-declared
520#[must_use]
521pub fn with_migration(text: &str, id: &str) -> String {
522    with_block(
523        text,
524        "migration:",
525        &format!("{}\n", migration_line(id)),
526        MIGRATION_COMMENT,
527    )
528}
529
530/// The line that records an open migration, exactly as
531/// [`with_migration`] writes it, so a search of the history for that line
532/// finds the commit that recorded the migration and nothing else.
533#[must_use]
534pub fn migration_line(id: &str) -> String {
535    format!("migration: {}", quoted(id))
536}
537
538/// Remove the open migration from a declaration, and the comment and the
539/// blank line `with_migration` wrote with it, so the declaration reads as it
540/// did before the key was recorded.
541#[must_use]
542pub fn without_migration(text: &str) -> String {
543    let lines: Vec<&str> = text.lines().collect();
544    let Some(key) = lines.iter().position(|line| line.starts_with("migration:")) else {
545        return text.to_string();
546    };
547    let mut end = key + 1;
548    while end < lines.len() && (lines[end].starts_with(' ') || lines[end].starts_with('\t')) {
549        end += 1;
550    }
551    let comment: Vec<&str> = MIGRATION_COMMENT.lines().collect();
552    let mut start = key;
553    if key >= comment.len() && lines[key - comment.len()..key] == comment[..] {
554        start = key - comment.len();
555        if start > 0 && lines[start - 1].is_empty() {
556            start -= 1;
557        }
558    }
559    let mut out = String::new();
560    for line in lines[..start].iter().chain(&lines[end..]) {
561        out.push_str(line);
562        out.push('\n');
563    }
564    out
565}
566
567/// Replace one top-level key and its indented children as a block, or
568/// append it under a comment where the declaration has no such key.
569fn with_block(text: &str, key: &str, block: &str, comment: &str) -> String {
570    let mut out = String::new();
571    let mut wrote = false;
572    let mut skipping = false;
573    for line in text.lines() {
574        if skipping {
575            if line.starts_with(' ') || line.starts_with('\t') {
576                continue;
577            }
578            skipping = false;
579        }
580        if !wrote && line.starts_with(key) {
581            out.push_str(block);
582            wrote = true;
583            skipping = true;
584            continue;
585        }
586        out.push_str(line);
587        out.push('\n');
588    }
589    if !wrote {
590        if !out.is_empty() && !out.ends_with("\n\n") {
591            out.push('\n');
592        }
593        out.push_str(comment);
594        out.push_str(block);
595    }
596    out
597}
598
599/// Record reserved paths in a declaration, keeping every comment.
600///
601/// The file is hand-edited and its comments carry the whole explanation of
602/// the four layers, so this rewrites one key textually rather than
603/// round-tripping the YAML. A path already recorded is left alone, which is
604/// what makes a repeated `--reserve` idempotent.
605#[must_use]
606pub fn with_reserved(text: &str, paths: &[String]) -> String {
607    if paths.is_empty() {
608        return text.to_string();
609    }
610    let existing = InstanceConfig::parse(text).unwrap_or_default().reserved;
611    let mut added: Vec<&String> = paths
612        .iter()
613        .filter(|path| !existing.contains(path))
614        .collect();
615    added.dedup();
616    if added.is_empty() {
617        return text.to_string();
618    }
619
620    let entries: String = existing
621        .iter()
622        .map(|path| format!("  - {}\n", quoted(path)))
623        .chain(added.iter().map(|path| format!("  - {}\n", quoted(path))))
624        .collect();
625
626    let mut out = String::new();
627    let mut wrote = false;
628    let mut skipping = false;
629    for line in text.lines() {
630        if skipping {
631            // Drop the previous list items, which the rewritten key carries.
632            if line.starts_with("  - ") || line.trim().is_empty() && !wrote {
633                continue;
634            }
635            skipping = false;
636        }
637        if !wrote && (line.starts_with("reserved:")) {
638            out.push_str("reserved:\n");
639            out.push_str(&entries);
640            wrote = true;
641            skipping = true;
642            continue;
643        }
644        out.push_str(line);
645        out.push('\n');
646    }
647    if !wrote {
648        out.push_str("reserved:\n");
649        out.push_str(&entries);
650    }
651    out
652}
653
654#[cfg(test)]
655mod tests {
656    use super::*;
657    use crate::domain::path_filter::Decision;
658
659    fn config(text: &str) -> InstanceConfig {
660        InstanceConfig::parse(text).expect("the fixture parses")
661    }
662
663    #[test]
664    fn an_absent_file_is_the_empty_declaration() {
665        let dir = tempfile::tempdir().expect("a scratch directory");
666        let root = camino::Utf8PathBuf::from_path_buf(dir.path().to_path_buf())
667            .expect("the scratch path is UTF-8");
668        let read = InstanceConfig::read(&root).expect("an absent file is not an error");
669        assert_eq!(read, InstanceConfig::default());
670    }
671
672    #[test]
673    fn an_empty_file_is_the_empty_declaration() {
674        assert_eq!(config("{}\n"), InstanceConfig::default());
675    }
676
677    #[test]
678    fn a_malformed_key_is_an_error_naming_the_key() {
679        let error = InstanceConfig::parse("reserved: AGENTS.md\n")
680            .expect_err("a scalar where a list belongs is refused");
681        assert!(
682            error.to_string().contains("reserved"),
683            "the error does not name the key: {error}"
684        );
685    }
686
687    #[test]
688    fn an_open_migration_round_trips_to_the_bytes_it_started_from() {
689        let seed = "# What the gates judge.\nreserved: []\n";
690        let open = with_migration(seed, "20261009T213000Z");
691        assert_eq!(config(&open).migration.as_deref(), Some("20261009T213000Z"));
692        assert_eq!(without_migration(&open), seed);
693        assert_eq!(without_migration(seed), seed);
694        assert!(InstanceConfig::parse("migration: '20261009T213000Z-2'\n").is_ok());
695        assert!(InstanceConfig::parse("migration: '20261009T213000Z-12'\n").is_ok());
696        for refused in [
697            "../x",
698            "20261009T213000Z-1",
699            "20261009T213000Z-0",
700            "20261009T213000Z-02",
701            "20261009T213000Z-",
702            "20261009T213000",
703            "2026100XT213000Z",
704            "20261009T213000Z/..",
705            "20261009T14020é",
706            "20261009T1402é0Z",
707            "20261009T213000Z-é",
708            "ééééééééééééééé",
709        ] {
710            let error =
711                InstanceConfig::parse(&format!("migration: '{refused}'\n")).expect_err(refused);
712            assert!(
713                error
714                    .to_string()
715                    .contains("setup:an-open-migration-is-declared"),
716                "{error}"
717            );
718        }
719    }
720
721    #[test]
722    fn a_host_decision_parses_renders_and_reads_back() {
723        let decision = Acquisition {
724            source: AcquisitionSource::Host,
725            minimum: "0.13.2".to_string(),
726        };
727        let text = with_acquisition("reserved: []\n", &decision);
728        assert!(text.contains("# How every host obtains sdd."), "{text}");
729        assert_eq!(config(&text).acquisition, Some(decision.clone()));
730        // A second write replaces the block rather than adding one.
731        let moved = Acquisition {
732            minimum: "0.14.0".to_string(),
733            ..decision
734        };
735        let again = with_acquisition(&text, &moved);
736        assert_eq!(again.matches("acquisition:").count(), 1, "{again}");
737        assert_eq!(config(&again).acquisition, Some(moved));
738    }
739
740    #[test]
741    fn an_acquisition_this_version_cannot_read_is_refused() {
742        assert!(InstanceConfig::parse("acquisition:\n  source: host\n  minimum: soon\n").is_err());
743        assert!(
744            InstanceConfig::parse("acquisition:\n  source: brew\n  minimum: '0.1.0'\n").is_err()
745        );
746        assert!(InstanceConfig::parse("acquisition:\n  source: host\n").is_err());
747    }
748
749    #[test]
750    fn an_unknown_key_is_refused() {
751        assert!(InstanceConfig::parse("reservd:\n  - a.md\n").is_err());
752    }
753
754    #[test]
755    fn an_unknown_gate_id_is_an_error_naming_the_key() {
756        let error = InstanceConfig::parse("gates:\n  no-such-gate:\n    exclude: [a]\n")
757            .expect_err("an unknown gate is refused");
758        assert!(matches!(error, ConfigError::UnknownGate(ref key) if key == "no-such-gate"));
759    }
760
761    #[test]
762    fn a_known_gate_id_parses() {
763        let parsed = config("gates:\n  no-personal-path:\n    exclude:\n      - vendor/**\n");
764        assert_eq!(
765            parsed
766                .for_gate(GateId::NoPersonalPath)
767                .map(|f| f.exclude.clone()),
768            Some(vec!["vendor/**".to_string()])
769        );
770    }
771
772    #[test]
773    fn a_path_leaving_the_repository_is_refused() {
774        let error = resolve(&[], &[], None, &[], &[], &["../outside/**".to_string()])
775            .expect_err("a pattern that climbs out is refused");
776        assert!(matches!(error, ConfigError::Pattern(_)));
777    }
778
779    #[test]
780    fn a_project_include_replaces_the_registry_include() {
781        let filter = resolve(
782            &["_docs/**/*.md".to_string()],
783            &[],
784            Some(&GateFilters {
785                include: vec!["method/**/*.md".to_string()],
786                exclude: Vec::new(),
787            }),
788            &[],
789            &[],
790            &[],
791        )
792        .expect("resolves");
793        assert_eq!(
794            filter.decide(Utf8Path::new("method/gates.md")),
795            Decision::Read
796        );
797        assert_eq!(
798            filter.decide(Utf8Path::new("_docs/specs/SPEC-a.md")),
799            Decision::NotIncluded,
800            "the registry include survived a project include that replaces it"
801        );
802    }
803
804    #[test]
805    fn every_exclude_layer_extends() {
806        let filter = resolve(
807            &[],
808            &["a.md".to_string()],
809            Some(&GateFilters {
810                include: Vec::new(),
811                exclude: vec!["b.md".to_string()],
812            }),
813            &[],
814            &["c.md".to_string()],
815            &["d.md".to_string()],
816        )
817        .expect("resolves");
818        for path in ["a.md", "b.md", "c.md", "d.md"] {
819            assert!(
820                matches!(filter.decide(Utf8Path::new(path)), Decision::Skipped(_)),
821                "{path} survived its exclude layer"
822            );
823        }
824    }
825
826    #[test]
827    fn reserved_wins_over_a_gate_entry_that_includes_it() {
828        let filter = resolve(
829            &[],
830            &[],
831            Some(&GateFilters {
832                include: vec!["AGENTS.md".to_string()],
833                exclude: Vec::new(),
834            }),
835            &[],
836            &[],
837            &["AGENTS.md".to_string()],
838        )
839        .expect("resolves");
840        match filter.decide(Utf8Path::new("AGENTS.md")) {
841            Decision::Skipped(pattern) => assert_eq!(pattern.layer, Layer::Reserved),
842            other => panic!("reserved did not win: {other:?}"),
843        }
844    }
845
846    #[test]
847    fn reserving_a_path_keeps_every_comment() {
848        let seed = "# why this file exists\nreserved: []\n\n# per gate\ngates: {}\n";
849        let out = with_reserved(seed, &["AGENTS.md".to_string()]);
850        assert!(
851            out.contains("# why this file exists"),
852            "a comment was lost:\n{out}"
853        );
854        assert!(out.contains("# per gate"), "a comment was lost:\n{out}");
855        assert!(
856            out.contains("  - 'AGENTS.md'"),
857            "the path is missing:\n{out}"
858        );
859        assert_eq!(
860            InstanceConfig::parse(&out).expect("still parses").reserved,
861            vec!["AGENTS.md".to_string()]
862        );
863    }
864
865    #[test]
866    fn reserving_a_recorded_path_changes_nothing() {
867        let text = "reserved:\n  - 'AGENTS.md'\ngates: {}\n";
868        assert_eq!(with_reserved(text, &["AGENTS.md".to_string()]), text);
869    }
870
871    #[test]
872    fn a_glob_is_written_as_a_yaml_scalar_that_reads_back() {
873        // `*`, `[`, `{`, and `#` all open something in YAML, and the filter
874        // grammar accepts globs starting with the first three.
875        for glob in ["**/generated.md", "[ab]/x.md", "{a,b}/x.md", "it's/x.md"] {
876            let out = with_reserved("reserved: []\ngates: {}\n", &[glob.to_string()]);
877            assert_eq!(
878                InstanceConfig::parse(&out)
879                    .unwrap_or_else(|e| panic!("{glob} did not read back: {e}"))
880                    .reserved,
881                vec![glob.to_string()],
882                "for {glob}"
883            );
884        }
885    }
886
887    #[test]
888    fn a_refused_pattern_fails_at_the_declaration_boundary() {
889        // Not where a gate runs, and not after the managed block carries it.
890        let error = InstanceConfig::parse("reserved:\n  - '!negated'\ngates: {}\n")
891            .expect_err("a negation is refused at parse");
892        assert!(matches!(error, ConfigError::Pattern(_)));
893        assert!(
894            InstanceConfig::parse("gates:\n  no-personal-path:\n    exclude: ['a[']\n").is_err()
895        );
896    }
897
898    #[test]
899    fn reserving_adds_beside_what_is_recorded() {
900        let text = "reserved:\n  - AGENTS.md\ngates: {}\n";
901        let out = with_reserved(text, &["vendor/**".to_string()]);
902        assert_eq!(
903            InstanceConfig::parse(&out).expect("parses").reserved,
904            vec!["AGENTS.md".to_string(), "vendor/**".to_string()]
905        );
906    }
907
908    #[test]
909    fn an_absent_key_is_builtin() {
910        assert_eq!(
911            config("reserved: []\ngates: {}\n").writing_style,
912            WritingStyle::default()
913        );
914        assert_eq!(
915            config("writing_style:\n  source: builtin\n  path: null\n")
916                .writing_style
917                .route(),
918            Some("`sdd method writing-style`".to_string())
919        );
920    }
921
922    #[test]
923    fn project_without_a_path_is_an_error_naming_the_key() {
924        let error = InstanceConfig::parse("writing_style:\n  source: project\n")
925            .expect_err("a project source needs a path");
926        assert!(matches!(error, ConfigError::WritingStyle(_)));
927        assert!(error.to_string().contains("writing_style"), "{error}");
928        assert!(error.to_string().contains("path"), "{error}");
929    }
930
931    #[test]
932    fn a_path_without_the_project_source_is_an_error() {
933        for source in ["builtin", "none"] {
934            let error = InstanceConfig::parse(&format!(
935                "writing_style:\n  source: {source}\n  path: docs/style.md\n"
936            ))
937            .expect_err("a path nothing reads is refused");
938            assert!(error.to_string().contains("nothing reads it"), "{error}");
939        }
940    }
941
942    #[test]
943    fn a_writing_style_path_leaving_the_repository_is_refused() {
944        for path in ["/etc/style.md", "../style.md", "docs/../../style.md"] {
945            assert!(
946                WritingStyle::parse_flag(&format!("project:{path}")).is_err(),
947                "{path} was accepted"
948            );
949        }
950        assert_eq!(
951            WritingStyle::parse_flag("project:docs/STYLE.md")
952                .unwrap()
953                .route(),
954            Some("`docs/STYLE.md`".to_string())
955        );
956        assert_eq!(WritingStyle::parse_flag("none").unwrap().route(), None);
957        assert!(WritingStyle::parse_flag("house").is_err());
958    }
959
960    #[test]
961    fn a_selection_is_written_into_the_declaration_and_reads_back() {
962        let seed = "reserved: []\n\n# how to write\nwriting_style:\n  source: builtin\n  path: null\n\ngates: {}\n";
963        let selection = WritingStyle::parse_flag("project:docs/STYLE.md").unwrap();
964        let out = with_writing_style(seed, &selection);
965        assert!(out.contains("# how to write"), "a comment was lost:\n{out}");
966        assert!(out.contains("gates: {}"), "a later key was lost:\n{out}");
967        assert_eq!(config(&out).writing_style, selection);
968
969        // A declaration written before the key existed gets it appended.
970        let older = "reserved: []\ngates: {}\n";
971        let out = with_writing_style(older, &WritingStyle::parse_flag("none").unwrap());
972        assert_eq!(config(&out).writing_style.source, WritingSource::None);
973        assert!(config(&out).reserved.is_empty());
974    }
975
976    #[test]
977    fn no_layer_can_reopen_an_exclusion() {
978        // The grammar carries no negation, so there is nothing to write that
979        // would undo an earlier exclude. This asserts the refusal rather
980        // than the absence.
981        let error = resolve(&[], &[], None, &[], &["!a.md".to_string()], &[])
982            .expect_err("a negation is refused");
983        assert!(matches!(error, ConfigError::Pattern(_)));
984    }
985}