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