Skip to main content

code_system_graph_core/
manifest.rs

1use std::collections::BTreeMap;
2
3use code_system_graph_model::{EdgeKind, contains_unsafe_metadata_characters};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use thiserror::Error;
7
8use crate::execution_policy::{ExecutionPolicy, ExecutionPolicyOverrides, InvalidExecutionPolicy};
9use crate::extraction_budget::{
10    ExtractionBudgetOverrides, ExtractionBudgets, InvalidExtractionBudget
11};
12use crate::ignore_policy::{IgnorePatternError, validate_excludes, validate_include_defaults};
13use crate::routes::normalize_authority;
14
15const MANUAL_ENDPOINT_MAX_BYTES: usize = 2_048;
16const MANUAL_CONTRACT_MAX_BYTES: usize = 1_024;
17const MANUAL_REASON_MAX_BYTES: usize = 4_096;
18
19/// Strict workspace manifest accepted by the initial registry slice.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
21#[serde(deny_unknown_fields)]
22pub struct WorkspaceManifest {
23    /// Manifest schema version.
24    pub version: u32,
25    /// Stable workspace name.
26    pub name: String,
27    /// Additional filesystem roots repositories may resolve beneath.
28    #[serde(rename = "allowedRoots", default)]
29    pub allowed_roots: Vec<String>,
30    /// Repositories indexed by unique alias.
31    pub repos: BTreeMap<String, RepositoryConfig>,
32    /// Versioned exact relationship declarations and suppressions.
33    #[serde(rename = "manualLinks", default)]
34    pub manual_links: Vec<ManualLinkConfig>,
35    /// Optional operator-owned extraction safety limit overrides.
36    #[serde(rename = "extractionBudgets", default)]
37    pub extraction_budgets: Option<ExtractionBudgetOverrides>,
38    /// Optional operator-owned supervised-execution policy overrides.
39    #[serde(rename = "executionPolicy", default)]
40    pub execution_policy: Option<ExecutionPolicyOverrides>,
41}
42
43/// Repository registration and boundary inputs.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
45#[serde(rename_all = "camelCase", deny_unknown_fields)]
46pub struct RepositoryConfig {
47    /// Native path as written in the manifest.
48    pub path: String,
49    /// Optional `OpenAPI` artifact relative to the repository root.
50    pub openapi: Option<String>,
51    /// Explicit HTTP consumers that cannot yet be extracted from source.
52    pub http_consumers: Option<Vec<HttpConsumerConfig>>,
53    /// Explicit cross-language integration tests and validated HTTP contracts.
54    pub integration_tests: Option<Vec<IntegrationTestConfig>>,
55    /// Explicit contract-to-source implementation anchors.
56    pub implementations: Option<Vec<ContractImplementationConfig>>,
57    /// Additional repository-relative globs omitted from automatic discovery.
58    pub excludes: Option<Vec<String>>,
59    /// Repository-relative exceptions to reactivable built-in exclusions.
60    pub include_defaults: Option<Vec<String>>,
61    /// `host` or `host:port` authorities served by this repository. An entry without a port
62    /// matches every port of that host.
63    pub authorities: Option<Vec<String>>,
64}
65
66/// Additive manifest settings introduced without changing exhaustively constructible public
67/// configuration structs.
68#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
69pub struct ManifestExtensions {
70    repository_use_gitignore: BTreeMap<String, bool>,
71}
72
73impl ManifestExtensions {
74    /// Returns the workspace-level `.gitignore` choice for one repository alias.
75    #[must_use]
76    pub fn repository_use_gitignore(&self, alias: &str) -> Option<bool> {
77        self.repository_use_gitignore.get(alias).copied()
78    }
79}
80
81#[derive(Deserialize)]
82#[serde(deny_unknown_fields)]
83struct WorkspaceManifestWire {
84    version: u32,
85    name: String,
86    #[serde(rename = "allowedRoots", default)]
87    allowed_roots: Vec<String>,
88    repos: BTreeMap<String, RepositoryConfigWire>,
89    #[serde(rename = "manualLinks", default)]
90    manual_links: Vec<ManualLinkConfig>,
91    #[serde(rename = "extractionBudgets", default)]
92    extraction_budgets: Option<ExtractionBudgetOverrides>,
93    #[serde(rename = "executionPolicy", default)]
94    execution_policy: Option<ExecutionPolicyOverrides>,
95}
96
97#[derive(Deserialize)]
98#[serde(rename_all = "camelCase", deny_unknown_fields)]
99struct RepositoryConfigWire {
100    path: String,
101    openapi: Option<String>,
102    http_consumers: Option<Vec<HttpConsumerConfig>>,
103    integration_tests: Option<Vec<IntegrationTestConfig>>,
104    implementations: Option<Vec<ContractImplementationConfig>>,
105    excludes: Option<Vec<String>>,
106    include_defaults: Option<Vec<String>>,
107    use_gitignore: Option<bool>,
108    authorities: Option<Vec<String>>,
109}
110
111/// Exact manual relationship or automatic-link suppression.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
113#[serde(deny_unknown_fields)]
114pub struct ManualLinkConfig {
115    /// Exact source node identifier or stable key.
116    pub from: String,
117    /// Exact target node identifier or stable key.
118    pub to: String,
119    /// Concrete graph relationship.
120    pub relation: EdgeKind,
121    /// Optional contract identity retained for audit context.
122    pub contract: Option<String>,
123    /// Mandatory human explanation for the override.
124    pub reason: String,
125    /// Whether to remove the exact automatic relationship instead of creating one.
126    #[serde(default)]
127    pub suppress: bool,
128}
129
130/// Explicit HTTP consumer boundary.
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
132#[serde(deny_unknown_fields)]
133pub struct HttpConsumerConfig {
134    /// Upper- or lower-case HTTP method.
135    pub method: String,
136    /// HTTP path template.
137    pub path: String,
138    /// Repository-relative evidence path.
139    pub source: String,
140}
141
142/// Explicit test case that validates an HTTP contract across a repository boundary.
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
144#[serde(deny_unknown_fields)]
145pub struct IntegrationTestConfig {
146    /// Test function or scenario name.
147    pub name: String,
148    /// Repository-relative test source path.
149    pub path: String,
150    /// Test framework, such as `pytest`.
151    pub framework: String,
152    /// Source language, such as `python`.
153    pub language: String,
154    /// HTTP contract validated by this test.
155    pub validates: HttpContractConfig,
156}
157
158/// Canonicalizable HTTP contract target.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
160#[serde(deny_unknown_fields)]
161pub struct HttpContractConfig {
162    /// HTTP method.
163    pub method: String,
164    /// HTTP path template.
165    pub path: String,
166}
167
168/// Explicit source symbol that implements an HTTP contract.
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
170#[serde(deny_unknown_fields)]
171pub struct ContractImplementationConfig {
172    /// Source language, such as `rust`.
173    pub language: String,
174    /// Repository-relative implementation source path.
175    pub path: String,
176    /// Qualified or local symbol name.
177    pub symbol: String,
178    /// HTTP contract implemented by the symbol.
179    pub implements: HttpContractConfig,
180}
181
182/// Error returned while validating a workspace manifest.
183#[derive(Debug, Error)]
184pub enum ManifestError {
185    /// YAML could not be decoded according to the strict schema.
186    #[error("invalid workspace manifest: {0}")]
187    InvalidYaml(#[from] serde_saphyr::DeserializeError),
188    /// The manifest uses an unsupported schema version.
189    #[error("unsupported manifest version {found}; expected version 1")]
190    UnsupportedVersion {
191        /// Version supplied by the user.
192        found: u32,
193    },
194    /// A required string is empty after trimming.
195    #[error("manifest field `{field}` must not be empty")]
196    EmptyField {
197        /// Dot-style field location.
198        field: String,
199    },
200    /// A metadata field contains terminal control or bidirectional formatting characters.
201    #[error("manifest field `{field}` contains unsafe control or bidirectional characters")]
202    UnsafeMetadata {
203        /// Dot-style field location.
204        field: String,
205    },
206    /// A bounded manifest metadata field exceeds its hard byte limit.
207    #[error("manifest field `{field}` exceeds the {maximum}-byte limit")]
208    FieldTooLong {
209        /// Dot-style field location.
210        field: String,
211        /// Non-overridable maximum UTF-8 byte length.
212        maximum: usize,
213    },
214    /// A repository discovery pattern is malformed or unsafe.
215    #[error("manifest field `{field}` is invalid: {source}")]
216    InvalidIgnorePattern {
217        /// Dot-style field location.
218        field: String,
219        /// Pattern validation failure.
220        #[source]
221        source: IgnorePatternError,
222    },
223    /// An extraction budget is zero or cannot be represented internally.
224    #[error("invalid workspace manifest: {0}")]
225    InvalidExtractionBudget(#[from] InvalidExtractionBudget),
226    /// An execution policy value or relationship is invalid.
227    #[error("invalid workspace manifest: {0}")]
228    InvalidExecutionPolicy(#[from] InvalidExecutionPolicy),
229    /// The workspace does not register any repositories.
230    #[error("manifest field `repos` must contain at least one repository")]
231    EmptyRepositories,
232    /// A manual relationship uses the reserved generic relationship kind.
233    #[error("manifest field `manualLinks[{index}].relation` must be a concrete edge kind")]
234    NonConcreteManualRelation {
235        /// Zero-based declaration index.
236        index: usize,
237    },
238    /// A manual relationship names the same literal endpoint twice.
239    #[error("manual link at `manualLinks[{index}]` cannot link endpoint `{endpoint}` to itself")]
240    ManualSelfLink {
241        /// Zero-based declaration index.
242        index: usize,
243        /// Repeated endpoint literal.
244        endpoint: String,
245    },
246    /// Two manual declarations target the same relationship identity.
247    #[error(
248        "manual link at `manualLinks[{duplicate}]` duplicates `manualLinks[{first}]` for `{from}` -> `{to}` ({relation:?})"
249    )]
250    DuplicateManualLink {
251        /// Index of the first declaration.
252        first: usize,
253        /// Index of the repeated declaration.
254        duplicate: usize,
255        /// Exact source endpoint literal.
256        from: String,
257        /// Exact target endpoint literal.
258        to: String,
259        /// Repeated relationship.
260        relation: EdgeKind,
261    },
262    /// A repository authority is not a `host` or `host:port` value.
263    #[error(
264        "manifest field `{field}` must be a `host` or `host:port` authority without scheme or path"
265    )]
266    InvalidAuthority {
267        /// Dot-style field location.
268        field: String,
269    },
270    /// Two repositories declare the same authority.
271    #[error("authority `{authority}` is declared by both `repos.{first}` and `repos.{second}`")]
272    DuplicateAuthority {
273        /// Normalized authority.
274        authority: String,
275        /// Alias of the first declaring repository.
276        first: String,
277        /// Alias of the repeating repository.
278        second: String,
279    },
280}
281
282/// Parses and semantically validates a strict workspace manifest.
283///
284/// # Errors
285///
286/// Returns [`ManifestError`] for malformed YAML, unknown keys, unsupported versions, empty
287/// fields, or an empty repository registry.
288pub fn parse_manifest(input: &str) -> Result<WorkspaceManifest, ManifestError> {
289    parse_manifest_with_extensions(input).map(|(manifest, _)| manifest)
290}
291
292/// Parses a strict workspace manifest together with additive patch-compatible settings.
293///
294/// # Errors
295///
296/// Returns [`ManifestError`] under the same conditions as [`parse_manifest`].
297pub fn parse_manifest_with_extensions(
298    input: &str,
299) -> Result<(WorkspaceManifest, ManifestExtensions), ManifestError> {
300    let wire: WorkspaceManifestWire = crate::yaml::from_str(input)?;
301    let mut repository_use_gitignore = BTreeMap::new();
302    let repos = wire
303        .repos
304        .into_iter()
305        .map(|(alias, repository)| {
306            if let Some(value) = repository.use_gitignore {
307                repository_use_gitignore.insert(alias.clone(), value);
308            }
309            (
310                alias,
311                RepositoryConfig {
312                    path: repository.path,
313                    openapi: repository.openapi,
314                    http_consumers: repository.http_consumers,
315                    integration_tests: repository.integration_tests,
316                    implementations: repository.implementations,
317                    excludes: repository.excludes,
318                    include_defaults: repository.include_defaults,
319                    authorities: repository.authorities,
320                },
321            )
322        })
323        .collect();
324    let manifest = WorkspaceManifest {
325        version: wire.version,
326        name: wire.name,
327        allowed_roots: wire.allowed_roots,
328        repos,
329        manual_links: wire.manual_links,
330        extraction_budgets: wire.extraction_budgets,
331        execution_policy: wire.execution_policy,
332    };
333    validate_manifest(manifest).map(|manifest| {
334        (
335            manifest,
336            ManifestExtensions {
337                repository_use_gitignore,
338            },
339        )
340    })
341}
342
343fn validate_manifest(manifest: WorkspaceManifest) -> Result<WorkspaceManifest, ManifestError> {
344    if manifest.version != 1 {
345        return Err(ManifestError::UnsupportedVersion {
346            found: manifest.version,
347        });
348    }
349    validate_not_empty("name", &manifest.name)?;
350    for (index, root) in manifest.allowed_roots.iter().enumerate() {
351        validate_not_empty(&format!("allowedRoots[{index}]"), root)?;
352    }
353    if manifest.repos.is_empty() {
354        return Err(ManifestError::EmptyRepositories);
355    }
356    validate_manual_links(&manifest.manual_links)?;
357    ExtractionBudgets::resolve(manifest.extraction_budgets.as_ref())?;
358    ExecutionPolicy::resolve(manifest.execution_policy.as_ref())?;
359    for (alias, repository) in &manifest.repos {
360        validate_not_empty(&format!("repos.{alias}"), alias)?;
361        validate_not_empty(&format!("repos.{alias}.path"), &repository.path)?;
362        if let Some(openapi) = &repository.openapi {
363            validate_not_empty(&format!("repos.{alias}.openapi"), openapi)?;
364        }
365        for (index, consumer) in repository.http_consumers.iter().flatten().enumerate() {
366            validate_not_empty(
367                &format!("repos.{alias}.httpConsumers[{index}].method"),
368                &consumer.method,
369            )?;
370            validate_not_empty(
371                &format!("repos.{alias}.httpConsumers[{index}].path"),
372                &consumer.path,
373            )?;
374            validate_not_empty(
375                &format!("repos.{alias}.httpConsumers[{index}].source"),
376                &consumer.source,
377            )?;
378        }
379        for (index, test) in repository.integration_tests.iter().flatten().enumerate() {
380            for (field, value) in [
381                ("name", test.name.as_str()),
382                ("path", test.path.as_str()),
383                ("framework", test.framework.as_str()),
384                ("language", test.language.as_str()),
385                ("validates.method", test.validates.method.as_str()),
386                ("validates.path", test.validates.path.as_str()),
387            ] {
388                validate_not_empty(
389                    &format!("repos.{alias}.integrationTests[{index}].{field}"),
390                    value,
391                )?;
392            }
393        }
394        for (index, implementation) in repository.implementations.iter().flatten().enumerate() {
395            for (field, value) in [
396                ("language", implementation.language.as_str()),
397                ("path", implementation.path.as_str()),
398                ("symbol", implementation.symbol.as_str()),
399                (
400                    "implements.method",
401                    implementation.implements.method.as_str(),
402                ),
403                ("implements.path", implementation.implements.path.as_str()),
404            ] {
405                validate_not_empty(
406                    &format!("repos.{alias}.implementations[{index}].{field}"),
407                    value,
408                )?;
409            }
410        }
411        validate_repository_ignore_patterns(alias, repository)?;
412    }
413    validate_authorities(&manifest.repos)?;
414    Ok(manifest)
415}
416
417fn validate_authorities(repos: &BTreeMap<String, RepositoryConfig>) -> Result<(), ManifestError> {
418    let mut owners = BTreeMap::<String, &str>::new();
419    for (alias, repository) in repos {
420        for (index, authority) in repository.authorities.iter().flatten().enumerate() {
421            let field = format!("repos.{alias}.authorities[{index}]");
422            validate_not_empty(&field, authority)?;
423            let normalized =
424                normalize_authority(authority).ok_or(ManifestError::InvalidAuthority { field })?;
425            if let Some(first) = owners.insert(normalized.clone(), alias)
426                && first != alias
427            {
428                return Err(ManifestError::DuplicateAuthority {
429                    authority: normalized,
430                    first: first.to_owned(),
431                    second: alias.clone(),
432                });
433            }
434        }
435    }
436    Ok(())
437}
438
439fn validate_repository_ignore_patterns(
440    alias: &str,
441    repository: &RepositoryConfig,
442) -> Result<(), ManifestError> {
443    if let Some(patterns) = &repository.excludes {
444        validate_excludes(patterns).map_err(|source| ManifestError::InvalidIgnorePattern {
445            field: format!("repos.{alias}.excludes"),
446            source,
447        })?;
448    }
449    if let Some(patterns) = &repository.include_defaults {
450        validate_include_defaults(patterns).map_err(|source| {
451            ManifestError::InvalidIgnorePattern {
452                field: format!("repos.{alias}.includeDefaults"),
453                source,
454            }
455        })?;
456    }
457    Ok(())
458}
459
460/// Validates manually constructed relationship declarations.
461///
462/// # Errors
463///
464/// Returns [`ManifestError`] for empty or unsafe metadata, reserved relationship kinds,
465/// self-links, or duplicate source/target/relation declarations.
466pub fn validate_manual_links(links: &[ManualLinkConfig]) -> Result<(), ManifestError> {
467    let mut identities = BTreeMap::new();
468    for (index, link) in links.iter().enumerate() {
469        validate_not_empty(&format!("manualLinks[{index}].from"), &link.from)?;
470        validate_not_empty(&format!("manualLinks[{index}].to"), &link.to)?;
471        validate_not_empty(&format!("manualLinks[{index}].reason"), &link.reason)?;
472        validate_maximum(
473            &format!("manualLinks[{index}].from"),
474            &link.from,
475            MANUAL_ENDPOINT_MAX_BYTES,
476        )?;
477        validate_maximum(
478            &format!("manualLinks[{index}].to"),
479            &link.to,
480            MANUAL_ENDPOINT_MAX_BYTES,
481        )?;
482        validate_maximum(
483            &format!("manualLinks[{index}].reason"),
484            &link.reason,
485            MANUAL_REASON_MAX_BYTES,
486        )?;
487        if let Some(contract) = &link.contract {
488            validate_not_empty(&format!("manualLinks[{index}].contract"), contract)?;
489            validate_maximum(
490                &format!("manualLinks[{index}].contract"),
491                contract,
492                MANUAL_CONTRACT_MAX_BYTES,
493            )?;
494        }
495        if link.relation == EdgeKind::ManualLink {
496            return Err(ManifestError::NonConcreteManualRelation { index });
497        }
498        if link.from == link.to {
499            return Err(ManifestError::ManualSelfLink {
500                index,
501                endpoint: link.from.clone(),
502            });
503        }
504        let identity = (link.from.clone(), link.to.clone(), link.relation);
505        if let Some(first) = identities.insert(identity, index) {
506            return Err(ManifestError::DuplicateManualLink {
507                first,
508                duplicate: index,
509                from: link.from.clone(),
510                to: link.to.clone(),
511                relation: link.relation,
512            });
513        }
514    }
515    Ok(())
516}
517
518fn validate_not_empty(field: &str, value: &str) -> Result<(), ManifestError> {
519    if value.trim().is_empty() {
520        return Err(ManifestError::EmptyField {
521            field: field.to_owned(),
522        });
523    }
524    if contains_unsafe_metadata_characters(value) {
525        return Err(ManifestError::UnsafeMetadata {
526            field: field.to_owned(),
527        });
528    }
529    Ok(())
530}
531
532fn validate_maximum(field: &str, value: &str, maximum: usize) -> Result<(), ManifestError> {
533    if value.len() > maximum {
534        return Err(ManifestError::FieldTooLong {
535            field: field.to_owned(),
536            maximum,
537        });
538    }
539    Ok(())
540}
541
542#[cfg(test)]
543mod tests {
544    use code_system_graph_model::EdgeKind;
545
546    use super::{
547        MANUAL_REASON_MAX_BYTES, ManifestError, parse_manifest, parse_manifest_with_extensions
548    };
549    use crate::{ExecutionPolicy, ExtractionBudgets, IgnorePatternError};
550
551    const VALID: &str = r"
552version: 1
553name: commerce
554repos:
555  web:
556    path: ../web
557    httpConsumers:
558      - method: POST
559        path: /api/orders
560        source: src/checkout.ts
561";
562
563    #[test]
564    fn parse_manifest_should_accept_strict_valid_input() {
565        let result = parse_manifest(VALID);
566
567        assert!(result.is_ok(), "unexpected manifest error: {result:?}");
568    }
569
570    #[test]
571    fn extraction_budgets_should_be_optional_and_resolve_safe_defaults() {
572        let manifest = parse_manifest(VALID).expect("manifest without advanced budgets is valid");
573        let effective = ExtractionBudgets::resolve(manifest.extraction_budgets.as_ref())
574            .expect("safe defaults are valid");
575
576        assert_eq!(effective, ExtractionBudgets::default());
577    }
578
579    #[test]
580    fn extraction_budgets_should_accept_partial_higher_and_lower_overrides() {
581        let input = VALID.replace(
582            "name: commerce",
583            "name: commerce\nextractionBudgets:\n  maxInputBytesPerArtifact: 1024\n  maxStructuralDepthPerArtifact: 128",
584        );
585        let manifest = parse_manifest(&input).expect("partial override should be valid");
586        let effective = ExtractionBudgets::resolve(manifest.extraction_budgets.as_ref())
587            .expect("partial override should resolve");
588
589        assert_eq!(effective.max_input_bytes_per_artifact, 1_024);
590        assert_eq!(effective.max_structural_depth_per_artifact, 128);
591        assert_eq!(
592            effective.max_ast_depth_per_artifact,
593            ExtractionBudgets::default().max_ast_depth_per_artifact
594        );
595    }
596
597    #[test]
598    fn extraction_budgets_should_accept_a_complete_override() {
599        let input = VALID.replace(
600            "name: commerce",
601            "name: commerce\nextractionBudgets:\n  maxInputBytesPerArtifact: 1\n  maxStructuralDepthPerArtifact: 2\n  maxAstDepthPerArtifact: 3\n  maxWorkUnitsPerArtifact: 4\n  maxTreeSitterNodesPerArtifact: 5\n  maxObservationsPerArtifact: 6\n  maxAccumulatedStringBytesPerArtifact: 7\n  maxSerializedOutputBytesPerArtifact: 8\n  maxStringBytesPerValue: 9\n  maxPortablePathBytesPerValue: 10\n  maxIdentifierBytesPerValue: 11\n  maxStructuredWallTimeMsPerArtifact: 12\n  maxTreeSitterWallTimeMsPerArtifact: 13",
602        );
603        let manifest = parse_manifest(&input).expect("complete override should be valid");
604        let effective = ExtractionBudgets::resolve(manifest.extraction_budgets.as_ref())
605            .expect("complete override should resolve");
606
607        assert_eq!(effective.max_input_bytes_per_artifact, 1);
608        assert_eq!(effective.max_structural_depth_per_artifact, 2);
609        assert_eq!(effective.max_ast_depth_per_artifact, 3);
610        assert_eq!(effective.max_work_units_per_artifact, 4);
611        assert_eq!(effective.max_tree_sitter_nodes_per_artifact, 5);
612        assert_eq!(effective.max_observations_per_artifact, 6);
613        assert_eq!(effective.max_accumulated_string_bytes_per_artifact, 7);
614        assert_eq!(effective.max_serialized_output_bytes_per_artifact, 8);
615        assert_eq!(effective.max_string_bytes_per_value, 9);
616        assert_eq!(effective.max_portable_path_bytes_per_value, 10);
617        assert_eq!(effective.max_identifier_bytes_per_value, 11);
618        assert_eq!(effective.max_structured_wall_time_ms_per_artifact, 12);
619        assert_eq!(effective.max_tree_sitter_wall_time_ms_per_artifact, 13);
620    }
621
622    #[test]
623    fn extraction_budgets_should_reject_zero_overflow_and_unknown_fields() {
624        let zero = VALID.replace(
625            "name: commerce",
626            "name: commerce\nextractionBudgets:\n  maxWorkUnitsPerArtifact: 0",
627        );
628        let overflow = VALID.replace(
629            "name: commerce",
630            "name: commerce\nextractionBudgets:\n  maxWorkUnitsPerArtifact: 18446744073709551616",
631        );
632        let unknown = VALID.replace(
633            "name: commerce",
634            "name: commerce\nextractionBudgets:\n  maxWorkUnitsPerArtifact: 1\n  maximumMagic: 2",
635        );
636
637        assert!(matches!(
638            parse_manifest(&zero),
639            Err(ManifestError::InvalidExtractionBudget(_))
640        ));
641        assert!(matches!(
642            parse_manifest(&overflow),
643            Err(ManifestError::InvalidYaml(_))
644        ));
645        assert!(matches!(
646            parse_manifest(&unknown),
647            Err(ManifestError::InvalidYaml(_))
648        ));
649    }
650
651    #[test]
652    fn execution_policy_should_resolve_defaults_and_partial_overrides() {
653        let manifest = parse_manifest(VALID).expect("manifest without execution policy is valid");
654        assert_eq!(
655            ExecutionPolicy::resolve(manifest.execution_policy.as_ref()).expect("defaults"),
656            ExecutionPolicy::default()
657        );
658
659        let input = VALID.replace(
660            "name: commerce",
661            "name: commerce\nexecutionPolicy:\n  maxScanWallTimeMs: 28800000\n  maxNoProgressTimeMs: 600000",
662        );
663        let manifest = parse_manifest(&input).expect("partial policy override is valid");
664        let effective = ExecutionPolicy::resolve(manifest.execution_policy.as_ref())
665            .expect("partial policy resolves");
666        assert_eq!(effective.max_scan_wall_time_ms, 28_800_000);
667        assert_eq!(effective.max_no_progress_time_ms, 600_000);
668        assert_eq!(
669            effective.max_worker_memory_bytes,
670            ExecutionPolicy::default().max_worker_memory_bytes
671        );
672    }
673
674    #[test]
675    fn execution_policy_should_reject_zero_overflow_unknown_and_invalid_relationships() {
676        let zero = VALID.replace(
677            "name: commerce",
678            "name: commerce\nexecutionPolicy:\n  maxWorkerMemoryBytes: 0",
679        );
680        let overflow = VALID.replace(
681            "name: commerce",
682            "name: commerce\nexecutionPolicy:\n  maxWorkerMemoryBytes: 18446744073709551616",
683        );
684        let unknown = VALID.replace(
685            "name: commerce",
686            "name: commerce\nexecutionPolicy:\n  maximumMagic: 1",
687        );
688        let invalid = VALID.replace(
689            "name: commerce",
690            "name: commerce\nexecutionPolicy:\n  maxScanWallTimeMs: 1000\n  maxNoProgressTimeMs: 1001\n  maxCodeGraphSyncWallTimeMsPerRepo: 1000\n  gracefulTerminationMs: 1",
691        );
692        let invalid_anchor_limit = VALID.replace(
693            "name: commerce",
694            "name: commerce\nexecutionPolicy:\n  maxCodeGraphCorroborationAnchorsPerRepo: -2",
695        );
696
697        assert!(matches!(
698            parse_manifest(&zero),
699            Err(ManifestError::InvalidExecutionPolicy(_))
700        ));
701        assert!(matches!(
702            parse_manifest(&overflow),
703            Err(ManifestError::InvalidYaml(_))
704        ));
705        assert!(matches!(
706            parse_manifest(&unknown),
707            Err(ManifestError::InvalidYaml(_))
708        ));
709        assert!(matches!(
710            parse_manifest(&invalid_anchor_limit),
711            Err(ManifestError::InvalidExecutionPolicy(_))
712        ));
713        let invalid_result = parse_manifest(&invalid);
714        assert!(
715            matches!(
716                invalid_result,
717                Err(ManifestError::InvalidExecutionPolicy(_))
718            ),
719            "unexpected invalid relationship result: {invalid_result:?}"
720        );
721    }
722
723    #[test]
724    fn parse_manifest_should_accept_repository_ignore_patterns() {
725        let input = VALID.replace(
726            "    path: ../web",
727            "    path: ../web\n    excludes: [coverage/**]\n    includeDefaults: [vendor/internal/**]",
728        );
729
730        let result = parse_manifest(&input);
731
732        assert!(result.is_ok(), "unexpected manifest error: {result:?}");
733    }
734
735    #[test]
736    fn parse_manifest_should_normalize_execution_policy_settings() {
737        let input = VALID.replace(
738            "name: commerce",
739            "name: commerce\nexecutionPolicy:\n  maxCodeGraphCorroborationAnchorsPerRepo: 12",
740        );
741        let input = input.replace(
742            "    path: ../web",
743            "    path: ../web\n    useGitignore: true",
744        );
745
746        let (manifest, extensions) =
747            parse_manifest_with_extensions(&input).expect("additive settings are valid");
748
749        assert!(manifest.execution_policy.is_some());
750        assert_eq!(extensions.repository_use_gitignore("web"), Some(true));
751        let policy =
752            ExecutionPolicy::resolve(manifest.execution_policy.as_ref()).expect("effective policy");
753        assert_eq!(
754            policy
755                .max_codegraph_corroboration_anchors_per_repo
756                .bounded()
757                .map(std::num::NonZeroUsize::get),
758            Some(12)
759        );
760    }
761
762    #[test]
763    fn parse_manifest_should_reject_protected_default_include() {
764        let input = VALID.replace(
765            "    path: ../web",
766            "    path: ../web\n    includeDefaults: [.codegraph/**]",
767        );
768
769        let result = parse_manifest(&input);
770
771        assert!(matches!(
772            result,
773            Err(ManifestError::InvalidIgnorePattern { field, .. })
774                if field == "repos.web.includeDefaults"
775        ));
776    }
777
778    #[test]
779    fn parse_manifest_should_reject_unsupported_ignore_syntax() {
780        let input = VALID.replace(
781            "    path: ../web",
782            "    path: ../web\n    excludes: [\"src/[ab]/**\"]",
783        );
784
785        let result = parse_manifest(&input);
786
787        assert!(matches!(
788            result,
789            Err(ManifestError::InvalidIgnorePattern {
790                source: IgnorePatternError::UnsupportedSyntax(_),
791                ..
792            })
793        ));
794    }
795
796    #[test]
797    fn parse_manifest_should_reject_unknown_keys() {
798        let result =
799            parse_manifest(&VALID.replace("name: commerce", "name: commerce\nextra: true"));
800
801        assert!(matches!(result, Err(ManifestError::InvalidYaml(_))));
802    }
803
804    #[test]
805    fn parse_manifest_should_reject_unsupported_version() {
806        let result = parse_manifest(&VALID.replace("version: 1", "version: 2"));
807
808        assert!(matches!(
809            result,
810            Err(ManifestError::UnsupportedVersion { found: 2 })
811        ));
812    }
813
814    #[test]
815    fn parse_manifest_should_reject_bidi_metadata() {
816        let result = parse_manifest(&VALID.replace("commerce", "commerce\u{202e}txt"));
817
818        assert!(matches!(
819            result,
820            Err(ManifestError::UnsafeMetadata { field }) if field == "name"
821        ));
822    }
823
824    #[test]
825    fn parse_manifest_should_accept_exact_manual_link() {
826        let input = format!(
827            "{VALID}manualLinks:\n  - from: node:web\n    to: service:api\n    relation: consumes\n    contract: POST /orders\n    reason: Manual checkout boundary\n"
828        );
829
830        let result = parse_manifest(&input).map(|manifest| manifest.manual_links);
831
832        assert!(matches!(
833            result,
834            Ok(links)
835                if links.len() == 1
836                    && links[0].relation == EdgeKind::Consumes
837                    && !links[0].suppress
838        ));
839    }
840
841    #[test]
842    fn parse_manifest_should_reject_unknown_manual_link_fields() {
843        let input = format!(
844            "{VALID}manualLinks:\n  - from: node:web\n    to: service:api\n    relation: consumes\n    reason: Explicit dependency\n    approximate: true\n"
845        );
846
847        let result = parse_manifest(&input);
848
849        assert!(matches!(result, Err(ManifestError::InvalidYaml(_))));
850    }
851
852    #[test]
853    fn parse_manifest_should_reject_empty_manual_link_reason() {
854        let input = format!(
855            "{VALID}manualLinks:\n  - from: node:web\n    to: service:api\n    relation: consumes\n    reason: '   '\n"
856        );
857
858        let result = parse_manifest(&input);
859
860        assert!(matches!(
861            result,
862            Err(ManifestError::EmptyField { field })
863                if field == "manualLinks[0].reason"
864        ));
865    }
866
867    #[test]
868    fn parse_manifest_should_reject_oversized_manual_link_reason() {
869        let input = format!(
870            "{VALID}manualLinks:\n  - from: node:web\n    to: service:api\n    relation: consumes\n    reason: {}\n",
871            "x".repeat(MANUAL_REASON_MAX_BYTES + 1)
872        );
873
874        let result = parse_manifest(&input);
875
876        assert!(matches!(
877            result,
878            Err(ManifestError::FieldTooLong { field, maximum })
879                if field == "manualLinks[0].reason" && maximum == MANUAL_REASON_MAX_BYTES
880        ));
881    }
882
883    #[test]
884    fn parse_manifest_should_reject_unsafe_manual_link_metadata() {
885        let input = format!(
886            "{VALID}manualLinks:\n  - from: node:web\u{202e}\n    to: service:api\n    relation: consumes\n    reason: Explicit dependency\n"
887        );
888
889        let result = parse_manifest(&input);
890
891        assert!(matches!(
892            result,
893            Err(ManifestError::UnsafeMetadata { field })
894                if field == "manualLinks[0].from"
895        ));
896    }
897
898    #[test]
899    fn parse_manifest_should_reject_duplicate_manual_link_identity() {
900        let declaration = "  - from: node:web\n    to: service:api\n    relation: consumes\n    reason: Explicit dependency\n";
901        let input = format!("{VALID}manualLinks:\n{declaration}{declaration}");
902
903        let result = parse_manifest(&input);
904
905        assert!(matches!(
906            result,
907            Err(ManifestError::DuplicateManualLink {
908                first: 0,
909                duplicate: 1,
910                ..
911            })
912        ));
913    }
914
915    #[test]
916    fn parse_manifest_should_reject_literal_manual_self_link() {
917        let input = format!(
918            "{VALID}manualLinks:\n  - from: node:web\n    to: node:web\n    relation: consumes\n    reason: Invalid self link\n"
919        );
920
921        let result = parse_manifest(&input);
922
923        assert!(matches!(
924            result,
925            Err(ManifestError::ManualSelfLink { index: 0, .. })
926        ));
927    }
928
929    const AUTHORITIES: &str = r"
930version: 1
931name: commerce
932repos:
933  orders:
934    path: ../orders
935    authorities: [orders-api:8080, orders.internal]
936  billing:
937    path: ../billing
938    authorities: [BILLING]
939";
940
941    #[test]
942    fn parse_manifest_should_accept_repository_authorities() {
943        let manifest = parse_manifest(AUTHORITIES).expect("valid authorities");
944
945        assert_eq!(
946            manifest.repos["orders"].authorities,
947            Some(vec![
948                "orders-api:8080".to_owned(),
949                "orders.internal".to_owned()
950            ])
951        );
952    }
953
954    #[test]
955    fn parse_manifest_should_reject_authorities_with_scheme_or_path() {
956        for authority in ["http://orders", "orders/v1", "orders:http"] {
957            let input = AUTHORITIES.replace("orders.internal", authority);
958
959            let result = parse_manifest(&input);
960
961            assert!(
962                matches!(
963                    result,
964                    Err(ManifestError::InvalidAuthority { ref field })
965                        if field == "repos.orders.authorities[1]"
966                ),
967                "{authority}: {result:?}"
968            );
969        }
970    }
971
972    #[test]
973    fn parse_manifest_should_reject_an_authority_declared_by_two_repositories() {
974        let input = AUTHORITIES.replace("[BILLING]", "[Orders-API:8080]");
975
976        let result = parse_manifest(&input);
977
978        assert!(matches!(
979            result,
980            Err(ManifestError::DuplicateAuthority { authority, .. }) if authority == "orders-api:8080"
981        ));
982    }
983}