Skip to main content

code_system_graph_core/
config.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3
4use code_system_graph_model::stable_id;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9use crate::ignore_policy::discover_repository_files_matching;
10use crate::{
11    CapabilityDir, CapabilityError, ContractImplementationConfig, HttpConsumerConfig, IgnorePatternError, IgnorePolicy, IntegrationTestConfig, MAX_REPOSITORY_CONFIG_BYTES, RegularFileEntry, RepositoryConfig, RepositoryDiscoveryError, validate_excludes, validate_include_defaults
12};
13
14const LOCAL_CONFIG_NAME: &str = ".code-system-graph.yaml";
15const MAX_OPENAPI_DISCOVERY_DEPTH: usize = 8;
16const MAX_OPENAPI_CANDIDATES: usize = 32;
17
18/// Origin of an effective repository configuration value.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
20#[serde(rename_all = "snake_case")]
21pub enum ConfigSource {
22    /// Explicit command-line override.
23    CliOverride,
24    /// Explicit workspace manifest value.
25    WorkspaceManifest,
26    /// Repository-local `.code-system-graph.yaml` value.
27    RepositoryLocal,
28    /// Deterministic filesystem auto-detection.
29    AutoDetected,
30    /// Safe built-in default.
31    Default,
32}
33
34/// Applies the highest-precedence command-line `OpenAPI` override.
35///
36/// # Errors
37///
38/// Returns [`ConfigError::EmptyField`] when the override is empty.
39pub fn apply_openapi_override(
40    config: &mut EffectiveRepositoryConfig,
41    openapi: &str,
42) -> Result<(), ConfigError> {
43    if openapi.trim().is_empty() {
44        return Err(ConfigError::EmptyField {
45            path: PathBuf::from("<cli>"),
46            field: "repoOpenapi".to_owned(),
47        });
48    }
49    let previous_fingerprint = config.fingerprint.clone();
50    config.openapi = vec![openapi.to_owned()];
51    config.openapi_source = ConfigSource::CliOverride;
52    config.fingerprint = stable_id(
53        "repo-config",
54        &format!("base={previous_fingerprint};cli_openapi={openapi}"),
55    );
56    Ok(())
57}
58
59/// Strict merged repository configuration after precedence resolution.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
61pub struct EffectiveRepositoryConfig {
62    /// Effective automatic-discovery exclusion policy.
63    pub ignore_policy: IgnorePolicy,
64    /// Selected `OpenAPI` artifacts relative to the checkout root.
65    pub openapi: Vec<String>,
66    /// Source that selected the `OpenAPI` artifacts.
67    pub openapi_source: ConfigSource,
68    /// Selected explicit HTTP consumers.
69    pub http_consumers: Vec<HttpConsumerConfig>,
70    /// Source that selected the HTTP consumers.
71    pub http_consumers_source: ConfigSource,
72    /// Selected explicit cross-language integration tests.
73    pub integration_tests: Vec<IntegrationTestConfig>,
74    /// Source that selected integration tests.
75    pub integration_tests_source: ConfigSource,
76    /// Selected explicit contract implementation anchors.
77    pub implementations: Vec<ContractImplementationConfig>,
78    /// Source that selected implementation anchors.
79    pub implementations_source: ConfigSource,
80    /// Fingerprint of all effective values and relevant local configuration.
81    pub fingerprint: String,
82}
83
84#[derive(Debug, Deserialize)]
85#[serde(rename_all = "camelCase", deny_unknown_fields)]
86struct RepositoryLocalConfig {
87    version: u32,
88    openapi: Option<String>,
89    http_consumers: Option<Vec<HttpConsumerConfig>>,
90    integration_tests: Option<Vec<IntegrationTestConfig>>,
91    implementations: Option<Vec<ContractImplementationConfig>>,
92    excludes: Option<Vec<String>>,
93    include_defaults: Option<Vec<String>>,
94    use_gitignore: Option<bool>,
95}
96
97/// Error returned while resolving repository configuration precedence.
98#[derive(Debug, Error)]
99pub enum ConfigError {
100    /// Repository-local configuration could not be read.
101    #[error("failed to read repository config `{path}`: {source}")]
102    Read {
103        /// Configuration path.
104        path: PathBuf,
105        /// Underlying filesystem error.
106        source: std::io::Error,
107    },
108    /// Repository-local configuration is malformed or contains unknown keys.
109    #[error("invalid repository config `{path}`: {source}")]
110    Invalid {
111        /// Configuration path.
112        path: PathBuf,
113        /// YAML decoding error.
114        source: Box<serde_saphyr::DeserializeError>,
115    },
116    /// Repository-local configuration schema version is unsupported.
117    #[error("unsupported repository config version {found} in `{path}`; expected version 1")]
118    UnsupportedVersion {
119        /// Configuration path.
120        path: PathBuf,
121        /// Version found in the file.
122        found: u32,
123    },
124    /// A configured value is empty.
125    #[error("repository config field `{field}` in `{path}` must not be empty")]
126    EmptyField {
127        /// Configuration path.
128        path: PathBuf,
129        /// Dot-style field location.
130        field: String,
131    },
132    /// Auto-detection found multiple plausible `OpenAPI` artifacts.
133    #[error("ambiguous OpenAPI auto-detection in `{root}`: {candidates:?}")]
134    AmbiguousOpenApi {
135        /// Repository checkout root.
136        root: PathBuf,
137        /// Candidate paths in deterministic order.
138        candidates: Vec<String>,
139    },
140    /// A repository-local discovery pattern is malformed or unsafe.
141    #[error("repository config field `{field}` in `{path}` is invalid: {source}")]
142    InvalidIgnorePattern {
143        /// Configuration path.
144        path: PathBuf,
145        /// Dot-style field location.
146        field: String,
147        /// Pattern validation failure.
148        #[source]
149        source: IgnorePatternError,
150    },
151    /// Automatic repository discovery or an enabled `.gitignore` file failed.
152    #[error(transparent)]
153    Discovery(#[from] RepositoryDiscoveryError),
154    /// Repository-local configuration is a symbolic link or reparse point.
155    #[error("repository config `{path}` is a symbolic link or reparse point")]
156    Symlink {
157        /// Configuration path.
158        path: PathBuf,
159    },
160    /// Repository-local configuration is not a regular file.
161    #[error("repository config `{path}` is not a regular file")]
162    NotRegularFile {
163        /// Configuration path.
164        path: PathBuf,
165    },
166    /// Repository-local configuration exceeds the accepted size limit.
167    #[error("repository config `{path}` exceeds {limit} bytes")]
168    TooLarge {
169        /// Configuration path.
170        path: PathBuf,
171        /// Maximum accepted size in bytes.
172        limit: usize,
173    },
174    /// Repository-local configuration resolves outside the checkout root.
175    #[error("repository config `{path}` is outside checkout `{checkout}`")]
176    OutsideCheckout {
177        /// Configuration path.
178        path: PathBuf,
179        /// Canonical checkout root.
180        checkout: PathBuf,
181    },
182}
183
184/// Resolves workspace, repository-local, auto-detected, and default values in that order.
185///
186/// An explicit empty workspace `httpConsumers` list suppresses lower-precedence values.
187/// Auto-detection never chooses among multiple candidates.
188///
189/// # Errors
190///
191/// Returns [`ConfigError`] for unreadable or invalid local configuration, empty values, or
192/// ambiguous auto-detection.
193pub fn resolve_repository_config(
194    checkout_path: &Path,
195    workspace: &RepositoryConfig,
196) -> Result<EffectiveRepositoryConfig, ConfigError> {
197    resolve_repository_config_with_use_gitignore(checkout_path, workspace, None)
198}
199
200/// Resolves repository configuration with an additive workspace-level `.gitignore` choice.
201///
202/// This companion API keeps [`RepositoryConfig`] exhaustively constructible for patch-version
203/// source compatibility.
204///
205/// # Errors
206///
207/// Returns the same errors as [`resolve_repository_config`].
208pub fn resolve_repository_config_with_use_gitignore(
209    checkout_path: &Path,
210    workspace: &RepositoryConfig,
211    workspace_use_gitignore: Option<bool>,
212) -> Result<EffectiveRepositoryConfig, ConfigError> {
213    let checkout = CapabilityDir::open(checkout_path)
214        .map_err(|error| map_capability_error(error, checkout_path, LOCAL_CONFIG_NAME))?;
215    let local_relative = Path::new(LOCAL_CONFIG_NAME);
216    let (local, local_source) = match checkout
217        .classify_regular_file_entry(local_relative)
218        .map_err(|error| map_capability_error(error, checkout_path, LOCAL_CONFIG_NAME))?
219    {
220        RegularFileEntry::Absent => (None, None),
221        RegularFileEntry::Regular => {
222            let local_path = checkout_path.join(LOCAL_CONFIG_NAME);
223            let source = checkout
224                .read_utf8_file_bounded(local_relative, MAX_REPOSITORY_CONFIG_BYTES)
225                .map_err(|error| map_capability_error(error, checkout_path, LOCAL_CONFIG_NAME))?;
226            let config: RepositoryLocalConfig =
227                crate::yaml::from_str(&source).map_err(|source| ConfigError::Invalid {
228                    path: local_path.clone(),
229                    source: Box::new(source),
230                })?;
231            validate_local(&local_path, &config)?;
232            (Some(config), Some(source))
233        }
234    };
235
236    let ignore_policy = resolve_ignore_policy(
237        checkout_path,
238        workspace,
239        workspace_use_gitignore,
240        local.as_ref(),
241    )?;
242    let (openapi, openapi_source) = if let Some(openapi) = &workspace.openapi {
243        (vec![openapi.clone()], ConfigSource::WorkspaceManifest)
244    } else if let Some(openapi) = local.as_ref().and_then(|config| config.openapi.clone()) {
245        (vec![openapi], ConfigSource::RepositoryLocal)
246    } else {
247        let candidates = discover_openapi_candidates(checkout_path, &ignore_policy)?;
248        if candidates.is_empty() {
249            (Vec::new(), ConfigSource::Default)
250        } else {
251            reject_competing_openapi_formats(checkout_path, &candidates)?;
252            (candidates, ConfigSource::AutoDetected)
253        }
254    };
255    let (http_consumers, http_consumers_source) = if let Some(consumers) = &workspace.http_consumers
256    {
257        (consumers.clone(), ConfigSource::WorkspaceManifest)
258    } else if let Some(consumers) = local
259        .as_ref()
260        .and_then(|config| config.http_consumers.clone())
261    {
262        (consumers, ConfigSource::RepositoryLocal)
263    } else {
264        (Vec::new(), ConfigSource::Default)
265    };
266    let (integration_tests, integration_tests_source) =
267        if let Some(tests) = &workspace.integration_tests {
268            (tests.clone(), ConfigSource::WorkspaceManifest)
269        } else if let Some(tests) = local
270            .as_ref()
271            .and_then(|config| config.integration_tests.clone())
272        {
273            (tests, ConfigSource::RepositoryLocal)
274        } else {
275            (Vec::new(), ConfigSource::Default)
276        };
277    let (implementations, implementations_source) =
278        if let Some(implementations) = &workspace.implementations {
279            (implementations.clone(), ConfigSource::WorkspaceManifest)
280        } else if let Some(implementations) = local
281            .as_ref()
282            .and_then(|config| config.implementations.clone())
283        {
284            (implementations, ConfigSource::RepositoryLocal)
285        } else {
286            (Vec::new(), ConfigSource::Default)
287        };
288    let fingerprint_material = format!(
289        "openapi={openapi:?};openapi_source={openapi_source:?};\
290         consumers={http_consumers:?};consumers_source={http_consumers_source:?};\
291         tests={integration_tests:?};tests_source={integration_tests_source:?};\
292         implementations={implementations:?};implementations_source={implementations_source:?};\
293         ignore_policy={};\
294         local={local_source:?}",
295        ignore_policy.fingerprint_material()
296    );
297    Ok(EffectiveRepositoryConfig {
298        ignore_policy,
299        openapi,
300        openapi_source,
301        http_consumers,
302        http_consumers_source,
303        integration_tests,
304        integration_tests_source,
305        implementations,
306        implementations_source,
307        fingerprint: stable_id("repo-config", &fingerprint_material),
308    })
309}
310
311fn map_capability_error(error: CapabilityError, checkout: &Path, config_name: &str) -> ConfigError {
312    let path = checkout.join(config_name);
313    match error {
314        CapabilityError::Io { path, source } => ConfigError::Read { path, source },
315        CapabilityError::Symlink { .. } => ConfigError::Symlink { path },
316        CapabilityError::NotRegularFile { .. } => ConfigError::NotRegularFile { path },
317        CapabilityError::TooLarge { limit, .. } => ConfigError::TooLarge { path, limit },
318        CapabilityError::OutsideRoot { root, .. } => ConfigError::OutsideCheckout {
319            path,
320            checkout: root,
321        },
322        CapabilityError::InvalidRelativePath { .. }
323        | CapabilityError::NotDirectory { .. }
324        | CapabilityError::InvalidUtf8 { .. } => ConfigError::Read {
325            path,
326            source: std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()),
327        },
328    }
329}
330
331fn discover_openapi_candidates(
332    root: &Path,
333    ignore_policy: &IgnorePolicy,
334) -> Result<Vec<String>, ConfigError> {
335    let mut candidates = Vec::new();
336    for relative in discover_repository_files_matching(
337        root,
338        ignore_policy,
339        Some(MAX_OPENAPI_DISCOVERY_DEPTH.saturating_add(1)),
340        Some(MAX_OPENAPI_CANDIDATES),
341        |relative| {
342            relative
343                .file_name()
344                .and_then(|value| value.to_str())
345                .is_some_and(openapi_filename)
346        },
347    )? {
348        candidates.push(relative.to_string_lossy().replace('\\', "/"));
349    }
350    candidates.sort();
351    candidates.dedup();
352    Ok(candidates)
353}
354
355fn openapi_filename(name: &str) -> bool {
356    let lower = name.to_ascii_lowercase();
357    lower.contains("openapi")
358        && matches!(
359            Path::new(&lower)
360                .extension()
361                .and_then(|value| value.to_str()),
362            Some("json" | "yaml" | "yml")
363        )
364}
365
366fn reject_competing_openapi_formats(root: &Path, candidates: &[String]) -> Result<(), ConfigError> {
367    let mut by_stem = BTreeMap::<String, Vec<String>>::new();
368    for candidate in candidates {
369        let path = Path::new(candidate);
370        let parent = path.parent().unwrap_or_else(|| Path::new(""));
371        let stem = path
372            .file_stem()
373            .and_then(|value| value.to_str())
374            .unwrap_or(candidate);
375        by_stem
376            .entry(parent.join(stem).to_string_lossy().to_string())
377            .or_default()
378            .push(candidate.clone());
379    }
380    let ambiguous = by_stem
381        .into_values()
382        .filter(|values| values.len() > 1)
383        .flatten()
384        .collect::<Vec<_>>();
385    if ambiguous.is_empty() {
386        Ok(())
387    } else {
388        Err(ConfigError::AmbiguousOpenApi {
389            root: root.to_path_buf(),
390            candidates: ambiguous,
391        })
392    }
393}
394
395fn validate_local(path: &Path, config: &RepositoryLocalConfig) -> Result<(), ConfigError> {
396    if config.version != 1 {
397        return Err(ConfigError::UnsupportedVersion {
398            path: path.to_path_buf(),
399            found: config.version,
400        });
401    }
402    if config
403        .openapi
404        .as_ref()
405        .is_some_and(|value| value.trim().is_empty())
406    {
407        return Err(ConfigError::EmptyField {
408            path: path.to_path_buf(),
409            field: "openapi".to_owned(),
410        });
411    }
412    for (index, consumer) in config.http_consumers.iter().flatten().enumerate() {
413        for (field, value) in [
414            ("method", consumer.method.as_str()),
415            ("path", consumer.path.as_str()),
416            ("source", consumer.source.as_str()),
417        ] {
418            if value.trim().is_empty() {
419                return Err(ConfigError::EmptyField {
420                    path: path.to_path_buf(),
421                    field: format!("httpConsumers[{index}].{field}"),
422                });
423            }
424        }
425    }
426    for (index, test) in config.integration_tests.iter().flatten().enumerate() {
427        for (field, value) in [
428            ("name", test.name.as_str()),
429            ("path", test.path.as_str()),
430            ("framework", test.framework.as_str()),
431            ("language", test.language.as_str()),
432            ("validates.method", test.validates.method.as_str()),
433            ("validates.path", test.validates.path.as_str()),
434        ] {
435            if value.trim().is_empty() {
436                return Err(ConfigError::EmptyField {
437                    path: path.to_path_buf(),
438                    field: format!("integrationTests[{index}].{field}"),
439                });
440            }
441        }
442    }
443    for (index, implementation) in config.implementations.iter().flatten().enumerate() {
444        for (field, value) in [
445            ("language", implementation.language.as_str()),
446            ("path", implementation.path.as_str()),
447            ("symbol", implementation.symbol.as_str()),
448            (
449                "implements.method",
450                implementation.implements.method.as_str(),
451            ),
452            ("implements.path", implementation.implements.path.as_str()),
453        ] {
454            if value.trim().is_empty() {
455                return Err(ConfigError::EmptyField {
456                    path: path.to_path_buf(),
457                    field: format!("implementations[{index}].{field}"),
458                });
459            }
460        }
461    }
462    if let Some(patterns) = &config.excludes {
463        validate_excludes(patterns).map_err(|source| ConfigError::InvalidIgnorePattern {
464            path: path.to_path_buf(),
465            field: "excludes".to_owned(),
466            source,
467        })?;
468    }
469    if let Some(patterns) = &config.include_defaults {
470        validate_include_defaults(patterns).map_err(|source| {
471            ConfigError::InvalidIgnorePattern {
472                path: path.to_path_buf(),
473                field: "includeDefaults".to_owned(),
474                source,
475            }
476        })?;
477    }
478    Ok(())
479}
480
481fn select_patterns(
482    workspace: Option<&Vec<String>>,
483    local: Option<&Vec<String>>,
484) -> (Vec<String>, ConfigSource) {
485    if let Some(patterns) = workspace {
486        (patterns.clone(), ConfigSource::WorkspaceManifest)
487    } else if let Some(patterns) = local {
488        (patterns.clone(), ConfigSource::RepositoryLocal)
489    } else {
490        (Vec::new(), ConfigSource::Default)
491    }
492}
493
494fn select_flag(workspace: Option<bool>, local: Option<bool>) -> (bool, ConfigSource) {
495    if let Some(value) = workspace {
496        (value, ConfigSource::WorkspaceManifest)
497    } else if let Some(value) = local {
498        (value, ConfigSource::RepositoryLocal)
499    } else {
500        (false, ConfigSource::Default)
501    }
502}
503
504fn resolve_ignore_policy(
505    checkout_path: &Path,
506    workspace: &RepositoryConfig,
507    workspace_use_gitignore: Option<bool>,
508    local: Option<&RepositoryLocalConfig>,
509) -> Result<IgnorePolicy, ConfigError> {
510    let (excludes, excludes_source) = select_patterns(
511        workspace.excludes.as_ref(),
512        local.and_then(|config| config.excludes.as_ref()),
513    );
514    let (include_defaults, include_defaults_source) = select_patterns(
515        workspace.include_defaults.as_ref(),
516        local.and_then(|config| config.include_defaults.as_ref()),
517    );
518    let (use_gitignore, use_gitignore_source) = select_flag(
519        workspace_use_gitignore,
520        local.and_then(|config| config.use_gitignore),
521    );
522    IgnorePolicy::with_gitignore(
523        excludes,
524        excludes_source,
525        include_defaults,
526        include_defaults_source,
527        use_gitignore,
528        use_gitignore_source,
529    )
530    .map_err(|source| ConfigError::InvalidIgnorePattern {
531        path: checkout_path.to_path_buf(),
532        field: "ignorePolicy".to_owned(),
533        source,
534    })
535}
536
537#[cfg(test)]
538mod tests {
539    use std::fs;
540
541    use super::{
542        ConfigError, ConfigSource, resolve_repository_config, resolve_repository_config_with_use_gitignore
543    };
544    use crate::{HttpConsumerConfig, RepositoryConfig};
545
546    #[test]
547    fn workspace_manifest_should_override_repository_local_values()
548    -> Result<(), Box<dyn std::error::Error>> {
549        let repository = tempfile::tempdir()?;
550        fs::write(
551            repository.path().join(".code-system-graph.yaml"),
552            "version: 1\nopenapi: local.yaml\nhttpConsumers: []\n",
553        )?;
554        let workspace = RepositoryConfig {
555            path: ".".to_owned(),
556            openapi: Some("workspace.yaml".to_owned()),
557            http_consumers: Some(vec![HttpConsumerConfig {
558                method: "GET".to_owned(),
559                path: "/health".to_owned(),
560                source: "client.rs".to_owned(),
561            }]),
562            integration_tests: None,
563            implementations: None,
564            excludes: None,
565            include_defaults: None,
566            authorities: None,
567        };
568
569        let resolved = resolve_repository_config(repository.path(), &workspace)?;
570
571        assert_eq!(
572            (
573                resolved.openapi,
574                resolved.openapi_source,
575                resolved.http_consumers.len(),
576                resolved.http_consumers_source,
577            ),
578            (
579                vec!["workspace.yaml".to_owned()],
580                ConfigSource::WorkspaceManifest,
581                1,
582                ConfigSource::WorkspaceManifest,
583            )
584        );
585        Ok(())
586    }
587
588    #[test]
589    fn workspace_ignore_fields_should_override_repository_local_lists()
590    -> Result<(), Box<dyn std::error::Error>> {
591        let repository = tempfile::tempdir()?;
592        fs::write(
593            repository.path().join(".code-system-graph.yaml"),
594            "version: 1\nexcludes: [local/**]\nincludeDefaults: [vendor/local/**]\n",
595        )?;
596        let workspace = RepositoryConfig {
597            path: ".".to_owned(),
598            openapi: None,
599            http_consumers: None,
600            integration_tests: None,
601            implementations: None,
602            excludes: Some(vec!["workspace/**".to_owned()]),
603            include_defaults: Some(Vec::new()),
604            authorities: None,
605        };
606
607        let resolved = resolve_repository_config(repository.path(), &workspace)?;
608
609        assert_eq!(
610            (
611                resolved.ignore_policy.configured_excludes().to_vec(),
612                resolved.ignore_policy.configured_excludes_source(),
613                resolved.ignore_policy.include_defaults().to_vec(),
614                resolved.ignore_policy.include_defaults_source(),
615            ),
616            (
617                vec!["workspace/**".to_owned()],
618                ConfigSource::WorkspaceManifest,
619                Vec::new(),
620                ConfigSource::WorkspaceManifest,
621            )
622        );
623        Ok(())
624    }
625
626    #[test]
627    fn workspace_use_gitignore_should_override_repository_local_value()
628    -> Result<(), Box<dyn std::error::Error>> {
629        let repository = tempfile::tempdir()?;
630        fs::write(
631            repository.path().join(".code-system-graph.yaml"),
632            "version: 1\nuseGitignore: true\n",
633        )?;
634        let workspace = RepositoryConfig {
635            path: ".".to_owned(),
636            openapi: None,
637            http_consumers: None,
638            integration_tests: None,
639            implementations: None,
640            excludes: None,
641            include_defaults: None,
642            authorities: None,
643        };
644
645        let resolved = resolve_repository_config_with_use_gitignore(
646            repository.path(),
647            &workspace,
648            Some(false),
649        )?;
650
651        assert!(!resolved.ignore_policy.use_gitignore());
652        assert_eq!(
653            resolved.ignore_policy.use_gitignore_source(),
654            ConfigSource::WorkspaceManifest
655        );
656        Ok(())
657    }
658
659    #[test]
660    fn repository_local_use_gitignore_should_apply_when_workspace_omits_it()
661    -> Result<(), Box<dyn std::error::Error>> {
662        let repository = tempfile::tempdir()?;
663        fs::write(
664            repository.path().join(".code-system-graph.yaml"),
665            "version: 1\nuseGitignore: true\n",
666        )?;
667        let workspace = RepositoryConfig {
668            path: ".".to_owned(),
669            openapi: None,
670            http_consumers: None,
671            integration_tests: None,
672            implementations: None,
673            excludes: None,
674            include_defaults: None,
675            authorities: None,
676        };
677
678        let resolved = resolve_repository_config(repository.path(), &workspace)?;
679
680        assert!(resolved.ignore_policy.use_gitignore());
681        assert_eq!(
682            resolved.ignore_policy.use_gitignore_source(),
683            ConfigSource::RepositoryLocal
684        );
685        Ok(())
686    }
687
688    #[test]
689    fn openapi_auto_detection_should_respect_gitignore_when_enabled()
690    -> Result<(), Box<dyn std::error::Error>> {
691        let repository = tempfile::tempdir()?;
692        fs::write(repository.path().join(".gitignore"), "ignored/\n")?;
693        fs::create_dir(repository.path().join("ignored"))?;
694        fs::write(repository.path().join("ignored/openapi.yaml"), "{}")?;
695        fs::write(repository.path().join("openapi.json"), "{}")?;
696        let workspace = RepositoryConfig {
697            path: ".".to_owned(),
698            openapi: None,
699            http_consumers: None,
700            integration_tests: None,
701            implementations: None,
702            excludes: None,
703            include_defaults: None,
704            authorities: None,
705        };
706
707        let resolved = resolve_repository_config_with_use_gitignore(
708            repository.path(),
709            &workspace,
710            Some(true),
711        )?;
712
713        assert_eq!(resolved.openapi, vec!["openapi.json"]);
714        Ok(())
715    }
716
717    #[test]
718    fn canonical_equivalent_patterns_should_produce_the_same_repository_fingerprint()
719    -> Result<(), Box<dyn std::error::Error>> {
720        let repository = tempfile::tempdir()?;
721        let canonical = RepositoryConfig {
722            path: ".".to_owned(),
723            openapi: None,
724            http_consumers: None,
725            integration_tests: None,
726            implementations: None,
727            excludes: Some(vec!["coverage/**".to_owned()]),
728            include_defaults: Some(vec!["vendor/internal-sdk/**".to_owned()]),
729            authorities: None,
730        };
731        let redundant = RepositoryConfig {
732            excludes: Some(vec!["./coverage//./**".to_owned()]),
733            include_defaults: Some(vec!["./vendor//internal-sdk/./**".to_owned()]),
734            authorities: None,
735            ..canonical.clone()
736        };
737
738        let canonical = resolve_repository_config(repository.path(), &canonical)?;
739        let redundant = resolve_repository_config(repository.path(), &redundant)?;
740
741        assert_eq!(canonical.fingerprint, redundant.fingerprint);
742        Ok(())
743    }
744
745    #[test]
746    fn openapi_auto_detection_should_respect_reopened_default_subtree()
747    -> Result<(), Box<dyn std::error::Error>> {
748        let repository = tempfile::tempdir()?;
749        fs::create_dir_all(repository.path().join("vendor/internal-sdk"))?;
750        fs::create_dir_all(repository.path().join("vendor/external"))?;
751        fs::write(
752            repository.path().join("vendor/internal-sdk/openapi.yaml"),
753            "{}",
754        )?;
755        fs::write(repository.path().join("vendor/external/openapi.yaml"), "{}")?;
756        let workspace = RepositoryConfig {
757            path: ".".to_owned(),
758            openapi: None,
759            http_consumers: None,
760            integration_tests: None,
761            implementations: None,
762            excludes: None,
763            include_defaults: Some(vec!["vendor/internal-sdk/**".to_owned()]),
764            authorities: None,
765        };
766
767        let resolved = resolve_repository_config(repository.path(), &workspace)?;
768
769        assert_eq!(
770            resolved.openapi,
771            vec!["vendor/internal-sdk/openapi.yaml".to_owned()]
772        );
773        Ok(())
774    }
775
776    #[test]
777    fn auto_detection_should_keep_distinct_nested_openapi_documents()
778    -> Result<(), Box<dyn std::error::Error>> {
779        let repository = tempfile::tempdir()?;
780        fs::create_dir_all(repository.path().join("backend/docs"))?;
781        fs::create_dir_all(repository.path().join("frontend/mockoon"))?;
782        fs::write(repository.path().join("backend/docs/openapi.json"), "{}")?;
783        fs::write(
784            repository
785                .path()
786                .join("frontend/mockoon/mock_openapi3.json"),
787            "{}",
788        )?;
789        let workspace = RepositoryConfig {
790            path: ".".to_owned(),
791            openapi: None,
792            http_consumers: None,
793            integration_tests: None,
794            implementations: None,
795            excludes: None,
796            include_defaults: None,
797            authorities: None,
798        };
799
800        let resolved = resolve_repository_config(repository.path(), &workspace)?;
801
802        assert_eq!(
803            resolved.openapi,
804            vec![
805                "backend/docs/openapi.json".to_owned(),
806                "frontend/mockoon/mock_openapi3.json".to_owned(),
807            ]
808        );
809        assert_eq!(resolved.openapi_source, ConfigSource::AutoDetected);
810        Ok(())
811    }
812
813    #[test]
814    fn auto_detection_should_reject_multiple_openapi_candidates()
815    -> Result<(), Box<dyn std::error::Error>> {
816        let repository = tempfile::tempdir()?;
817        fs::write(repository.path().join("openapi.yaml"), "openapi: 3.1.0")?;
818        fs::write(repository.path().join("openapi.json"), "{}")?;
819        let workspace = RepositoryConfig {
820            path: ".".to_owned(),
821            openapi: None,
822            http_consumers: None,
823            integration_tests: None,
824            implementations: None,
825            excludes: None,
826            include_defaults: None,
827            authorities: None,
828        };
829
830        let result = resolve_repository_config(repository.path(), &workspace);
831
832        assert!(matches!(result, Err(ConfigError::AmbiguousOpenApi { .. })));
833        Ok(())
834    }
835
836    #[test]
837    fn repository_local_config_should_reject_unknown_keys() -> Result<(), Box<dyn std::error::Error>>
838    {
839        let repository = tempfile::tempdir()?;
840        fs::write(
841            repository.path().join(".code-system-graph.yaml"),
842            "version: 1\nunknown: true\n",
843        )?;
844        let workspace = RepositoryConfig {
845            path: ".".to_owned(),
846            openapi: None,
847            http_consumers: None,
848            integration_tests: None,
849            implementations: None,
850            excludes: None,
851            include_defaults: None,
852            authorities: None,
853        };
854
855        let result = resolve_repository_config(repository.path(), &workspace);
856
857        assert!(matches!(result, Err(ConfigError::Invalid { .. })));
858        Ok(())
859    }
860
861    #[test]
862    fn repository_local_config_should_reject_symlink() -> Result<(), Box<dyn std::error::Error>> {
863        let temporary = tempfile::tempdir()?;
864        let repository = temporary.path().join("repository");
865        let outside = temporary.path().join("outside.yaml");
866        std::fs::create_dir_all(&repository)?;
867        std::fs::write(&outside, "version: 1\n")?;
868        #[cfg(unix)]
869        std::os::unix::fs::symlink(&outside, repository.join(".code-system-graph.yaml"))?;
870        #[cfg(windows)]
871        std::os::windows::fs::symlink_file(&outside, repository.join(".code-system-graph.yaml"))?;
872        let workspace = RepositoryConfig {
873            path: ".".to_owned(),
874            openapi: None,
875            http_consumers: None,
876            integration_tests: None,
877            implementations: None,
878            excludes: None,
879            include_defaults: None,
880            authorities: None,
881        };
882
883        let result = resolve_repository_config(&repository, &workspace);
884
885        assert!(matches!(
886            result,
887            Err(ConfigError::Symlink { .. }
888                | ConfigError::OutsideCheckout { .. }
889                | ConfigError::NotRegularFile { .. })
890        ));
891        Ok(())
892    }
893
894    #[test]
895    fn repository_local_config_should_reject_oversized_file()
896    -> Result<(), Box<dyn std::error::Error>> {
897        let repository = tempfile::tempdir()?;
898        std::fs::write(
899            repository.path().join(".code-system-graph.yaml"),
900            "x".repeat(crate::capability_dir::MAX_REPOSITORY_CONFIG_BYTES + 1),
901        )?;
902        let workspace = RepositoryConfig {
903            path: ".".to_owned(),
904            openapi: None,
905            http_consumers: None,
906            integration_tests: None,
907            implementations: None,
908            excludes: None,
909            include_defaults: None,
910            authorities: None,
911        };
912
913        let result = resolve_repository_config(repository.path(), &workspace);
914
915        assert!(matches!(result, Err(ConfigError::TooLarge { .. })));
916        Ok(())
917    }
918
919    #[test]
920    fn repository_local_config_should_reject_directory_entry()
921    -> Result<(), Box<dyn std::error::Error>> {
922        let repository = tempfile::tempdir()?;
923        std::fs::create_dir_all(repository.path().join(".code-system-graph.yaml"))?;
924        let workspace = RepositoryConfig {
925            path: ".".to_owned(),
926            openapi: None,
927            http_consumers: None,
928            integration_tests: None,
929            implementations: None,
930            excludes: None,
931            include_defaults: None,
932            authorities: None,
933        };
934
935        let result = resolve_repository_config(repository.path(), &workspace);
936
937        assert!(matches!(result, Err(ConfigError::NotRegularFile { .. })));
938        Ok(())
939    }
940
941    #[test]
942    fn cli_openapi_should_override_workspace_value() -> Result<(), Box<dyn std::error::Error>> {
943        let repository = tempfile::tempdir()?;
944        let workspace = RepositoryConfig {
945            path: ".".to_owned(),
946            openapi: Some("workspace.yaml".to_owned()),
947            http_consumers: None,
948            integration_tests: None,
949            implementations: None,
950            excludes: None,
951            include_defaults: None,
952            authorities: None,
953        };
954        let mut resolved = resolve_repository_config(repository.path(), &workspace)?;
955
956        super::apply_openapi_override(&mut resolved, "cli.yaml")?;
957
958        assert_eq!(
959            (resolved.openapi, resolved.openapi_source),
960            (vec!["cli.yaml".to_owned()], ConfigSource::CliOverride)
961        );
962        Ok(())
963    }
964}