Skip to main content

code_system_graph_core/
extraction_graph.rs

1//! Deterministic graph conversion for extraction documents.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use code_system_graph_model::{
6    Edge, EdgeId, EdgeKind, EpistemicStatus, Evidence, EvidenceId, Node, NodeId, NodeKind, Provenance, RepoId, RepositoryCoverageGap, stable_id
7};
8
9use crate::{
10    DataAccessObservation, DataAccessRole, DataArtifactKind, DataArtifactReference, DataArtifactReferenceKind, DataDocument, DatabaseForeignKey, DatabaseTable, DeploymentKind, DeploymentUnit, DocumentKind, DocumentRecord, DocumentationDocument, ExplicitReference, ExplicitReferenceKind, InfrastructureDocument, InfrastructureEvidence, InfrastructureResource, InfrastructureResourceKind, OwnershipRule, SafeConfigDocument
11};
12
13type RepositoryReference<'a> = (&'a str, &'a RepoId, Option<&'a str>);
14
15/// Graph-ready facts assembled from supported extraction documents.
16#[derive(Debug, Clone, Default)]
17pub struct ExtractionGraphFacts {
18    /// Repository, artifact, data, deployment, configuration, document, and owner nodes.
19    pub nodes: Vec<Node>,
20    /// Directly evidenced extraction relationships.
21    pub edges: Vec<Edge>,
22    /// Value-free evidence supporting the emitted relationships.
23    pub evidence: Vec<Evidence>,
24    /// Explicit repository dependencies that could not be resolved without guessing.
25    pub coverage_gaps: Vec<RepositoryCoverageGap>,
26}
27
28#[derive(Debug, Clone)]
29struct TableInfo {
30    node: Node,
31    database: Option<String>,
32    schema: Option<String>,
33    name: String,
34    columns: BTreeMap<String, Node>,
35}
36
37#[derive(Debug, Clone)]
38struct PendingAccess {
39    repo_id: RepoId,
40    source_path: String,
41    content_hash: String,
42    access: DataAccessObservation,
43}
44
45type KnownSourceSymbols = BTreeMap<(RepoId, String, String), Node>;
46
47#[derive(Debug, Clone)]
48struct PendingForeignKey {
49    repo_id: RepoId,
50    source_path: String,
51    content_hash: String,
52    source_table_key: String,
53    foreign_key: DatabaseForeignKey,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57enum MigrationDirection {
58    Forward,
59    Up,
60    Down,
61}
62
63#[derive(Debug, Clone)]
64struct MigrationArtifact {
65    repo_id: RepoId,
66    source_path: String,
67    content_hash: String,
68    artifact: Node,
69    order_hint: Option<u64>,
70    evidence_line: u32,
71    direction: MigrationDirection,
72}
73
74#[derive(Debug, Clone)]
75struct DeploymentInfo {
76    repo_id: RepoId,
77    node: Node,
78    aliases: BTreeSet<String>,
79}
80
81#[derive(Debug, Clone)]
82struct ResourceInfo {
83    node: Node,
84    aliases: BTreeSet<String>,
85}
86
87#[derive(Debug, Clone)]
88struct PendingDependency {
89    source: Node,
90    target: String,
91    repo_id: RepoId,
92    source_path: String,
93    content_hash: String,
94    line: Option<u32>,
95}
96
97#[derive(Debug, Clone)]
98struct PendingReference {
99    document: Node,
100    repo_id: RepoId,
101    source_path: String,
102    content_hash: String,
103    reference: ExplicitReference,
104}
105
106#[derive(Default)]
107struct GraphBuilder {
108    facts: ExtractionGraphFacts,
109}
110
111impl GraphBuilder {
112    fn node(&mut self, node: Node) {
113        self.facts.nodes.push(node);
114    }
115
116    fn evidence(&mut self, evidence: Evidence) {
117        self.facts.evidence.push(evidence);
118    }
119
120    fn edge(&mut self, source: &Node, target: &Node, kind: EdgeKind, evidence: &Evidence) {
121        if source.id == target.id {
122            return;
123        }
124        let key = format!("{}:{kind:?}:{}", source.id.as_str(), target.id.as_str());
125        self.facts.edges.push(Edge {
126            id: EdgeId::new(stable_id("edge", &key)),
127            source: source.id.clone(),
128            target: target.id.clone(),
129            kind,
130            confidence: 1.0,
131            status: EpistemicStatus::Confirmed,
132            evidence: vec![evidence.id.clone()],
133        });
134    }
135
136    fn finish(mut self) -> ExtractionGraphFacts {
137        let mut nodes = BTreeMap::new();
138        for node in self.facts.nodes {
139            nodes.entry(node.id.clone()).or_insert(node);
140        }
141        self.facts.nodes = nodes.into_values().collect();
142
143        let mut edges: BTreeMap<EdgeId, Edge> = BTreeMap::new();
144        for edge in self.facts.edges {
145            if let Some(existing) = edges.get_mut(&edge.id) {
146                existing.evidence.extend(edge.evidence);
147                existing.confidence = existing.confidence.max(edge.confidence);
148            } else {
149                edges.insert(edge.id.clone(), edge);
150            }
151        }
152        self.facts.edges = edges
153            .into_values()
154            .map(|mut edge| {
155                edge.evidence.sort();
156                edge.evidence.dedup();
157                edge
158            })
159            .collect();
160
161        let mut evidence = BTreeMap::new();
162        for item in self.facts.evidence {
163            evidence.entry(item.id.clone()).or_insert(item);
164        }
165        self.facts.evidence = evidence.into_values().collect();
166        self.facts.coverage_gaps.sort_by(|left, right| {
167            (&left.repo_id, &left.reason).cmp(&(&right.repo_id, &right.reason))
168        });
169        self.facts.coverage_gaps.dedup();
170        self.facts
171    }
172}
173
174/// Converts all supported extractor outputs into deterministic, ambiguity-safe graph facts.
175///
176/// Only exact, unique targets are linked. Dynamic or incomplete observations that lack a concrete
177/// target remain unlinked, and retained evidence contains locators and static notes rather than
178/// source or configuration values.
179#[must_use]
180pub fn documents_to_graph(
181    data_inputs: &[(&RepoId, &str, &str, &DataDocument)],
182    infrastructure_inputs: &[(&RepoId, &str, &str, &InfrastructureDocument)],
183    documentation_inputs: &[(&RepoId, &str, &str, &DocumentationDocument)],
184    config_inputs: &[(&RepoId, &str, &str, &SafeConfigDocument)],
185    known_nodes: &[Node],
186    repository_aliases: &[RepositoryReference<'_>],
187) -> ExtractionGraphFacts {
188    let mut builder = GraphBuilder::default();
189    let source_symbols = index_known_source_symbols(known_nodes);
190
191    append_config_documents(&mut builder, config_inputs);
192    let tables = append_data_documents(&mut builder, data_inputs);
193    append_infrastructure_documents(&mut builder, infrastructure_inputs);
194    append_documentation_documents(
195        &mut builder,
196        documentation_inputs,
197        known_nodes,
198        repository_aliases,
199    );
200
201    // Data observations can resolve across documents, so they are linked after every declaration
202    // has entered the exact-match table index.
203    link_data_observations(&mut builder, data_inputs, &tables, &source_symbols);
204    link_data_artifact_references(&mut builder, data_inputs, &tables, &source_symbols);
205    builder.finish()
206}
207
208fn append_config_documents(
209    builder: &mut GraphBuilder,
210    inputs: &[(&RepoId, &str, &str, &SafeConfigDocument)],
211) {
212    for (repo_id, source_path, content_hash, document) in inputs {
213        if document.keys.is_empty() {
214            continue;
215        }
216        let artifact = append_artifact(
217            builder,
218            repo_id,
219            source_path,
220            content_hash,
221            "code-system-graph.extraction.config",
222            "configuration artifact",
223        );
224        for key in &document.keys {
225            let node = config_node(repo_id, &key.scope.join("."), &key.name);
226            let evidence = extraction_evidence(
227                repo_id,
228                source_path,
229                content_hash,
230                line_from_usize(key.line),
231                line_from_usize(key.line),
232                "code-system-graph.extraction.config",
233                "configuration key declaration",
234            );
235            builder.edge(&artifact, &node, EdgeKind::Configures, &evidence);
236            builder.node(node);
237            builder.evidence(evidence);
238        }
239    }
240}
241
242fn append_data_documents(
243    builder: &mut GraphBuilder,
244    inputs: &[(&RepoId, &str, &str, &DataDocument)],
245) -> BTreeMap<String, TableInfo> {
246    let mut tables = BTreeMap::new();
247    let mut migrations = Vec::new();
248    for (repo_id, source_path, content_hash, document) in inputs {
249        if document.tables.is_empty()
250            && document.accesses.is_empty()
251            && document.references.is_empty()
252            && document.artifact_kind != DataArtifactKind::SqlMigration
253        {
254            continue;
255        }
256        let artifact = append_artifact(
257            builder,
258            repo_id,
259            source_path,
260            content_hash,
261            "code-system-graph.extraction.data",
262            "data artifact",
263        );
264        if let Some(migration) = &document.migration {
265            migrations.push(MigrationArtifact {
266                repo_id: (*repo_id).clone(),
267                source_path: (*source_path).to_owned(),
268                content_hash: (*content_hash).to_owned(),
269                artifact: artifact.clone(),
270                order_hint: migration.order_hint,
271                evidence_line: migration.evidence.get(),
272                direction: migration_direction(source_path),
273            });
274        }
275        for table in &document.tables {
276            let info = table_info(document, table);
277            let table_evidence = extraction_evidence(
278                repo_id,
279                source_path,
280                content_hash,
281                Some(table.evidence.get()),
282                Some(table.evidence.get()),
283                "code-system-graph.extraction.data",
284                "database table declaration",
285            );
286            builder.edge(&artifact, &info.node, EdgeKind::Contains, &table_evidence);
287            builder.node(info.node.clone());
288            builder.evidence(table_evidence.clone());
289
290            if let Some(database) = &info.database {
291                let database = database_node(database);
292                builder.edge(&database, &info.node, EdgeKind::Contains, &table_evidence);
293                builder.node(database);
294            }
295            for column in &table.columns {
296                let Some(column_node) = info.columns.get(&column.name) else {
297                    continue;
298                };
299                let evidence = extraction_evidence(
300                    repo_id,
301                    source_path,
302                    content_hash,
303                    Some(column.evidence.get()),
304                    Some(column.evidence.get()),
305                    "code-system-graph.extraction.data",
306                    "database column declaration",
307                );
308                builder.edge(&info.node, column_node, EdgeKind::Contains, &evidence);
309                builder.node(column_node.clone());
310                builder.evidence(evidence);
311            }
312            tables
313                .entry(info.node.stable_key.clone())
314                .and_modify(|existing: &mut TableInfo| {
315                    existing.columns.extend(info.columns.clone());
316                })
317                .or_insert(info);
318        }
319    }
320    link_migration_artifacts(builder, &migrations);
321    tables
322}
323
324fn link_migration_artifacts(builder: &mut GraphBuilder, migrations: &[MigrationArtifact]) {
325    let mut pairs: BTreeMap<(RepoId, String, String), Vec<&MigrationArtifact>> = BTreeMap::new();
326    let mut ordered: BTreeMap<(RepoId, String), BTreeMap<u64, Vec<&MigrationArtifact>>> =
327        BTreeMap::new();
328
329    for migration in migrations {
330        let (directory, family) = migration_family(&migration.source_path);
331        pairs
332            .entry((migration.repo_id.clone(), directory.clone(), family))
333            .or_default()
334            .push(migration);
335        if migration.direction != MigrationDirection::Down
336            && let Some(order_hint) = migration.order_hint
337        {
338            ordered
339                .entry((migration.repo_id.clone(), directory))
340                .or_default()
341                .entry(order_hint)
342                .or_default()
343                .push(migration);
344        }
345    }
346
347    for candidates in pairs.values() {
348        let up = exactly_one_migration(
349            candidates
350                .iter()
351                .filter(|migration| migration.direction == MigrationDirection::Up)
352                .copied(),
353        );
354        let down = exactly_one_migration(
355            candidates
356                .iter()
357                .filter(|migration| migration.direction == MigrationDirection::Down)
358                .copied(),
359        );
360        let (Some(up), Some(down)) = (up, down) else {
361            continue;
362        };
363        let evidence = extraction_evidence(
364            &down.repo_id,
365            &down.source_path,
366            &down.content_hash,
367            Some(down.evidence_line),
368            Some(down.evidence_line),
369            "code-system-graph.extraction.data",
370            "reversible migration pair",
371        );
372        builder.edge(&down.artifact, &up.artifact, EdgeKind::Reverts, &evidence);
373        builder.evidence(evidence);
374    }
375
376    for revisions in ordered.values() {
377        let migrations = revisions
378            .values()
379            .map(|candidates| exactly_one_migration(candidates.iter().copied()))
380            .collect::<Vec<_>>();
381        for pair in migrations.windows(2) {
382            let [Some(previous), Some(next)] = pair else {
383                continue;
384            };
385            let evidence = extraction_evidence(
386                &next.repo_id,
387                &next.source_path,
388                &next.content_hash,
389                Some(next.evidence_line),
390                Some(next.evidence_line),
391                "code-system-graph.extraction.data",
392                "migration order",
393            );
394            builder.edge(
395                &previous.artifact,
396                &next.artifact,
397                EdgeKind::Precedes,
398                &evidence,
399            );
400            builder.evidence(evidence);
401        }
402    }
403}
404
405fn exactly_one_migration<'a>(
406    mut candidates: impl Iterator<Item = &'a MigrationArtifact>,
407) -> Option<&'a MigrationArtifact> {
408    let candidate = candidates.next()?;
409    candidates.next().is_none().then_some(candidate)
410}
411
412fn migration_direction(source_path: &str) -> MigrationDirection {
413    if source_path.ends_with(".up.sql") {
414        MigrationDirection::Up
415    } else if source_path.ends_with(".down.sql") {
416        MigrationDirection::Down
417    } else {
418        MigrationDirection::Forward
419    }
420}
421
422fn migration_family(source_path: &str) -> (String, String) {
423    let (directory, filename) = source_path
424        .rsplit_once('/')
425        .map_or(("", source_path), |(directory, filename)| {
426            (directory, filename)
427        });
428    let family = filename
429        .strip_suffix(".up.sql")
430        .or_else(|| filename.strip_suffix(".down.sql"))
431        .or_else(|| filename.strip_suffix(".sql"))
432        .unwrap_or(filename);
433    (directory.to_owned(), family.to_owned())
434}
435
436fn link_data_observations(
437    builder: &mut GraphBuilder,
438    inputs: &[(&RepoId, &str, &str, &DataDocument)],
439    tables: &BTreeMap<String, TableInfo>,
440    source_symbols: &KnownSourceSymbols,
441) {
442    let mut accesses = Vec::new();
443    let mut foreign_keys = Vec::new();
444    for (repo_id, source_path, content_hash, document) in inputs {
445        accesses.extend(
446            document
447                .accesses
448                .iter()
449                .cloned()
450                .map(|access| PendingAccess {
451                    repo_id: (*repo_id).clone(),
452                    source_path: (*source_path).to_owned(),
453                    content_hash: (*content_hash).to_owned(),
454                    access,
455                }),
456        );
457        for table in &document.tables {
458            let info = table_info(document, table);
459            foreign_keys.extend(table.foreign_keys.iter().cloned().map(|foreign_key| {
460                PendingForeignKey {
461                    repo_id: (*repo_id).clone(),
462                    source_path: (*source_path).to_owned(),
463                    content_hash: (*content_hash).to_owned(),
464                    source_table_key: info.node.stable_key.clone(),
465                    foreign_key,
466                }
467            }));
468        }
469    }
470    link_accesses(builder, accesses, tables, source_symbols);
471    link_foreign_keys(builder, foreign_keys, tables);
472}
473
474fn link_data_artifact_references(
475    builder: &mut GraphBuilder,
476    inputs: &[(&RepoId, &str, &str, &DataDocument)],
477    tables: &BTreeMap<String, TableInfo>,
478    source_symbols: &KnownSourceSymbols,
479) {
480    let mut referenced_accesses = Vec::new();
481    for (repo_id, source_path, content_hash, document) in inputs {
482        for reference in &document.references {
483            let effective_path = effective_data_reference_path(reference, repo_id, inputs);
484            let targets = inputs
485                .iter()
486                .filter(|(candidate_repo, candidate_path, _, candidate)| {
487                    *candidate_repo == *repo_id
488                        && match reference.kind {
489                            DataArtifactReferenceKind::QueryFile => {
490                                *candidate_path == reference.path
491                                    && candidate.artifact_kind == DataArtifactKind::SqlQueryFile
492                            }
493                            DataArtifactReferenceKind::MigrationDirectory
494                            | DataArtifactReferenceKind::SqlxDefaultMigrationDirectory => {
495                                matches!(
496                                    candidate.artifact_kind,
497                                    DataArtifactKind::SqlMigration
498                                        | DataArtifactKind::DeclarativeSqlSchema
499                                        | DataArtifactKind::SqlQueryFile
500                                ) && path_is_within(candidate_path, &effective_path)
501                            }
502                        }
503                })
504                .collect::<Vec<_>>();
505            if reference.kind == DataArtifactReferenceKind::QueryFile && targets.len() != 1 {
506                continue;
507            }
508            let source_artifact = append_artifact(
509                builder,
510                repo_id,
511                source_path,
512                content_hash,
513                "code-system-graph.extraction.data",
514                "data source artifact",
515            );
516            let source = reference.owner.as_deref().map_or_else(
517                || source_artifact.clone(),
518                |owner| data_symbol_node(repo_id, source_path, owner, source_symbols),
519            );
520            for (target_repo, target_path, target_hash, target_document) in targets {
521                let target_artifact = append_artifact(
522                    builder,
523                    target_repo,
524                    target_path,
525                    target_hash,
526                    "code-system-graph.extraction.data",
527                    "referenced data artifact",
528                );
529                let evidence = extraction_evidence(
530                    repo_id,
531                    source_path,
532                    content_hash,
533                    Some(reference.evidence.get()),
534                    Some(reference.evidence.get()),
535                    "code-system-graph.extraction.data",
536                    match reference.kind {
537                        DataArtifactReferenceKind::QueryFile => "SQLx query file reference",
538                        DataArtifactReferenceKind::MigrationDirectory => {
539                            "SQLx migration directory reference"
540                        }
541                        DataArtifactReferenceKind::SqlxDefaultMigrationDirectory => {
542                            "SQLx configured migration directory reference"
543                        }
544                    },
545                );
546                builder.edge(&source, &target_artifact, EdgeKind::Consumes, &evidence);
547                builder.node(source.clone());
548                builder.evidence(evidence);
549
550                if reference.kind == DataArtifactReferenceKind::QueryFile {
551                    referenced_accesses.extend(target_document.accesses.iter().map(|access| {
552                        let mut access = access.clone();
553                        access.owner.clone_from(&reference.owner);
554                        access.evidence = reference.evidence;
555                        PendingAccess {
556                            repo_id: (*repo_id).clone(),
557                            source_path: (*source_path).to_owned(),
558                            content_hash: (*content_hash).to_owned(),
559                            access,
560                        }
561                    }));
562                }
563            }
564        }
565    }
566    link_accesses(builder, referenced_accesses, tables, source_symbols);
567}
568
569fn effective_data_reference_path(
570    reference: &DataArtifactReference,
571    repo_id: &RepoId,
572    inputs: &[(&RepoId, &str, &str, &DataDocument)],
573) -> String {
574    if reference.kind != DataArtifactReferenceKind::SqlxDefaultMigrationDirectory {
575        return reference.path.clone();
576    }
577    inputs
578        .iter()
579        .find(|(candidate_repo, candidate_path, _, candidate)| {
580            *candidate_repo == repo_id
581                && candidate.artifact_kind == DataArtifactKind::SqlxConfiguration
582                && *candidate_path == sqlx_configuration_path(&reference.path)
583        })
584        .and_then(|(_, _, _, configuration)| {
585            configuration
586                .references
587                .iter()
588                .find(|candidate| candidate.kind == DataArtifactReferenceKind::MigrationDirectory)
589                .map(|candidate| candidate.path.clone())
590        })
591        .unwrap_or_else(|| join_portable_path(&reference.path, "migrations"))
592}
593
594fn path_is_within(candidate: &str, directory: &str) -> bool {
595    candidate == directory
596        || candidate
597            .strip_prefix(directory)
598            .is_some_and(|suffix| suffix.starts_with('/'))
599}
600
601fn sqlx_configuration_path(crate_root: &str) -> String {
602    join_portable_path(crate_root, "sqlx.toml")
603}
604
605fn join_portable_path(parent: &str, child: &str) -> String {
606    if parent.is_empty() {
607        child.to_owned()
608    } else {
609        format!("{}/{}", parent.trim_end_matches('/'), child)
610    }
611}
612
613fn link_accesses(
614    builder: &mut GraphBuilder,
615    accesses: Vec<PendingAccess>,
616    tables: &BTreeMap<String, TableInfo>,
617    source_symbols: &KnownSourceSymbols,
618) {
619    let mut model_tables = BTreeMap::<String, BTreeSet<String>>::new();
620    for pending in &accesses {
621        if pending.access.role != DataAccessRole::ModelBinding {
622            continue;
623        }
624        let Some(model) = pending.access.owner.as_ref() else {
625            continue;
626        };
627        model_tables
628            .entry(model.clone())
629            .or_default()
630            .insert(pending.access.table.clone());
631    }
632    for pending in accesses {
633        let Some(owner) = pending.access.owner.as_deref() else {
634            continue;
635        };
636        let resolved_model_table = pending
637            .access
638            .model
639            .as_ref()
640            .and_then(|model| model_tables.get(model).cloned().and_then(exactly_one));
641        let target_name = if pending.access.table.is_empty() {
642            let Some(table) = resolved_model_table.as_deref() else {
643                continue;
644            };
645            table
646        } else {
647            &pending.access.table
648        };
649        let Some(target) = resolve_table(tables, target_name) else {
650            continue;
651        };
652        let symbol = data_symbol_node(
653            &pending.repo_id,
654            &pending.source_path,
655            owner,
656            source_symbols,
657        );
658        let evidence = extraction_evidence(
659            &pending.repo_id,
660            &pending.source_path,
661            &pending.content_hash,
662            Some(pending.access.evidence.get()),
663            Some(pending.access.evidence.get()),
664            "code-system-graph.extraction.data",
665            "database access observation",
666        );
667        match pending.access.role {
668            DataAccessRole::Reader => {
669                builder.edge(&symbol, &target.node, EdgeKind::ReadsTable, &evidence);
670            }
671            DataAccessRole::Writer => {
672                builder.edge(&symbol, &target.node, EdgeKind::WritesTable, &evidence);
673            }
674            DataAccessRole::ModelBinding => {
675                builder.edge(&target.node, &symbol, EdgeKind::ImplementedBy, &evidence);
676            }
677            DataAccessRole::Declaration => continue,
678        }
679        builder.node(symbol);
680        builder.evidence(evidence);
681    }
682}
683
684fn link_foreign_keys(
685    builder: &mut GraphBuilder,
686    foreign_keys: Vec<PendingForeignKey>,
687    tables: &BTreeMap<String, TableInfo>,
688) {
689    for pending in foreign_keys {
690        let Some(source) = tables.get(&pending.source_table_key) else {
691            continue;
692        };
693        let Some(target) = resolve_table(tables, &pending.foreign_key.referenced_table) else {
694            continue;
695        };
696        let evidence = extraction_evidence(
697            &pending.repo_id,
698            &pending.source_path,
699            &pending.content_hash,
700            Some(pending.foreign_key.evidence.get()),
701            Some(pending.foreign_key.evidence.get()),
702            "code-system-graph.extraction.data",
703            "foreign key declaration",
704        );
705        if pending.foreign_key.referenced_columns.is_empty() {
706            builder.edge(&source.node, &target.node, EdgeKind::Consumes, &evidence);
707            builder.evidence(evidence);
708            continue;
709        }
710        if pending.foreign_key.columns.len() != pending.foreign_key.referenced_columns.len() {
711            continue;
712        }
713        let pairs = pending
714            .foreign_key
715            .columns
716            .iter()
717            .zip(&pending.foreign_key.referenced_columns)
718            .filter_map(|(local, referenced)| {
719                Some((source.columns.get(local)?, target.columns.get(referenced)?))
720            })
721            .collect::<Vec<_>>();
722        if pairs.len() != pending.foreign_key.columns.len() {
723            continue;
724        }
725        for (local, referenced) in pairs {
726            builder.edge(local, referenced, EdgeKind::Consumes, &evidence);
727        }
728        builder.evidence(evidence);
729    }
730}
731
732fn append_infrastructure_documents(
733    builder: &mut GraphBuilder,
734    inputs: &[(&RepoId, &str, &str, &InfrastructureDocument)],
735) {
736    let mut deployments = Vec::new();
737    let mut resources = Vec::new();
738    let mut dependencies = Vec::new();
739
740    for (repo_id, source_path, content_hash, document) in inputs {
741        if document.deployment_units.is_empty()
742            && document.resources.is_empty()
743            && document.environment_keys.is_empty()
744        {
745            continue;
746        }
747        let artifact = append_artifact(
748            builder,
749            repo_id,
750            source_path,
751            content_hash,
752            "code-system-graph.extraction.infrastructure",
753            "infrastructure artifact",
754        );
755        append_deployment_units(
756            builder,
757            repo_id,
758            source_path,
759            content_hash,
760            &document.deployment_units,
761            &mut deployments,
762            &mut dependencies,
763        );
764        append_infrastructure_resources(
765            builder,
766            repo_id,
767            source_path,
768            content_hash,
769            &artifact,
770            &document.resources,
771            &mut deployments,
772            &mut resources,
773            &mut dependencies,
774        );
775        append_document_environment_keys(
776            builder,
777            repo_id,
778            source_path,
779            content_hash,
780            &artifact,
781            &document.environment_keys,
782        );
783    }
784    link_infrastructure_dependencies(builder, &deployments, &resources, dependencies);
785}
786
787fn link_infrastructure_dependencies(
788    builder: &mut GraphBuilder,
789    deployments: &[DeploymentInfo],
790    resources: &[ResourceInfo],
791    dependencies: Vec<PendingDependency>,
792) {
793    for dependency in dependencies {
794        let target = resolve_infrastructure_target(deployments, resources, &dependency.target);
795        let Some(target) = target else {
796            continue;
797        };
798        let evidence = extraction_evidence(
799            &dependency.repo_id,
800            &dependency.source_path,
801            &dependency.content_hash,
802            dependency.line,
803            dependency.line,
804            "code-system-graph.extraction.infrastructure",
805            "explicit infrastructure dependency",
806        );
807        builder.edge(
808            &dependency.source,
809            &target,
810            EdgeKind::CallsRemote,
811            &evidence,
812        );
813        builder.node(target);
814        builder.evidence(evidence);
815    }
816}
817
818fn append_deployment_units(
819    builder: &mut GraphBuilder,
820    repo_id: &RepoId,
821    source_path: &str,
822    content_hash: &str,
823    units: &[DeploymentUnit],
824    deployments: &mut Vec<DeploymentInfo>,
825    dependencies: &mut Vec<PendingDependency>,
826) {
827    for unit in units {
828        let technology = deployment_technology(unit.kind);
829        let deployment = deployment_node(technology, unit.namespace.as_deref(), &unit.name);
830        let line = infrastructure_line(&unit.evidence);
831        let evidence = extraction_evidence(
832            repo_id,
833            source_path,
834            content_hash,
835            line,
836            line,
837            "code-system-graph.extraction.infrastructure",
838            "deployment declaration",
839        );
840        let repository = repository_node(repo_id);
841        builder.edge(&repository, &deployment, EdgeKind::Deploys, &evidence);
842        builder.node(repository);
843        builder.node(deployment.clone());
844        builder.evidence(evidence.clone());
845        for service_name in &unit.service_names {
846            let service = service_node(repo_id, service_name);
847            builder.edge(&deployment, &service, EdgeKind::Provides, &evidence);
848            builder.node(service);
849        }
850        append_deployment_environment_keys(
851            builder,
852            repo_id,
853            source_path,
854            content_hash,
855            &deployment,
856            &unit.environment_keys,
857            line,
858        );
859        dependencies.extend(unit.dependencies.iter().map(|target| PendingDependency {
860            source: deployment.clone(),
861            target: target.clone(),
862            repo_id: repo_id.clone(),
863            source_path: source_path.to_owned(),
864            content_hash: content_hash.to_owned(),
865            line,
866        }));
867        let aliases = BTreeSet::from([
868            unit.name.clone(),
869            deployment.stable_key.clone(),
870            deployment
871                .stable_key
872                .strip_prefix("deployment:")
873                .unwrap_or(&deployment.stable_key)
874                .to_owned(),
875        ]);
876        deployments.push(DeploymentInfo {
877            repo_id: repo_id.clone(),
878            node: deployment,
879            aliases,
880        });
881    }
882}
883
884fn append_deployment_environment_keys(
885    builder: &mut GraphBuilder,
886    repo_id: &RepoId,
887    source_path: &str,
888    content_hash: &str,
889    deployment: &Node,
890    key_names: &[String],
891    line: Option<u32>,
892) {
893    for key_name in key_names {
894        let config = resolve_or_create_config(builder, repo_id, &deployment.stable_key, key_name);
895        let evidence = extraction_evidence(
896            repo_id,
897            source_path,
898            content_hash,
899            line,
900            line,
901            "code-system-graph.extraction.infrastructure",
902            "environment key declaration",
903        );
904        builder.edge(deployment, &config, EdgeKind::Configures, &evidence);
905        builder.node(config);
906        builder.evidence(evidence);
907    }
908}
909
910#[expect(
911    clippy::too_many_arguments,
912    reason = "The helper preserves explicit source provenance."
913)]
914fn append_infrastructure_resources(
915    builder: &mut GraphBuilder,
916    repo_id: &RepoId,
917    source_path: &str,
918    content_hash: &str,
919    artifact: &Node,
920    document_resources: &[InfrastructureResource],
921    deployments: &mut [DeploymentInfo],
922    resources: &mut Vec<ResourceInfo>,
923    dependencies: &mut Vec<PendingDependency>,
924) {
925    for resource in document_resources {
926        let line = infrastructure_line(&resource.evidence);
927        let node = infrastructure_resource_node(repo_id, resource);
928        if let Some(node) = node {
929            let evidence = extraction_evidence(
930                repo_id,
931                source_path,
932                content_hash,
933                line,
934                line,
935                "code-system-graph.extraction.infrastructure",
936                "infrastructure resource declaration",
937            );
938            builder.edge(artifact, &node, EdgeKind::Contains, &evidence);
939            builder.node(node.clone());
940            builder.evidence(evidence);
941            let aliases = BTreeSet::from([
942                resource.name.clone(),
943                format!("{}.{}", resource.resource_type, resource.name),
944                format!("{}/{}", resource.resource_type, resource.name),
945                node.stable_key.clone(),
946            ]);
947            resources.push(ResourceInfo {
948                node: node.clone(),
949                aliases: aliases.clone(),
950            });
951            for deployment in &mut *deployments {
952                if deployment.repo_id == *repo_id && deployment.node.label == resource.name {
953                    deployment.aliases.extend(aliases.iter().cloned());
954                }
955            }
956            dependencies.extend(
957                resource
958                    .dependencies
959                    .iter()
960                    .map(|target| PendingDependency {
961                        source: node.clone(),
962                        target: target.clone(),
963                        repo_id: repo_id.clone(),
964                        source_path: source_path.to_owned(),
965                        content_hash: content_hash.to_owned(),
966                        line,
967                    }),
968            );
969        }
970        append_resource_config_keys(
971            builder,
972            repo_id,
973            source_path,
974            content_hash,
975            artifact,
976            resource,
977            line,
978        );
979    }
980}
981
982fn infrastructure_resource_node(
983    repo_id: &RepoId,
984    resource: &InfrastructureResource,
985) -> Option<Node> {
986    match resource.kind {
987        InfrastructureResourceKind::Service => Some(service_node(repo_id, &resource.name)),
988        InfrastructureResourceKind::Database => Some(database_node(&resource.name)),
989        InfrastructureResourceKind::Topic | InfrastructureResourceKind::Queue => Some(
990            event_channel_node(resource.namespace.as_deref(), &resource.name),
991        ),
992        InfrastructureResourceKind::Ingress | InfrastructureResourceKind::Other => None,
993    }
994}
995
996fn append_resource_config_keys(
997    builder: &mut GraphBuilder,
998    repo_id: &RepoId,
999    source_path: &str,
1000    content_hash: &str,
1001    artifact: &Node,
1002    resource: &InfrastructureResource,
1003    line: Option<u32>,
1004) {
1005    for key_name in &resource.key_names {
1006        let scope = format!(
1007            "resource:{}:{}:{}",
1008            resource.resource_type,
1009            resource.namespace.as_deref().unwrap_or(""),
1010            resource.name
1011        );
1012        let config = resolve_or_create_config(builder, repo_id, &scope, key_name);
1013        let evidence = extraction_evidence(
1014            repo_id,
1015            source_path,
1016            content_hash,
1017            line,
1018            line,
1019            "code-system-graph.extraction.infrastructure",
1020            "infrastructure configuration key",
1021        );
1022        builder.edge(artifact, &config, EdgeKind::Configures, &evidence);
1023        builder.node(config);
1024        builder.evidence(evidence);
1025    }
1026}
1027
1028fn append_document_environment_keys(
1029    builder: &mut GraphBuilder,
1030    repo_id: &RepoId,
1031    source_path: &str,
1032    content_hash: &str,
1033    artifact: &Node,
1034    key_names: &[String],
1035) {
1036    for key_name in key_names {
1037        let config = resolve_or_create_config(builder, repo_id, "environment", key_name);
1038        let evidence = extraction_evidence(
1039            repo_id,
1040            source_path,
1041            content_hash,
1042            None,
1043            None,
1044            "code-system-graph.extraction.infrastructure",
1045            "environment key declaration",
1046        );
1047        builder.edge(artifact, &config, EdgeKind::Configures, &evidence);
1048        builder.node(config);
1049        builder.evidence(evidence);
1050    }
1051}
1052
1053fn append_documentation_documents(
1054    builder: &mut GraphBuilder,
1055    inputs: &[(&RepoId, &str, &str, &DocumentationDocument)],
1056    known_nodes: &[Node],
1057    repository_aliases: &[RepositoryReference<'_>],
1058) {
1059    let mut references = Vec::new();
1060    for (repo_id, source_path, content_hash, document) in inputs {
1061        let artifact = append_artifact(
1062            builder,
1063            repo_id,
1064            source_path,
1065            content_hash,
1066            "code-system-graph.extraction.documents",
1067            "documentation artifact",
1068        );
1069        append_document_records(
1070            builder,
1071            repo_id,
1072            source_path,
1073            content_hash,
1074            &artifact,
1075            &document.records,
1076            &mut references,
1077        );
1078        append_ownership_rules(
1079            builder,
1080            repo_id,
1081            source_path,
1082            content_hash,
1083            &document.ownership_rules,
1084        );
1085    }
1086
1087    let mut candidates = builder.facts.nodes.clone();
1088    candidates.extend_from_slice(known_nodes);
1089    for (alias, repo_id, _) in repository_aliases {
1090        if !alias.is_empty() {
1091            candidates.push(repository_node(repo_id));
1092        }
1093    }
1094    link_document_references(builder, &candidates, repository_aliases, references);
1095}
1096
1097fn link_document_references(
1098    builder: &mut GraphBuilder,
1099    candidates: &[Node],
1100    repository_aliases: &[RepositoryReference<'_>],
1101    references: Vec<PendingReference>,
1102) {
1103    for pending in references {
1104        let Some(target) = resolve_reference(
1105            candidates,
1106            repository_aliases,
1107            &pending.repo_id,
1108            &pending.reference,
1109        ) else {
1110            if pending.reference.kind == ExplicitReferenceKind::RepositoryDependency {
1111                builder.facts.coverage_gaps.push(RepositoryCoverageGap {
1112                    repo_id: pending.repo_id.clone(),
1113                    reason: format!(
1114                        "An explicit repository dependency at {}:{} could not be matched to an exact registered remote; no dependency edge was asserted.",
1115                        pending.source_path,
1116                        pending.reference.evidence.start
1117                    ),
1118                });
1119            }
1120            continue;
1121        };
1122        let evidence = extraction_evidence(
1123            &pending.repo_id,
1124            &pending.source_path,
1125            &pending.content_hash,
1126            Some(pending.reference.evidence.start),
1127            Some(pending.reference.evidence.end),
1128            "code-system-graph.extraction.documents",
1129            "explicit document reference",
1130        );
1131        if pending.reference.kind == ExplicitReferenceKind::RepositoryDependency {
1132            let source = repository_node(&pending.repo_id);
1133            builder.edge(&source, &target, EdgeKind::DependsOnRepository, &evidence);
1134            builder.node(source);
1135        } else {
1136            builder.edge(&pending.document, &target, EdgeKind::Documents, &evidence);
1137        }
1138        builder.node(target);
1139        builder.evidence(evidence);
1140    }
1141}
1142
1143fn append_document_records(
1144    builder: &mut GraphBuilder,
1145    repo_id: &RepoId,
1146    source_path: &str,
1147    content_hash: &str,
1148    artifact: &Node,
1149    records: &[DocumentRecord],
1150    references: &mut Vec<PendingReference>,
1151) {
1152    for record in records {
1153        let node = document_node(
1154            repo_id,
1155            &record.source_path,
1156            record.kind,
1157            record.title.as_deref(),
1158        );
1159        let record_evidence = extraction_evidence(
1160            repo_id,
1161            source_path,
1162            content_hash,
1163            None,
1164            None,
1165            "code-system-graph.extraction.documents",
1166            "document record",
1167        );
1168        builder.edge(artifact, &node, EdgeKind::Contains, &record_evidence);
1169        builder.node(node.clone());
1170        builder.evidence(record_evidence);
1171        let catalog_service = (record.kind == DocumentKind::ServiceCatalog)
1172            .then_some(record.title.as_deref())
1173            .flatten()
1174            .map(|name| service_node(repo_id, name));
1175        if let Some(service) = &catalog_service {
1176            builder.node(service.clone());
1177        }
1178        for owner_name in &record.owners {
1179            let owner = owner_node(owner_name);
1180            let owner_range = record
1181                .references
1182                .iter()
1183                .find(|reference| {
1184                    reference.kind == ExplicitReferenceKind::Owner
1185                        && reference.target == *owner_name
1186                })
1187                .map(|reference| reference.evidence);
1188            let evidence = extraction_evidence(
1189                repo_id,
1190                source_path,
1191                content_hash,
1192                owner_range.map(|range| range.start),
1193                owner_range.map(|range| range.end),
1194                "code-system-graph.extraction.documents",
1195                "explicit ownership declaration",
1196            );
1197            let ownership_subject = catalog_service.as_ref().unwrap_or(&node);
1198            builder.edge(ownership_subject, &owner, EdgeKind::OwnedBy, &evidence);
1199            builder.node(owner);
1200            builder.evidence(evidence);
1201        }
1202        references.extend(
1203            record
1204                .references
1205                .iter()
1206                .cloned()
1207                .map(|reference| PendingReference {
1208                    document: node.clone(),
1209                    repo_id: repo_id.clone(),
1210                    source_path: source_path.to_owned(),
1211                    content_hash: content_hash.to_owned(),
1212                    reference,
1213                }),
1214        );
1215    }
1216}
1217
1218fn append_ownership_rules(
1219    builder: &mut GraphBuilder,
1220    repo_id: &RepoId,
1221    source_path: &str,
1222    content_hash: &str,
1223    rules: &[OwnershipRule],
1224) {
1225    let document = document_node(
1226        repo_id,
1227        source_path,
1228        DocumentKind::Codeowners,
1229        Some("CODEOWNERS"),
1230    );
1231    for rule in rules {
1232        for owner_name in &rule.owners {
1233            let owner = owner_node(owner_name);
1234            let evidence = extraction_evidence(
1235                repo_id,
1236                source_path,
1237                content_hash,
1238                Some(rule.line),
1239                Some(rule.line),
1240                "code-system-graph.extraction.documents",
1241                "CODEOWNERS owner declaration",
1242            );
1243            builder.edge(&document, &owner, EdgeKind::OwnedBy, &evidence);
1244            builder.node(document.clone());
1245            builder.node(owner);
1246            builder.evidence(evidence);
1247        }
1248    }
1249}
1250
1251fn append_artifact(
1252    builder: &mut GraphBuilder,
1253    repo_id: &RepoId,
1254    source_path: &str,
1255    content_hash: &str,
1256    extractor: &str,
1257    note: &str,
1258) -> Node {
1259    let repository = repository_node(repo_id);
1260    let artifact = artifact_node(repo_id, source_path);
1261    let evidence = extraction_evidence(
1262        repo_id,
1263        source_path,
1264        content_hash,
1265        Some(1),
1266        Some(1),
1267        extractor,
1268        note,
1269    );
1270    builder.edge(&repository, &artifact, EdgeKind::Contains, &evidence);
1271    builder.node(repository);
1272    builder.node(artifact.clone());
1273    builder.evidence(evidence);
1274    artifact
1275}
1276
1277fn table_info(document: &DataDocument, table: &DatabaseTable) -> TableInfo {
1278    let database = table
1279        .database
1280        .clone()
1281        .or_else(|| document.database_name.clone());
1282    let schema = table
1283        .schema
1284        .clone()
1285        .or_else(|| document.schema_name.clone());
1286    let node = table_node(database.as_deref(), schema.as_deref(), &table.name);
1287    let columns = table
1288        .columns
1289        .iter()
1290        .map(|column| {
1291            (
1292                column.name.clone(),
1293                column_node(&node.stable_key, &column.name),
1294            )
1295        })
1296        .collect();
1297    TableInfo {
1298        node,
1299        database,
1300        schema,
1301        name: table.name.clone(),
1302        columns,
1303    }
1304}
1305
1306fn resolve_table<'a>(
1307    tables: &'a BTreeMap<String, TableInfo>,
1308    target: &str,
1309) -> Option<&'a TableInfo> {
1310    let matches = tables
1311        .values()
1312        .filter(|table| table_aliases(table).contains(target))
1313        .map(|table| table.node.id.clone())
1314        .collect::<BTreeSet<_>>();
1315    let id = exactly_one(matches)?;
1316    tables.values().find(|table| table.node.id == id)
1317}
1318
1319fn table_aliases(table: &TableInfo) -> BTreeSet<String> {
1320    let mut aliases = BTreeSet::from([
1321        table.node.stable_key.clone(),
1322        table
1323            .node
1324            .stable_key
1325            .strip_prefix("table:")
1326            .unwrap_or(&table.node.stable_key)
1327            .to_owned(),
1328        table.name.clone(),
1329    ]);
1330    if let Some(schema) = &table.schema {
1331        aliases.insert(format!("{schema}.{}", table.name));
1332    }
1333    if let Some(database) = &table.database {
1334        aliases.insert(format!("{database}.{}", table.name));
1335        if let Some(schema) = &table.schema {
1336            aliases.insert(format!("{database}.{schema}.{}", table.name));
1337        }
1338    }
1339    aliases
1340}
1341
1342fn resolve_or_create_config(
1343    builder: &GraphBuilder,
1344    repo_id: &RepoId,
1345    fallback_scope: &str,
1346    name: &str,
1347) -> Node {
1348    let matches = builder
1349        .facts
1350        .nodes
1351        .iter()
1352        .filter(|node| {
1353            node.kind == NodeKind::ConfigKey
1354                && node.repo_id.as_ref() == Some(repo_id)
1355                && node.label == name
1356        })
1357        .map(|node| node.id.clone())
1358        .collect::<BTreeSet<_>>();
1359    exactly_one(matches)
1360        .and_then(|id| {
1361            builder
1362                .facts
1363                .nodes
1364                .iter()
1365                .find(|node| node.id == id)
1366                .cloned()
1367        })
1368        .unwrap_or_else(|| config_node(repo_id, fallback_scope, name))
1369}
1370
1371fn resolve_infrastructure_target(
1372    deployments: &[DeploymentInfo],
1373    resources: &[ResourceInfo],
1374    target: &str,
1375) -> Option<Node> {
1376    let deployment_matches = deployments
1377        .iter()
1378        .filter(|deployment| deployment.aliases.contains(target))
1379        .map(|deployment| deployment.node.id.clone())
1380        .collect::<BTreeSet<_>>();
1381    if !deployment_matches.is_empty() {
1382        let id = exactly_one(deployment_matches)?;
1383        return deployments
1384            .iter()
1385            .find(|deployment| deployment.node.id == id)
1386            .map(|deployment| deployment.node.clone());
1387    }
1388    let resource_matches = resources
1389        .iter()
1390        .filter(|resource| resource.aliases.contains(target))
1391        .map(|resource| resource.node.id.clone())
1392        .collect::<BTreeSet<_>>();
1393    let id = exactly_one(resource_matches)?;
1394    resources
1395        .iter()
1396        .find(|resource| resource.node.id == id)
1397        .map(|resource| resource.node.clone())
1398}
1399
1400fn resolve_reference(
1401    candidates: &[Node],
1402    repository_aliases: &[RepositoryReference<'_>],
1403    repo_id: &RepoId,
1404    reference: &ExplicitReference,
1405) -> Option<Node> {
1406    let matches = candidates
1407        .iter()
1408        .filter(|node| {
1409            reference_matches(
1410                node,
1411                repository_aliases,
1412                repo_id,
1413                reference.kind,
1414                &reference.target,
1415            )
1416        })
1417        .map(|node| node.id.clone())
1418        .collect::<BTreeSet<_>>();
1419    let id = exactly_one(matches)?;
1420    candidates.iter().find(|node| node.id == id).cloned()
1421}
1422
1423fn reference_matches(
1424    node: &Node,
1425    repository_aliases: &[RepositoryReference<'_>],
1426    repo_id: &RepoId,
1427    kind: ExplicitReferenceKind,
1428    target: &str,
1429) -> bool {
1430    let expected = match kind {
1431        ExplicitReferenceKind::Repository | ExplicitReferenceKind::RepositoryDependency => {
1432            &[NodeKind::Repository][..]
1433        }
1434        ExplicitReferenceKind::Service => &[NodeKind::Service][..],
1435        ExplicitReferenceKind::HttpContract => &[NodeKind::HttpOperation][..],
1436        ExplicitReferenceKind::EventChannel => &[NodeKind::EventChannel][..],
1437        ExplicitReferenceKind::GraphqlOperation => &[NodeKind::GraphqlOperation][..],
1438        ExplicitReferenceKind::RpcMethod => &[NodeKind::RpcMethod][..],
1439        ExplicitReferenceKind::DatabaseTable => &[NodeKind::DatabaseTable][..],
1440        ExplicitReferenceKind::Deployment => &[NodeKind::Deployment][..],
1441        ExplicitReferenceKind::ConfigKey => &[NodeKind::ConfigKey][..],
1442        ExplicitReferenceKind::Document => &[NodeKind::Document, NodeKind::Adr][..],
1443        ExplicitReferenceKind::Owner => &[NodeKind::Owner][..],
1444    };
1445    if !expected.contains(&node.kind) {
1446        return false;
1447    }
1448    if matches!(
1449        kind,
1450        ExplicitReferenceKind::Repository | ExplicitReferenceKind::RepositoryDependency
1451    ) {
1452        return node.repo_id.as_ref().is_some_and(|candidate| {
1453            candidate.as_str() == target
1454                || repository_aliases.iter().any(|(alias, repo, remote)| {
1455                    (*alias == target || remote.is_some_and(|remote| remote == target))
1456                        && *repo == candidate
1457                })
1458        });
1459    }
1460    if node.stable_key == target || node.label == target {
1461        return true;
1462    }
1463    let prefix = reference_prefix(kind);
1464    if node
1465        .stable_key
1466        .strip_prefix(prefix)
1467        .is_some_and(|suffix| suffix == target)
1468    {
1469        return true;
1470    }
1471    match kind {
1472        ExplicitReferenceKind::Service => {
1473            target
1474                .split_once(':')
1475                .and_then(|(alias, name)| {
1476                    repository_aliases
1477                        .iter()
1478                        .find(|(candidate, _, _)| *candidate == alias)
1479                        .map(|(_, repository, _)| (repository, name))
1480                })
1481                .is_some_and(|(repository, name)| {
1482                    node.stable_key == format!("service:{}:{name}", repository.as_str())
1483                })
1484                || node.stable_key == format!("service:{}:{target}", repo_id.as_str())
1485        }
1486        ExplicitReferenceKind::Document => {
1487            node.stable_key == format!("document:{}:{target}", repo_id.as_str())
1488        }
1489        ExplicitReferenceKind::ConfigKey => {
1490            node.stable_key == format!("config:{}:{target}", repo_id.as_str())
1491        }
1492        ExplicitReferenceKind::Repository
1493        | ExplicitReferenceKind::RepositoryDependency
1494        | ExplicitReferenceKind::HttpContract
1495        | ExplicitReferenceKind::EventChannel
1496        | ExplicitReferenceKind::GraphqlOperation
1497        | ExplicitReferenceKind::RpcMethod
1498        | ExplicitReferenceKind::DatabaseTable
1499        | ExplicitReferenceKind::Deployment
1500        | ExplicitReferenceKind::Owner => false,
1501    }
1502}
1503
1504const fn reference_prefix(kind: ExplicitReferenceKind) -> &'static str {
1505    match kind {
1506        ExplicitReferenceKind::Repository | ExplicitReferenceKind::RepositoryDependency => {
1507            "repository:"
1508        }
1509        ExplicitReferenceKind::Service => "service:",
1510        ExplicitReferenceKind::HttpContract => "http:",
1511        ExplicitReferenceKind::EventChannel => "event:",
1512        ExplicitReferenceKind::GraphqlOperation => "graphql:",
1513        ExplicitReferenceKind::RpcMethod => "rpc:",
1514        ExplicitReferenceKind::DatabaseTable => "table:",
1515        ExplicitReferenceKind::Deployment => "deployment:",
1516        ExplicitReferenceKind::ConfigKey => "config:",
1517        ExplicitReferenceKind::Document => "document:",
1518        ExplicitReferenceKind::Owner => "owner:",
1519    }
1520}
1521
1522fn exactly_one<T: Ord>(mut values: BTreeSet<T>) -> Option<T> {
1523    (values.len() == 1).then(|| values.pop_first()).flatten()
1524}
1525
1526fn repository_node(repo_id: &RepoId) -> Node {
1527    graph_node(
1528        format!("repository:{}", repo_id.as_str()),
1529        NodeKind::Repository,
1530        Some(repo_id.clone()),
1531        repo_id.as_str(),
1532    )
1533}
1534
1535fn artifact_node(repo_id: &RepoId, source_path: &str) -> Node {
1536    graph_node(
1537        format!("artifact:{}:{source_path}", repo_id.as_str()),
1538        NodeKind::Artifact,
1539        Some(repo_id.clone()),
1540        source_path,
1541    )
1542}
1543
1544fn database_node(name: &str) -> Node {
1545    graph_node(format!("database:{name}"), NodeKind::Database, None, name)
1546}
1547
1548fn table_node(database: Option<&str>, schema: Option<&str>, name: &str) -> Node {
1549    graph_node(
1550        format!(
1551            "table:{}:{}:{name}",
1552            database.unwrap_or(""),
1553            schema.unwrap_or("")
1554        ),
1555        NodeKind::DatabaseTable,
1556        None,
1557        name,
1558    )
1559}
1560
1561fn column_node(table_key: &str, name: &str) -> Node {
1562    graph_node(
1563        format!("column:{table_key}:{name}"),
1564        NodeKind::DatabaseColumn,
1565        None,
1566        name,
1567    )
1568}
1569
1570fn index_known_source_symbols(nodes: &[Node]) -> KnownSourceSymbols {
1571    nodes
1572        .iter()
1573        .filter_map(|node| {
1574            let identity = crate::SourceSymbolIdentity::from_node(node)?;
1575            identity.language()?;
1576            Some((
1577                (
1578                    identity.repository().clone(),
1579                    identity.source_path().to_owned(),
1580                    identity.symbol().to_owned(),
1581                ),
1582                node.clone(),
1583            ))
1584        })
1585        .collect()
1586}
1587
1588fn data_symbol_node(
1589    repo_id: &RepoId,
1590    source_path: &str,
1591    owner: &str,
1592    source_symbols: &KnownSourceSymbols,
1593) -> Node {
1594    if let Some(node) =
1595        source_symbols.get(&(repo_id.clone(), source_path.to_owned(), owner.to_owned()))
1596    {
1597        return node.clone();
1598    }
1599    crate::SourceSymbolIdentity::data(repo_id.clone(), source_path, owner).node(owner)
1600}
1601
1602fn deployment_node(technology: &str, namespace: Option<&str>, name: &str) -> Node {
1603    graph_node(
1604        format!("deployment:{technology}:{}:{name}", namespace.unwrap_or("")),
1605        NodeKind::Deployment,
1606        None,
1607        name,
1608    )
1609}
1610
1611fn service_node(repo_id: &RepoId, name: &str) -> Node {
1612    graph_node(
1613        format!("service:{}:{name}", repo_id.as_str()),
1614        NodeKind::Service,
1615        Some(repo_id.clone()),
1616        name,
1617    )
1618}
1619
1620fn config_node(repo_id: &RepoId, scope: &str, name: &str) -> Node {
1621    graph_node(
1622        format!("config:{}:{scope}:{name}", repo_id.as_str()),
1623        NodeKind::ConfigKey,
1624        Some(repo_id.clone()),
1625        name,
1626    )
1627}
1628
1629fn event_channel_node(namespace: Option<&str>, name: &str) -> Node {
1630    graph_node(
1631        format!("event:infrastructure:{}:{name}", namespace.unwrap_or("")),
1632        NodeKind::EventChannel,
1633        None,
1634        name,
1635    )
1636}
1637
1638fn document_node(
1639    repo_id: &RepoId,
1640    source_path: &str,
1641    kind: DocumentKind,
1642    _title: Option<&str>,
1643) -> Node {
1644    graph_node(
1645        format!("document:{}:{source_path}", repo_id.as_str()),
1646        if kind == DocumentKind::Adr {
1647            NodeKind::Adr
1648        } else {
1649            NodeKind::Document
1650        },
1651        Some(repo_id.clone()),
1652        source_path,
1653    )
1654}
1655
1656fn owner_node(name: &str) -> Node {
1657    graph_node(format!("owner:{name}"), NodeKind::Owner, None, name)
1658}
1659
1660fn graph_node(stable_key: String, kind: NodeKind, repo_id: Option<RepoId>, label: &str) -> Node {
1661    Node {
1662        id: NodeId::new(stable_id("node", &stable_key)),
1663        kind,
1664        repo_id,
1665        stable_key,
1666        label: label.to_owned(),
1667    }
1668}
1669
1670fn extraction_evidence(
1671    repo_id: &RepoId,
1672    source_path: &str,
1673    content_hash: &str,
1674    start_line: Option<u32>,
1675    end_line: Option<u32>,
1676    extractor: &str,
1677    note: &str,
1678) -> Evidence {
1679    let key = format!(
1680        "{}:{source_path}:{}:{}:{extractor}:{note}:{content_hash}",
1681        repo_id.as_str(),
1682        start_line.map_or_else(String::new, |line| line.to_string()),
1683        end_line.map_or_else(String::new, |line| line.to_string())
1684    );
1685    Evidence {
1686        id: EvidenceId::new(stable_id("evidence", &key)),
1687        repo_id: Some(repo_id.clone()),
1688        file_path: Some(source_path.to_owned()),
1689        start_line,
1690        end_line,
1691        extractor: extractor.to_owned(),
1692        extractor_version: "1.0.0".to_owned(),
1693        provenance: Provenance::Extracted,
1694        confidence: 1.0,
1695        observed_at_commit: None,
1696        content_hash: Some(content_hash.to_owned()),
1697        note: Some(note.to_owned()),
1698    }
1699}
1700
1701const fn deployment_technology(kind: DeploymentKind) -> &'static str {
1702    match kind {
1703        DeploymentKind::DockerComposeService => "docker_compose_service",
1704        DeploymentKind::KubernetesDeployment => "kubernetes_deployment",
1705        DeploymentKind::KubernetesStatefulSet => "kubernetes_stateful_set",
1706        DeploymentKind::KubernetesDaemonSet => "kubernetes_daemon_set",
1707        DeploymentKind::KubernetesJob => "kubernetes_job",
1708        DeploymentKind::KubernetesCronJob => "kubernetes_cron_job",
1709        DeploymentKind::KubernetesPod => "kubernetes_pod",
1710        DeploymentKind::HelmTemplate => "helm_template",
1711        DeploymentKind::TerraformResource => "terraform_resource",
1712    }
1713}
1714
1715fn infrastructure_line(evidence: &[InfrastructureEvidence]) -> Option<u32> {
1716    evidence.iter().filter_map(|item| item.line).min()
1717}
1718
1719fn line_from_usize(line: usize) -> Option<u32> {
1720    u32::try_from(line).ok()
1721}
1722
1723#[cfg(test)]
1724mod tests {
1725    use code_system_graph_model::{EdgeKind, Node, NodeId, NodeKind, RepoId, stable_id};
1726
1727    use super::documents_to_graph;
1728    use crate::{
1729        DataAccessObservation, DataAccessRole, DataArtifactKind, DataDocument, DataEvidenceLine, DataOperation, DatabaseTable, DeploymentKind, DeploymentUnit, InfrastructureArtifactKind, InfrastructureDocument, InfrastructureEvidence, InfrastructureEvidenceKind, SourceLanguage, extract_data_artifact, extract_markdown, extract_safe_config, extract_service_catalog, parse_literal_sql_source_at_root
1730    };
1731
1732    #[test]
1733    fn data_reader_links_source_symbol_to_unique_table() {
1734        let repo = RepoId::new("repo:data");
1735        let line = DataEvidenceLine::new(7).expect("valid evidence line");
1736        let declaration = DataDocument {
1737            source_path: "schema.sql".to_owned(),
1738            artifact_kind: DataArtifactKind::DeclarativeSqlSchema,
1739            database_name: None,
1740            schema_name: None,
1741            tables: vec![DatabaseTable {
1742                database: None,
1743                schema: None,
1744                name: "users".to_owned(),
1745                columns: Vec::new(),
1746                indexes: Vec::new(),
1747                foreign_keys: Vec::new(),
1748                evidence: line,
1749            }],
1750            migration: None,
1751            accesses: Vec::new(),
1752            frameworks: Vec::new(),
1753            references: Vec::new(),
1754            owners: Vec::new(),
1755            warnings: Vec::new(),
1756            incomplete: false,
1757        };
1758        let reader = DataDocument {
1759            source_path: "src/users.rs".to_owned(),
1760            artifact_kind: DataArtifactKind::LiteralQuerySource,
1761            database_name: None,
1762            schema_name: None,
1763            tables: Vec::new(),
1764            migration: None,
1765            accesses: vec![DataAccessObservation {
1766                role: DataAccessRole::Reader,
1767                table: "users".to_owned(),
1768                model: None,
1769                owner: Some("load_users".to_owned()),
1770                operation: Some(DataOperation::Select),
1771                evidence: line,
1772            }],
1773            frameworks: Vec::new(),
1774            references: Vec::new(),
1775            owners: vec!["load_users".to_owned()],
1776            warnings: Vec::new(),
1777            incomplete: false,
1778        };
1779
1780        let facts = documents_to_graph(
1781            &[
1782                (&repo, "schema.sql", "schema-hash", &declaration),
1783                (&repo, "src/users.rs", "source-hash", &reader),
1784            ],
1785            &[],
1786            &[],
1787            &[],
1788            &[],
1789            &[],
1790        );
1791
1792        assert!(facts.edges.iter().any(|edge| {
1793            edge.kind == EdgeKind::ReadsTable
1794                && facts.nodes.iter().any(|node| {
1795                    node.id == edge.source
1796                        && node.kind == NodeKind::SymbolRef
1797                        && node.label == "load_users"
1798                })
1799                && facts.nodes.iter().any(|node| {
1800                    node.id == edge.target
1801                        && node.kind == NodeKind::DatabaseTable
1802                        && node.label == "users"
1803                })
1804        }));
1805    }
1806
1807    #[test]
1808    fn data_reader_reuses_exact_known_source_symbol() {
1809        let repo = RepoId::new("repo:data");
1810        let line = DataEvidenceLine::new(7).expect("valid evidence line");
1811        let declaration = DataDocument {
1812            source_path: "schema.sql".to_owned(),
1813            artifact_kind: DataArtifactKind::DeclarativeSqlSchema,
1814            database_name: None,
1815            schema_name: None,
1816            tables: vec![DatabaseTable {
1817                database: None,
1818                schema: None,
1819                name: "users".to_owned(),
1820                columns: Vec::new(),
1821                indexes: Vec::new(),
1822                foreign_keys: Vec::new(),
1823                evidence: line,
1824            }],
1825            migration: None,
1826            accesses: Vec::new(),
1827            frameworks: Vec::new(),
1828            references: Vec::new(),
1829            owners: Vec::new(),
1830            warnings: Vec::new(),
1831            incomplete: false,
1832        };
1833        let reader = DataDocument {
1834            source_path: "src/users.rs".to_owned(),
1835            artifact_kind: DataArtifactKind::LiteralQuerySource,
1836            database_name: None,
1837            schema_name: None,
1838            tables: Vec::new(),
1839            migration: None,
1840            accesses: vec![DataAccessObservation {
1841                role: DataAccessRole::Reader,
1842                table: "users".to_owned(),
1843                model: None,
1844                owner: Some("load_users".to_owned()),
1845                operation: Some(DataOperation::Select),
1846                evidence: line,
1847            }],
1848            frameworks: Vec::new(),
1849            references: Vec::new(),
1850            owners: vec!["load_users".to_owned()],
1851            warnings: Vec::new(),
1852            incomplete: false,
1853        };
1854        let stable_key = "symbol:repo:data:rust:src/users.rs:load_users".to_owned();
1855        let source_symbol = Node {
1856            id: NodeId::new(stable_id("node", &stable_key)),
1857            kind: NodeKind::SymbolRef,
1858            repo_id: Some(repo.clone()),
1859            stable_key,
1860            label: "rust::load_users".to_owned(),
1861        };
1862
1863        let facts = documents_to_graph(
1864            &[
1865                (&repo, "schema.sql", "schema-hash", &declaration),
1866                (&repo, "src/users.rs", "source-hash", &reader),
1867            ],
1868            &[],
1869            &[],
1870            &[],
1871            std::slice::from_ref(&source_symbol),
1872            &[],
1873        );
1874
1875        assert!(facts.nodes.iter().any(|node| node == &source_symbol));
1876        assert!(
1877            !facts
1878                .nodes
1879                .iter()
1880                .any(|node| node.stable_key.starts_with("data-symbol:"))
1881        );
1882        assert!(
1883            facts.edges.iter().any(|edge| {
1884                edge.source == source_symbol.id && edge.kind == EdgeKind::ReadsTable
1885            })
1886        );
1887    }
1888
1889    #[test]
1890    fn sqlalchemy_access_links_through_explicit_model_binding() {
1891        let repo = RepoId::new("repo:orm");
1892        let models = extract_data_artifact(
1893            "app/models.py",
1894            r#"
1895class Services(Base):
1896    __tablename__ = "services"
1897    id = Column(Integer, primary_key=True)
1898"#,
1899        )
1900        .expect("model should parse");
1901        let controller = parse_literal_sql_source_at_root(
1902            SourceLanguage::Python,
1903            "app/controllers.py",
1904            "",
1905            r"
1906from sqlalchemy.orm import Session
1907from app import models
1908
1909def list_services(db: Session):
1910    return db.query(models.Services).all()
1911
1912def create_service(db: Session):
1913    service = models.Services()
1914    db.add(service)
1915",
1916        );
1917
1918        let facts = documents_to_graph(
1919            &[
1920                (&repo, "app/models.py", "models-hash", &models),
1921                (&repo, "app/controllers.py", "controllers-hash", &controller),
1922            ],
1923            &[],
1924            &[],
1925            &[],
1926            &[],
1927            &[],
1928        );
1929
1930        assert!(facts.edges.iter().any(|edge| {
1931            edge.kind == EdgeKind::ReadsTable
1932                && facts
1933                    .nodes
1934                    .iter()
1935                    .any(|node| node.id == edge.source && node.label == "list_services")
1936                && facts
1937                    .nodes
1938                    .iter()
1939                    .any(|node| node.id == edge.target && node.label == "services")
1940        }));
1941        assert!(facts.edges.iter().any(|edge| {
1942            edge.kind == EdgeKind::WritesTable
1943                && facts
1944                    .nodes
1945                    .iter()
1946                    .any(|node| node.id == edge.source && node.label == "create_service")
1947                && facts
1948                    .nodes
1949                    .iter()
1950                    .any(|node| node.id == edge.target && node.label == "services")
1951        }));
1952    }
1953
1954    #[test]
1955    fn sqlx_query_file_links_calling_symbol_to_file_and_table() {
1956        let repo = RepoId::new("repo:data");
1957        let schema =
1958            extract_data_artifact("crates/api/schema.sql", "CREATE TABLE users (id INTEGER);")
1959                .expect("schema should parse");
1960        let query = extract_data_artifact(
1961            "crates/api/queries/users.sql",
1962            "SELECT id FROM users WHERE id = $1;",
1963        )
1964        .expect("query should parse");
1965        let source = parse_literal_sql_source_at_root(
1966            SourceLanguage::Rust,
1967            "crates/api/src/users.rs",
1968            "crates/api",
1969            r#"
1970async fn load_user(pool: &sqlx::PgPool) {
1971    sqlx::query_file!("queries/users.sql", 7_i64).fetch_one(pool).await;
1972}
1973"#,
1974        );
1975
1976        let facts = documents_to_graph(
1977            &[
1978                (&repo, "crates/api/schema.sql", "schema-hash", &schema),
1979                (&repo, "crates/api/queries/users.sql", "query-hash", &query),
1980                (&repo, "crates/api/src/users.rs", "source-hash", &source),
1981            ],
1982            &[],
1983            &[],
1984            &[],
1985            &[],
1986            &[],
1987        );
1988        let symbol = facts
1989            .nodes
1990            .iter()
1991            .find(|node| node.kind == NodeKind::SymbolRef && node.label == "load_user")
1992            .expect("calling symbol");
1993        let query_artifact = facts
1994            .nodes
1995            .iter()
1996            .find(|node| {
1997                node.kind == NodeKind::Artifact && node.label == "crates/api/queries/users.sql"
1998            })
1999            .expect("query artifact");
2000        let users = facts
2001            .nodes
2002            .iter()
2003            .find(|node| node.kind == NodeKind::DatabaseTable && node.label == "users")
2004            .expect("users table");
2005
2006        assert!(facts.edges.iter().any(|edge| {
2007            edge.source == symbol.id
2008                && edge.target == query_artifact.id
2009                && edge.kind == EdgeKind::Consumes
2010        }));
2011        assert!(facts.edges.iter().any(|edge| {
2012            edge.source == symbol.id && edge.target == users.id && edge.kind == EdgeKind::ReadsTable
2013        }));
2014    }
2015
2016    #[test]
2017    fn sqlx_default_migrate_macro_uses_incremental_configuration_artifact() {
2018        let repo = RepoId::new("repo:data");
2019        let source = parse_literal_sql_source_at_root(
2020            SourceLanguage::Rust,
2021            "crates/api/src/lib.rs",
2022            "crates/api",
2023            "static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!();",
2024        );
2025        let configuration = extract_data_artifact(
2026            "crates/api/sqlx.toml",
2027            "[migrate]\nmigrations-dir = \"db/migrations\"\n",
2028        )
2029        .expect("SQLx configuration should parse");
2030        let migration = extract_data_artifact(
2031            "crates/api/db/migrations/0001_users.sql",
2032            "CREATE TABLE users (id INTEGER);",
2033        )
2034        .expect("migration should parse");
2035
2036        let facts = documents_to_graph(
2037            &[
2038                (&repo, "crates/api/src/lib.rs", "source-hash", &source),
2039                (
2040                    &repo,
2041                    "crates/api/sqlx.toml",
2042                    "configuration-hash",
2043                    &configuration,
2044                ),
2045                (
2046                    &repo,
2047                    "crates/api/db/migrations/0001_users.sql",
2048                    "migration-hash",
2049                    &migration,
2050                ),
2051            ],
2052            &[],
2053            &[],
2054            &[],
2055            &[],
2056            &[],
2057        );
2058        let source_artifact = facts
2059            .nodes
2060            .iter()
2061            .find(|node| node.kind == NodeKind::Artifact && node.label == "crates/api/src/lib.rs")
2062            .expect("source artifact");
2063        let migration_artifact = facts
2064            .nodes
2065            .iter()
2066            .find(|node| {
2067                node.kind == NodeKind::Artifact
2068                    && node.label == "crates/api/db/migrations/0001_users.sql"
2069            })
2070            .expect("migration artifact");
2071
2072        assert!(facts.edges.iter().any(|edge| {
2073            edge.source == source_artifact.id
2074                && edge.target == migration_artifact.id
2075                && edge.kind == EdgeKind::Consumes
2076        }));
2077    }
2078
2079    #[test]
2080    fn reversible_migrations_keep_empty_artifacts_and_explicit_lineage() {
2081        let repo = RepoId::new("repo:migrations");
2082        let first_up = extract_data_artifact(
2083            "migrations/0001_users.up.sql",
2084            "CREATE TABLE users (id INTEGER);",
2085        )
2086        .expect("up migration should parse");
2087        let first_down =
2088            extract_data_artifact("migrations/0001_users.down.sql", "DROP TABLE users;")
2089                .expect("down migration should parse");
2090        let second_up = extract_data_artifact(
2091            "migrations/0002_accounts.up.sql",
2092            "CREATE TABLE accounts (id INTEGER);",
2093        )
2094        .expect("second migration should parse");
2095
2096        let facts = documents_to_graph(
2097            &[
2098                (&repo, "migrations/0001_users.up.sql", "first-up", &first_up),
2099                (
2100                    &repo,
2101                    "migrations/0001_users.down.sql",
2102                    "first-down",
2103                    &first_down,
2104                ),
2105                (
2106                    &repo,
2107                    "migrations/0002_accounts.up.sql",
2108                    "second-up",
2109                    &second_up,
2110                ),
2111            ],
2112            &[],
2113            &[],
2114            &[],
2115            &[],
2116            &[],
2117        );
2118        let artifact = |label: &str| {
2119            facts
2120                .nodes
2121                .iter()
2122                .find(|node| node.kind == NodeKind::Artifact && node.label == label)
2123                .unwrap_or_else(|| panic!("missing migration artifact {label}"))
2124        };
2125        let first_up = artifact("migrations/0001_users.up.sql");
2126        let first_down = artifact("migrations/0001_users.down.sql");
2127        let second_up = artifact("migrations/0002_accounts.up.sql");
2128
2129        assert!(facts.edges.iter().any(|edge| {
2130            edge.source == first_down.id
2131                && edge.target == first_up.id
2132                && edge.kind == EdgeKind::Reverts
2133        }));
2134        assert!(facts.edges.iter().any(|edge| {
2135            edge.source == first_up.id
2136                && edge.target == second_up.id
2137                && edge.kind == EdgeKind::Precedes
2138        }));
2139    }
2140
2141    #[test]
2142    fn repository_deploys_unit_that_provides_exact_service() {
2143        let repo = RepoId::new("repo:api");
2144        let document = InfrastructureDocument {
2145            artifact_kind: InfrastructureArtifactKind::DockerCompose,
2146            source_path: "compose.yaml".to_owned(),
2147            deployment_units: vec![DeploymentUnit {
2148                kind: DeploymentKind::DockerComposeService,
2149                name: "api".to_owned(),
2150                namespace: None,
2151                images: Vec::new(),
2152                ports: Vec::new(),
2153                environment_keys: Vec::new(),
2154                dependencies: Vec::new(),
2155                service_names: vec!["api".to_owned()],
2156                host_aliases: Vec::new(),
2157                selectors: Vec::new(),
2158                evidence: vec![InfrastructureEvidence {
2159                    kind: InfrastructureEvidenceKind::Declaration,
2160                    line: Some(2),
2161                }],
2162            }],
2163            resources: Vec::new(),
2164            environment_keys: Vec::new(),
2165            warnings: Vec::new(),
2166            incomplete: false,
2167        };
2168
2169        let facts = documents_to_graph(
2170            &[],
2171            &[(&repo, "compose.yaml", "compose-hash", &document)],
2172            &[],
2173            &[],
2174            &[],
2175            &[],
2176        );
2177
2178        assert!(
2179            [EdgeKind::Deploys, EdgeKind::Provides]
2180                .into_iter()
2181                .all(|kind| facts.edges.iter().any(|edge| edge.kind == kind))
2182        );
2183    }
2184
2185    #[test]
2186    fn explicit_catalog_references_document_service_and_owner() {
2187        let repo = RepoId::new("repo:billing");
2188        let document = extract_service_catalog(
2189            "catalog.yaml",
2190            "services:\n  - name: billing\n    owner: '@payments'\n",
2191        )
2192        .expect("valid service catalog");
2193
2194        let facts = documents_to_graph(
2195            &[],
2196            &[],
2197            &[(&repo, "catalog.yaml", "catalog-hash", &document)],
2198            &[],
2199            &[],
2200            &[],
2201        );
2202
2203        assert!(
2204            facts
2205                .edges
2206                .iter()
2207                .filter(|edge| edge.kind == EdgeKind::Documents)
2208                .any(|edge| {
2209                    facts.nodes.iter().any(|node| {
2210                        node.id == edge.target
2211                            && node.kind == NodeKind::Service
2212                            && node.label == "billing"
2213                    })
2214                })
2215                && facts
2216                    .edges
2217                    .iter()
2218                    .filter(|edge| edge.kind == EdgeKind::Documents)
2219                    .any(|edge| {
2220                        facts.nodes.iter().any(|node| {
2221                            node.id == edge.target
2222                                && node.kind == NodeKind::Owner
2223                                && node.label == "@payments"
2224                        })
2225                    })
2226        );
2227    }
2228
2229    #[test]
2230    fn explicit_generated_by_link_creates_cross_repository_dependency() {
2231        let platform = RepoId::new("repo:platform");
2232        let transpiler = RepoId::new("repo:transpiler");
2233        let document = extract_markdown(
2234            "README.md",
2235            "Generated by [hugint-transpiler](https://github.com/huginthub/hugint-transpiler).\n",
2236        )
2237        .expect("valid Markdown");
2238
2239        let facts = documents_to_graph(
2240            &[],
2241            &[],
2242            &[(&platform, "README.md", "readme-hash", &document)],
2243            &[],
2244            &[],
2245            &[
2246                (
2247                    "hugint-platform",
2248                    &platform,
2249                    Some("github.com/huginthub/hugint-platform"),
2250                ),
2251                (
2252                    "hugint-transpiler",
2253                    &transpiler,
2254                    Some("github.com/huginthub/hugint-transpiler"),
2255                ),
2256            ],
2257        );
2258
2259        let relation = facts
2260            .edges
2261            .iter()
2262            .find(|edge| {
2263                edge.kind == EdgeKind::DependsOnRepository
2264                    && facts.nodes.iter().any(|node| {
2265                        node.id == edge.source
2266                            && node.kind == NodeKind::Repository
2267                            && node.repo_id.as_ref() == Some(&platform)
2268                    })
2269                    && facts.nodes.iter().any(|node| {
2270                        node.id == edge.target
2271                            && node.kind == NodeKind::Repository
2272                            && node.repo_id.as_ref() == Some(&transpiler)
2273                    })
2274            })
2275            .expect("cross-repository dependency");
2276        assert_ne!(relation.source, relation.target);
2277    }
2278
2279    #[test]
2280    fn repository_link_with_wrong_owner_does_not_match_alias_basename() {
2281        let platform = RepoId::new("repo:platform");
2282        let payments = RepoId::new("repo:payments");
2283        let document = extract_markdown(
2284            "README.md",
2285            "Generated by [payments](https://github.com/evil-owner/payments).\n",
2286        )
2287        .expect("valid Markdown");
2288
2289        let facts = documents_to_graph(
2290            &[],
2291            &[],
2292            &[(&platform, "README.md", "readme-hash", &document)],
2293            &[],
2294            &[],
2295            &[("payments", &payments, Some("github.com/acme/payments"))],
2296        );
2297
2298        assert!(
2299            facts
2300                .edges
2301                .iter()
2302                .all(|edge| edge.kind != EdgeKind::DependsOnRepository)
2303        );
2304        assert_eq!(facts.coverage_gaps.len(), 1);
2305        assert_eq!(facts.coverage_gaps[0].repo_id, platform);
2306    }
2307
2308    #[test]
2309    fn repository_link_with_wrong_host_does_not_match_remote_slug() {
2310        let platform = RepoId::new("repo:platform");
2311        let payments = RepoId::new("repo:payments");
2312        let document = extract_markdown(
2313            "README.md",
2314            "Generated by [payments](https://github.com/acme/payments).\n",
2315        )
2316        .expect("valid Markdown");
2317
2318        let facts = documents_to_graph(
2319            &[],
2320            &[],
2321            &[(&platform, "README.md", "readme-hash", &document)],
2322            &[],
2323            &[],
2324            &[("payments", &payments, Some("gitlab.com/acme/payments"))],
2325        );
2326
2327        assert!(
2328            facts
2329                .edges
2330                .iter()
2331                .all(|edge| edge.kind != EdgeKind::DependsOnRepository)
2332        );
2333        assert_eq!(facts.coverage_gaps.len(), 1);
2334        assert_eq!(facts.coverage_gaps[0].repo_id, platform);
2335    }
2336
2337    #[test]
2338    fn serialized_graph_never_contains_fixture_secret() {
2339        const FIXTURE_SECRET: &str = "extraction-fixture-secret-5f16";
2340        let repo = RepoId::new("repo:config");
2341        let source = format!("API_TOKEN={FIXTURE_SECRET}\n");
2342        let document = extract_safe_config(".env", &source).expect("valid dotenv");
2343        let facts = documents_to_graph(
2344            &[],
2345            &[],
2346            &[],
2347            &[(&repo, ".env", "config-hash", &document)],
2348            &[],
2349            &[],
2350        );
2351
2352        let serialized = serde_json::to_string(&(&facts.nodes, &facts.edges, &facts.evidence))
2353            .expect("graph facts should serialize");
2354
2355        assert!(!serialized.contains(FIXTURE_SECRET));
2356    }
2357}