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