1use std::cmp::Ordering;
4use std::collections::{BTreeMap, BTreeSet};
5
6use code_system_graph_model::{
7 CommunityId, CommunitySnapshot, Edge, Evidence, EvidenceId, NativePath, NativePathEncoding, Node, NodeId, NodeKind, RepoFreshness, RepoFreshnessState, RepoId
8};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13use crate::{
14 ChangeSet, ChangeSourceLayer, ChangeValidity, ChangeValidityInput, ChangedFile, ChangedFileStatus, CompatibilityFinding, CompatibilityInput, CompatibilityReport, CompatibilityStatus, ImpactCompatibilityStatus, ImpactContext, ImpactDirection, ImpactError, ImpactOptions, ImpactReport, ImpactRequest, ImpactTarget, RiskLevel, analyze_impact, validate_change_set
15};
16
17pub const CHANGE_ANALYZER_VERSION: &str = "1.0.0";
19
20const MAX_CHANGED_FILES: usize = 100_000;
21const MAX_CHANGED_NODES: usize = 100_000;
22const MAX_IMPACT_TARGETS: usize = 10_000;
23const MAX_DEPTH: usize = 128;
24const MAX_PAGE_LIMIT: usize = 10_000;
25const MAX_PAGE_OFFSET: usize = 1_000_000;
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
29pub struct ChangeAnalysisOptions {
30 pub max_changed_files: usize,
32 pub max_changed_nodes: usize,
34 pub max_impact_targets: usize,
36 pub direction: ImpactDirection,
38 pub max_depth: usize,
40 pub offset: usize,
42 pub limit: usize,
44 pub summary_only: bool,
46}
47
48impl Default for ChangeAnalysisOptions {
49 fn default() -> Self {
50 Self {
51 max_changed_files: 1_000,
52 max_changed_nodes: 10_000,
53 max_impact_targets: 1_000,
54 direction: ImpactDirection::Upstream,
55 max_depth: 8,
56 offset: 0,
57 limit: 100,
58 summary_only: false,
59 }
60 }
61}
62
63#[derive(
65 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
66)]
67#[serde(rename_all = "snake_case")]
68pub enum ChangedPathSide {
69 Old,
71 New,
73}
74
75#[derive(
77 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
78)]
79#[serde(rename_all = "snake_case")]
80pub enum EvidenceMatchKind {
81 HunkIntersection,
83 FilePathFallback,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
89pub struct HunkLineMatch {
90 pub evidence_id: EvidenceId,
92 pub path_side: ChangedPathSide,
94 pub kind: EvidenceMatchKind,
96 pub hunk_index: Option<usize>,
98 pub hunk_start: Option<u32>,
100 pub hunk_end: Option<u32>,
102 pub evidence_start: Option<u32>,
104 pub evidence_end: Option<u32>,
106}
107
108#[derive(
110 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
111)]
112#[serde(rename_all = "snake_case")]
113pub enum MappingCompleteness {
114 Complete,
116 Partial,
118 Unknown,
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
124pub struct ChangedArtifactMapping {
125 pub old_path: Option<NativePath>,
127 pub new_path: Option<NativePath>,
129 pub status: ChangedFileStatus,
131 pub layer: ChangeSourceLayer,
133 pub matched_evidence_ids: Vec<EvidenceId>,
135 pub artifact_node_ids: Vec<NodeId>,
137 pub symbol_ref_node_ids: Vec<NodeId>,
139 pub boundary_node_ids: Vec<NodeId>,
141 pub matches: Vec<HunkLineMatch>,
143 pub completeness: MappingCompleteness,
145 pub gaps: Vec<String>,
147}
148
149#[derive(
151 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
152)]
153#[serde(rename_all = "snake_case")]
154pub enum ChangedEntityRole {
155 Artifact,
157 SymbolRef,
159 Boundary,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
165pub struct ChangedEntity {
166 pub node: Node,
168 pub roles: Vec<ChangedEntityRole>,
170 pub changed_paths: Vec<NativePath>,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
176pub struct ContractCompatibilityInput {
177 pub file_path: Option<String>,
179 pub contract_node_id: NodeId,
181 pub report: Option<CompatibilityReport>,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
187pub struct SemanticContractDelta {
188 pub contract: Node,
190 pub contract_kind: NodeKind,
192 pub status: CompatibilityStatus,
194 pub before_fingerprint: Option<String>,
196 pub after_fingerprint: Option<String>,
198 pub findings: Vec<CompatibilityFinding>,
200 pub factors: Vec<String>,
202 pub validations: Vec<String>,
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
208pub struct ChangeAnalysisCoverage {
209 pub complete: bool,
211 pub total_changed_files: usize,
213 pub analyzed_changed_files: usize,
215 pub mapped_changed_files: usize,
217 pub complete_changed_files: usize,
219 pub total_changed_nodes: usize,
221 pub retained_changed_nodes: usize,
223 pub total_impact_targets: usize,
225 pub analyzed_impact_targets: usize,
227 pub truncated: bool,
229 pub gaps: Vec<String>,
231}
232
233#[derive(
235 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
236)]
237#[serde(rename_all = "snake_case")]
238pub enum ChangeConclusion {
239 ImpactDetected,
241 NoSemanticImpactDetected,
243 Unknown,
245}
246
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
249pub struct ChangeAnalysisSummary {
250 pub conclusion: ChangeConclusion,
252 pub highest_risk: RiskLevel,
254 pub changed_entities: usize,
256 pub changed_contracts: usize,
258 pub impact_reports: usize,
260}
261
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
264pub struct ChangeImpactReport {
265 pub analyzer_version: String,
267 pub analyzer_fingerprint: String,
269 pub change_set: ChangeSet,
271 pub mappings: Vec<ChangedArtifactMapping>,
273 pub changed_entities: Vec<ChangedEntity>,
275 pub contract_deltas: Vec<SemanticContractDelta>,
277 pub impacts: Vec<ImpactReport>,
279 pub touched_repositories: Vec<RepoId>,
281 pub touched_services: Vec<Node>,
283 pub touched_communities: Vec<CommunityId>,
285 pub touched_contracts: Vec<Node>,
287 pub coverage: ChangeAnalysisCoverage,
289 pub summary: ChangeAnalysisSummary,
291}
292
293#[derive(Debug, Error)]
295pub enum ChangeAnalysisError {
296 #[error("change-analysis bounds are outside supported limits")]
298 InvalidBounds,
299 #[error("change-analysis inputs could not be fingerprinted: {0}")]
301 Fingerprint(#[source] serde_json::Error),
302 #[error("impact analysis failed for changed boundary `{target}`: {source}")]
304 Impact {
305 target: String,
307 #[source]
309 source: ImpactError,
310 },
311}
312
313#[derive(Debug)]
314struct MappingWork {
315 mapping: ChangedArtifactMapping,
316 representable_paths: BTreeSet<String>,
317}
318
319#[derive(Debug, Default)]
320struct EntityWork {
321 roles: BTreeSet<ChangedEntityRole>,
322 paths: BTreeSet<NativePath>,
323}
324
325#[expect(
335 clippy::too_many_arguments,
336 reason = "the pure boundary keeps every immutable analysis input explicit"
337)]
338#[expect(
339 clippy::too_many_lines,
340 reason = "the orchestration remains linear so coverage degradation is auditable"
341)]
342#[must_use = "change reports and validation errors must be handled"]
343pub fn analyze_changes(
344 change_set: &ChangeSet,
345 nodes: &[Node],
346 edges: &[Edge],
347 evidence: &[Evidence],
348 community: Option<&CommunitySnapshot>,
349 freshness: &[RepoFreshness],
350 compatibility: &[ContractCompatibilityInput],
351 options: &ChangeAnalysisOptions,
352) -> Result<ChangeImpactReport, ChangeAnalysisError> {
353 validate_options(options)?;
354 let analyzer_fingerprint = analyzer_fingerprint(
355 change_set,
356 nodes,
357 edges,
358 evidence,
359 community,
360 freshness,
361 compatibility,
362 options,
363 )?;
364
365 let node_index = nodes
366 .iter()
367 .map(|node| (node.id.clone(), node))
368 .collect::<BTreeMap<_, _>>();
369 let evidence_index = evidence
370 .iter()
371 .map(|item| (item.id.clone(), item))
372 .collect::<BTreeMap<_, _>>();
373 let mut ordered_files = change_set.files.iter().collect::<Vec<_>>();
374 ordered_files.sort_by(|left, right| changed_file_order(left, right));
375 let total_changed_files = ordered_files.len();
376 ordered_files.truncate(options.max_changed_files);
377
378 let mut mapping_work = ordered_files
379 .into_iter()
380 .map(|file| {
381 map_changed_file(
382 file,
383 &change_set.repo_id,
384 edges,
385 &node_index,
386 &evidence_index,
387 )
388 })
389 .collect::<Vec<_>>();
390 mapping_work.sort_by(|left, right| mapping_order(&left.mapping, &right.mapping));
391
392 let mut coverage_gaps = mapping_work
393 .iter()
394 .flat_map(|work| work.mapping.gaps.iter().cloned())
395 .collect::<BTreeSet<_>>();
396 let mut truncated = total_changed_files > mapping_work.len();
397 if truncated {
398 coverage_gaps.insert(format!(
399 "changed files truncated at {}; {} files were present",
400 options.max_changed_files, total_changed_files
401 ));
402 }
403
404 let all_changed_node_ids = mapping_work
405 .iter()
406 .flat_map(|work| {
407 work.mapping
408 .artifact_node_ids
409 .iter()
410 .chain(&work.mapping.symbol_ref_node_ids)
411 .chain(&work.mapping.boundary_node_ids)
412 .cloned()
413 })
414 .collect::<BTreeSet<_>>();
415 let total_changed_nodes = all_changed_node_ids.len();
416 let retained_node_ids = all_changed_node_ids
417 .iter()
418 .take(options.max_changed_nodes)
419 .cloned()
420 .collect::<BTreeSet<_>>();
421 if total_changed_nodes > retained_node_ids.len() {
422 truncated = true;
423 coverage_gaps.insert(format!(
424 "changed graph nodes truncated at {}; {} nodes were mapped",
425 options.max_changed_nodes, total_changed_nodes
426 ));
427 for work in &mut mapping_work {
428 retain_node_ids(&mut work.mapping, &retained_node_ids);
429 degrade_mapping(
430 &mut work.mapping,
431 "mapped node identities were truncated by the configured node bound",
432 );
433 }
434 }
435
436 let mut entities = build_changed_entities(&mapping_work, &node_index);
437 let changed_entity_count = entities.len();
438 let changed_entities = if options.summary_only {
439 Vec::new()
440 } else {
441 entities
442 .drain(..)
443 .skip(options.offset.min(changed_entity_count))
444 .take(options.limit)
445 .collect()
446 };
447
448 let changed_boundary_ids = mapping_work
449 .iter()
450 .flat_map(|work| work.mapping.boundary_node_ids.iter().cloned())
451 .collect::<BTreeSet<_>>();
452 let total_impact_targets = changed_boundary_ids.len();
453 let impact_target_ids = changed_boundary_ids
454 .iter()
455 .take(options.max_impact_targets)
456 .cloned()
457 .collect::<Vec<_>>();
458 if total_impact_targets > impact_target_ids.len() {
459 truncated = true;
460 coverage_gaps.insert(format!(
461 "impact targets truncated at {}; {} exact changed boundaries were mapped",
462 options.max_impact_targets, total_impact_targets
463 ));
464 }
465
466 let contract_deltas = build_contract_deltas(
467 &changed_boundary_ids,
468 &mapping_work,
469 &node_index,
470 compatibility,
471 );
472 if contract_deltas.iter().any(|delta| {
473 matches!(
474 delta.status,
475 CompatibilityStatus::Unknown | CompatibilityStatus::Incomparable
476 )
477 }) {
478 coverage_gaps.insert(
479 "one or more changed contracts lack complete before/after compatibility data"
480 .to_owned(),
481 );
482 }
483
484 let mapped_changed_files = mapping_work
485 .iter()
486 .filter(|work| !work.mapping.matched_evidence_ids.is_empty())
487 .count();
488 let complete_changed_files = mapping_work
489 .iter()
490 .filter(|work| work.mapping.completeness == MappingCompleteness::Complete)
491 .count();
492 let provisional_complete = !truncated
493 && mapping_work.len() == total_changed_files
494 && complete_changed_files == total_changed_files
495 && !contract_deltas.iter().any(|delta| {
496 matches!(
497 delta.status,
498 CompatibilityStatus::Unknown | CompatibilityStatus::Incomparable
499 )
500 });
501
502 let normalized_freshness = freshness_for_change_set(change_set, freshness);
503 let impact_compatibility = contract_deltas
504 .iter()
505 .map(impact_compatibility_input)
506 .collect::<Vec<_>>();
507 let service_memberships = derive_service_memberships(nodes, edges);
508 let impact_context = ImpactContext {
509 nodes: nodes.to_vec(),
510 edges: edges.to_vec(),
511 communities: community.cloned(),
512 freshness: normalized_freshness,
513 compatibility: impact_compatibility,
514 local_enrichment: Vec::new(),
515 public_contracts: changed_boundary_ids.iter().cloned().collect(),
516 criticality: Vec::new(),
517 centrality: BTreeMap::new(),
518 service_memberships,
519 environments: Vec::new(),
520 recommended_commands: Vec::new(),
521 graph_complete: provisional_complete,
522 coverage_gaps: coverage_gaps.iter().cloned().collect(),
523 };
524 let mut impacts = Vec::with_capacity(impact_target_ids.len());
525 for target in &impact_target_ids {
526 let request = ImpactRequest {
527 target: ImpactTarget::NodeId {
528 node_id: target.clone(),
529 },
530 direction: options.direction,
531 options: ImpactOptions {
532 max_depth: options.max_depth,
533 node_limit: options.max_changed_nodes,
534 edge_limit: 50_000,
535 confirmed_confidence: 0.8,
536 offset: 0,
537 limit: options.limit,
538 summary_only: options.summary_only,
539 include_depth_buckets: true,
540 },
541 };
542 impacts.push(analyze_impact(&request, &impact_context).map_err(|source| {
543 ChangeAnalysisError::Impact {
544 target: target.as_str().to_owned(),
545 source,
546 }
547 })?);
548 }
549 impacts.sort_by(|left, right| left.target.node.id.cmp(&right.target.node.id));
550
551 for impact in &impacts {
552 coverage_gaps.extend(impact.coverage.gaps.iter().cloned());
553 if impact.truncation.is_some() || !impact.coverage.sufficient_for_score {
554 truncated |= impact.truncation.is_some();
555 }
556 }
557 let complete = provisional_complete
558 && impacts
559 .iter()
560 .all(|impact| impact.coverage.sufficient_for_score && impact.truncation.is_none());
561 let coverage = ChangeAnalysisCoverage {
562 complete,
563 total_changed_files,
564 analyzed_changed_files: mapping_work.len(),
565 mapped_changed_files,
566 complete_changed_files,
567 total_changed_nodes,
568 retained_changed_nodes: retained_node_ids.len(),
569 total_impact_targets,
570 analyzed_impact_targets: impacts.len(),
571 truncated,
572 gaps: coverage_gaps.into_iter().collect(),
573 };
574
575 let mappings = mapping_work
576 .into_iter()
577 .map(|work| work.mapping)
578 .collect::<Vec<_>>();
579 let (touched_repositories, touched_services, touched_communities, touched_contracts) =
580 aggregate_touched(
581 change_set,
582 &retained_node_ids,
583 &node_index,
584 community,
585 &contract_deltas,
586 &impacts,
587 );
588 let summary = summarize(
589 &coverage,
590 changed_entity_count,
591 contract_deltas.len(),
592 &impacts,
593 );
594
595 Ok(ChangeImpactReport {
596 analyzer_version: CHANGE_ANALYZER_VERSION.to_owned(),
597 analyzer_fingerprint,
598 change_set: change_set.clone(),
599 mappings,
600 changed_entities,
601 contract_deltas,
602 impacts,
603 touched_repositories,
604 touched_services,
605 touched_communities,
606 touched_contracts,
607 coverage,
608 summary,
609 })
610}
611
612#[must_use]
614pub fn validate_change_analysis(
615 report: &ChangeImpactReport,
616 current: &ChangeValidityInput,
617) -> ChangeValidity {
618 validate_change_set(&report.change_set, current)
619}
620
621fn validate_options(options: &ChangeAnalysisOptions) -> Result<(), ChangeAnalysisError> {
622 if options.max_changed_files == 0
623 || options.max_changed_files > MAX_CHANGED_FILES
624 || options.max_changed_nodes == 0
625 || options.max_changed_nodes > MAX_CHANGED_NODES
626 || options.max_impact_targets == 0
627 || options.max_impact_targets > MAX_IMPACT_TARGETS
628 || options.max_depth == 0
629 || options.max_depth > MAX_DEPTH
630 || options.limit == 0
631 || options.limit > MAX_PAGE_LIMIT
632 || options.offset > MAX_PAGE_OFFSET
633 {
634 return Err(ChangeAnalysisError::InvalidBounds);
635 }
636 Ok(())
637}
638
639#[expect(
640 clippy::too_many_arguments,
641 reason = "the fingerprint intentionally covers every pure analyzer input"
642)]
643fn analyzer_fingerprint(
644 change_set: &ChangeSet,
645 nodes: &[Node],
646 edges: &[Edge],
647 evidence: &[Evidence],
648 community: Option<&CommunitySnapshot>,
649 freshness: &[RepoFreshness],
650 compatibility: &[ContractCompatibilityInput],
651 options: &ChangeAnalysisOptions,
652) -> Result<String, ChangeAnalysisError> {
653 #[derive(Serialize)]
654 struct Material<'a> {
655 analyzer_version: &'static str,
656 change_set: &'a ChangeSet,
657 nodes: Vec<&'a Node>,
658 edges: Vec<&'a Edge>,
659 evidence: Vec<&'a Evidence>,
660 community: Option<&'a CommunitySnapshot>,
661 freshness: Vec<&'a RepoFreshness>,
662 compatibility: Vec<&'a ContractCompatibilityInput>,
663 options: &'a ChangeAnalysisOptions,
664 }
665
666 let mut ordered_nodes = nodes.iter().collect::<Vec<_>>();
667 ordered_nodes.sort_by_key(|node| &node.id);
668 let mut ordered_edges = edges.iter().collect::<Vec<_>>();
669 ordered_edges.sort_by_key(|edge| &edge.id);
670 let mut ordered_evidence = evidence.iter().collect::<Vec<_>>();
671 ordered_evidence.sort_by_key(|item| &item.id);
672 let mut ordered_freshness = freshness.iter().collect::<Vec<_>>();
673 ordered_freshness.sort_by_key(|item| (&item.repo_id, &item.checkout_id));
674 let mut ordered_compatibility = compatibility.iter().collect::<Vec<_>>();
675 ordered_compatibility.sort_by(|left, right| {
676 (
677 &left.contract_node_id,
678 left.file_path.as_deref().unwrap_or_default(),
679 )
680 .cmp(&(
681 &right.contract_node_id,
682 right.file_path.as_deref().unwrap_or_default(),
683 ))
684 });
685 let encoded = serde_json::to_vec(&Material {
686 analyzer_version: CHANGE_ANALYZER_VERSION,
687 change_set,
688 nodes: ordered_nodes,
689 edges: ordered_edges,
690 evidence: ordered_evidence,
691 community,
692 freshness: ordered_freshness,
693 compatibility: ordered_compatibility,
694 options,
695 })
696 .map_err(ChangeAnalysisError::Fingerprint)?;
697 Ok(blake3::hash(&encoded).to_hex().to_string())
698}
699
700fn changed_file_order(left: &ChangedFile, right: &ChangedFile) -> Ordering {
701 (
702 left.source,
703 left.status,
704 left.old_path.as_ref(),
705 left.new_path.as_ref(),
706 )
707 .cmp(&(
708 right.source,
709 right.status,
710 right.old_path.as_ref(),
711 right.new_path.as_ref(),
712 ))
713}
714
715fn mapping_order(left: &ChangedArtifactMapping, right: &ChangedArtifactMapping) -> Ordering {
716 (
717 left.layer,
718 left.status,
719 left.old_path.as_ref(),
720 left.new_path.as_ref(),
721 )
722 .cmp(&(
723 right.layer,
724 right.status,
725 right.old_path.as_ref(),
726 right.new_path.as_ref(),
727 ))
728}
729
730#[expect(
731 clippy::too_many_lines,
732 reason = "old/new path, line, and graph evidence decisions remain auditable together"
733)]
734fn map_changed_file(
735 file: &ChangedFile,
736 repo_id: &RepoId,
737 edges: &[Edge],
738 nodes: &BTreeMap<NodeId, &Node>,
739 evidence: &BTreeMap<EvidenceId, &Evidence>,
740) -> MappingWork {
741 let mut gaps = BTreeSet::new();
742 let mut matched_evidence = BTreeSet::new();
743 let mut explanations = BTreeSet::new();
744 let mut representable_paths = BTreeSet::new();
745 let sides = relevant_sides(file);
746 let mut unrepresentable = false;
747 let mut matched_sides = BTreeSet::new();
748 let mut line_match = false;
749 let mut fallback_match = false;
750
751 for (side, path) in sides {
752 let Some(path_text) = native_path_text(path) else {
753 unrepresentable = true;
754 gaps.insert(format!(
755 "{} path cannot be represented as Unicode for evidence matching",
756 side_name(side)
757 ));
758 continue;
759 };
760 representable_paths.insert(path_text.clone());
761 for item in evidence.values().copied() {
762 if item.repo_id.as_ref() != Some(repo_id)
763 || item
764 .file_path
765 .as_deref()
766 .is_none_or(|candidate| !same_evidence_path(candidate, &path_text))
767 {
768 continue;
769 }
770 let ranges = hunk_ranges(file, side);
771 let evidence_range = evidence_range(item);
772 let intersections = evidence_range.map_or_else(Vec::new, |range| {
773 ranges
774 .iter()
775 .filter(|(_, hunk_range)| ranges_intersect(*hunk_range, range))
776 .copied()
777 .collect()
778 });
779 if !file.binary
780 && file.status != ChangedFileStatus::Untracked
781 && !intersections.is_empty()
782 {
783 line_match = true;
784 matched_sides.insert(side);
785 matched_evidence.insert(item.id.clone());
786 for (hunk_index, range) in intersections {
787 explanations.insert(match_explanation(
788 item,
789 side,
790 EvidenceMatchKind::HunkIntersection,
791 Some(hunk_index),
792 Some(range),
793 ));
794 }
795 } else if file.binary
796 || file.status == ChangedFileStatus::Untracked
797 || evidence_range.is_none()
798 || ranges.is_empty()
799 {
800 fallback_match = true;
801 matched_sides.insert(side);
802 matched_evidence.insert(item.id.clone());
803 explanations.insert(match_explanation(
804 item,
805 side,
806 EvidenceMatchKind::FilePathFallback,
807 None,
808 None,
809 ));
810 }
811 }
812 }
813
814 if file.binary {
815 gaps.insert("binary change has no line-level semantic evidence".to_owned());
816 }
817 if file.status == ChangedFileStatus::Untracked {
818 gaps.insert("untracked file body and line changes were not collected".to_owned());
819 }
820 if matched_evidence.is_empty() {
821 gaps.insert("no persisted evidence matched the changed path and hunk ranges".to_owned());
822 }
823 if fallback_match {
824 gaps.insert("one or more evidence records matched only at file-path level".to_owned());
825 }
826 if matched_sides.len() < expected_side_count(file) {
827 gaps.insert(
828 "not every required old/new path neighborhood matched persisted evidence".to_owned(),
829 );
830 }
831
832 let (artifact_node_ids, symbol_ref_node_ids, boundary_node_ids) =
833 nodes_for_evidence(&matched_evidence, edges, nodes);
834 if !matched_evidence.is_empty()
835 && artifact_node_ids.is_empty()
836 && symbol_ref_node_ids.is_empty()
837 && boundary_node_ids.is_empty()
838 {
839 gaps.insert(
840 "matched evidence is not attached to a supported semantic graph node".to_owned(),
841 );
842 }
843 if boundary_node_ids.is_empty() {
844 gaps.insert(
845 "no exact changed boundary node was established for impact propagation".to_owned(),
846 );
847 }
848
849 let completeness = if unrepresentable || matched_evidence.is_empty() {
850 MappingCompleteness::Unknown
851 } else if !file.binary
852 && file.status != ChangedFileStatus::Untracked
853 && line_match
854 && !fallback_match
855 && matched_sides.len() == expected_side_count(file)
856 && !boundary_node_ids.is_empty()
857 {
858 MappingCompleteness::Complete
859 } else {
860 MappingCompleteness::Partial
861 };
862
863 MappingWork {
864 mapping: ChangedArtifactMapping {
865 old_path: file.old_path.clone(),
866 new_path: file.new_path.clone(),
867 status: file.status,
868 layer: file.source,
869 matched_evidence_ids: matched_evidence.into_iter().collect(),
870 artifact_node_ids,
871 symbol_ref_node_ids,
872 boundary_node_ids,
873 matches: explanations.into_iter().collect(),
874 completeness,
875 gaps: gaps.into_iter().collect(),
876 },
877 representable_paths,
878 }
879}
880
881fn relevant_sides(file: &ChangedFile) -> Vec<(ChangedPathSide, &NativePath)> {
882 match file.status {
883 ChangedFileStatus::Deleted => file
884 .old_path
885 .as_ref()
886 .map(|path| vec![(ChangedPathSide::Old, path)])
887 .unwrap_or_default(),
888 ChangedFileStatus::Renamed => {
889 let mut sides = Vec::with_capacity(2);
890 if let Some(path) = &file.old_path {
891 sides.push((ChangedPathSide::Old, path));
892 }
893 if let Some(path) = &file.new_path {
894 sides.push((ChangedPathSide::New, path));
895 }
896 sides
897 }
898 _ => file
899 .new_path
900 .as_ref()
901 .or(file.old_path.as_ref())
902 .map(|path| vec![(ChangedPathSide::New, path)])
903 .unwrap_or_default(),
904 }
905}
906
907fn expected_side_count(file: &ChangedFile) -> usize {
908 match file.status {
909 ChangedFileStatus::Renamed => {
910 usize::from(file.old_path.is_some()) + usize::from(file.new_path.is_some())
911 }
912 _ => usize::from(file.old_path.is_some() || file.new_path.is_some()),
913 }
914}
915
916fn side_name(side: ChangedPathSide) -> &'static str {
917 match side {
918 ChangedPathSide::Old => "old",
919 ChangedPathSide::New => "new",
920 }
921}
922
923fn native_path_text(path: &NativePath) -> Option<String> {
924 match path.encoding {
925 NativePathEncoding::UnixBytes | NativePathEncoding::Utf8 => {
926 std::str::from_utf8(&path.bytes).ok().map(ToOwned::to_owned)
927 }
928 NativePathEncoding::WindowsWide => {
929 let (chunks, remainder) = path.bytes.as_chunks::<2>();
930 if !remainder.is_empty() {
931 return None;
932 }
933 let units = chunks.iter().map(|chunk| u16::from_le_bytes(*chunk));
934 char::decode_utf16(units)
935 .collect::<Result<String, _>>()
936 .ok()
937 }
938 }
939}
940
941fn same_evidence_path(left: &str, right: &str) -> bool {
942 left == right
943}
944
945fn hunk_ranges(file: &ChangedFile, side: ChangedPathSide) -> Vec<(usize, (u32, u32))> {
946 file.hunks
947 .iter()
948 .enumerate()
949 .filter_map(|(index, hunk)| {
950 let (start, count) = match side {
951 ChangedPathSide::Old => (hunk.old_start, hunk.old_count),
952 ChangedPathSide::New => (hunk.new_start, hunk.new_count),
953 };
954 inclusive_range(start, count).map(|range| (index, range))
955 })
956 .collect()
957}
958
959fn inclusive_range(start: u32, count: u32) -> Option<(u32, u32)> {
960 (count > 0).then(|| (start, start.saturating_add(count - 1)))
961}
962
963fn evidence_range(evidence: &Evidence) -> Option<(u32, u32)> {
964 match (evidence.start_line, evidence.end_line) {
965 (Some(start), Some(end)) if start <= end => Some((start, end)),
966 _ => None,
967 }
968}
969
970fn ranges_intersect(left: (u32, u32), right: (u32, u32)) -> bool {
971 left.0 <= right.1 && right.0 <= left.1
972}
973
974fn match_explanation(
975 evidence: &Evidence,
976 path_side: ChangedPathSide,
977 kind: EvidenceMatchKind,
978 hunk_index: Option<usize>,
979 hunk_range: Option<(u32, u32)>,
980) -> HunkLineMatch {
981 HunkLineMatch {
982 evidence_id: evidence.id.clone(),
983 path_side,
984 kind,
985 hunk_index,
986 hunk_start: hunk_range.map(|range| range.0),
987 hunk_end: hunk_range.map(|range| range.1),
988 evidence_start: evidence.start_line,
989 evidence_end: evidence.end_line,
990 }
991}
992
993impl PartialOrd for HunkLineMatch {
994 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
995 Some(self.cmp(other))
996 }
997}
998
999impl Ord for HunkLineMatch {
1000 fn cmp(&self, other: &Self) -> Ordering {
1001 (
1002 &self.evidence_id,
1003 self.path_side,
1004 self.kind,
1005 self.hunk_index,
1006 self.hunk_start,
1007 self.hunk_end,
1008 self.evidence_start,
1009 self.evidence_end,
1010 )
1011 .cmp(&(
1012 &other.evidence_id,
1013 other.path_side,
1014 other.kind,
1015 other.hunk_index,
1016 other.hunk_start,
1017 other.hunk_end,
1018 other.evidence_start,
1019 other.evidence_end,
1020 ))
1021 }
1022}
1023
1024fn nodes_for_evidence(
1025 evidence_ids: &BTreeSet<EvidenceId>,
1026 edges: &[Edge],
1027 nodes: &BTreeMap<NodeId, &Node>,
1028) -> (Vec<NodeId>, Vec<NodeId>, Vec<NodeId>) {
1029 let mut artifact = BTreeSet::new();
1030 let mut symbol = BTreeSet::new();
1031 let mut boundary = BTreeSet::new();
1032 for edge in edges {
1033 if !edge.evidence.iter().any(|id| evidence_ids.contains(id)) {
1034 continue;
1035 }
1036 for id in [&edge.source, &edge.target] {
1037 let Some(node) = nodes.get(id).copied() else {
1038 continue;
1039 };
1040 match node.kind {
1041 NodeKind::Artifact => {
1042 artifact.insert(id.clone());
1043 }
1044 NodeKind::SymbolRef => {
1045 symbol.insert(id.clone());
1046 }
1047 kind if is_boundary_kind(kind) => {
1048 boundary.insert(id.clone());
1049 }
1050 _ => {}
1051 }
1052 }
1053 }
1054 (
1055 artifact.into_iter().collect(),
1056 symbol.into_iter().collect(),
1057 boundary.into_iter().collect(),
1058 )
1059}
1060
1061fn is_boundary_kind(kind: NodeKind) -> bool {
1062 matches!(
1063 kind,
1064 NodeKind::Package
1065 | NodeKind::HttpOperation
1066 | NodeKind::GraphqlOperation
1067 | NodeKind::RpcMethod
1068 | NodeKind::EventChannel
1069 | NodeKind::EventSchema
1070 | NodeKind::Database
1071 | NodeKind::DatabaseTable
1072 | NodeKind::DatabaseColumn
1073 | NodeKind::ConfigKey
1074 )
1075}
1076
1077fn retain_node_ids(mapping: &mut ChangedArtifactMapping, retained: &BTreeSet<NodeId>) {
1078 mapping.artifact_node_ids.retain(|id| retained.contains(id));
1079 mapping
1080 .symbol_ref_node_ids
1081 .retain(|id| retained.contains(id));
1082 mapping.boundary_node_ids.retain(|id| retained.contains(id));
1083}
1084
1085fn degrade_mapping(mapping: &mut ChangedArtifactMapping, gap: &str) {
1086 mapping.completeness = MappingCompleteness::Partial;
1087 mapping.gaps.push(gap.to_owned());
1088 mapping.gaps.sort();
1089 mapping.gaps.dedup();
1090}
1091
1092fn build_changed_entities(
1093 mappings: &[MappingWork],
1094 nodes: &BTreeMap<NodeId, &Node>,
1095) -> Vec<ChangedEntity> {
1096 let mut work = BTreeMap::<NodeId, EntityWork>::new();
1097 for mapping in mappings {
1098 for (role, ids) in [
1099 (
1100 ChangedEntityRole::Artifact,
1101 &mapping.mapping.artifact_node_ids,
1102 ),
1103 (
1104 ChangedEntityRole::SymbolRef,
1105 &mapping.mapping.symbol_ref_node_ids,
1106 ),
1107 (
1108 ChangedEntityRole::Boundary,
1109 &mapping.mapping.boundary_node_ids,
1110 ),
1111 ] {
1112 for id in ids {
1113 let entity = work.entry(id.clone()).or_default();
1114 entity.roles.insert(role);
1115 entity
1116 .paths
1117 .extend(mapping.mapping.old_path.iter().cloned());
1118 entity
1119 .paths
1120 .extend(mapping.mapping.new_path.iter().cloned());
1121 }
1122 }
1123 }
1124 work.into_iter()
1125 .filter_map(|(id, work)| {
1126 nodes.get(&id).map(|node| ChangedEntity {
1127 node: (*node).clone(),
1128 roles: work.roles.into_iter().collect(),
1129 changed_paths: work.paths.into_iter().collect(),
1130 })
1131 })
1132 .collect()
1133}
1134
1135fn build_contract_deltas(
1136 contract_ids: &BTreeSet<NodeId>,
1137 mappings: &[MappingWork],
1138 nodes: &BTreeMap<NodeId, &Node>,
1139 inputs: &[ContractCompatibilityInput],
1140) -> Vec<SemanticContractDelta> {
1141 contract_ids
1142 .iter()
1143 .filter_map(|contract_id| {
1144 let contract = nodes.get(contract_id).copied()?;
1145 let paths = mappings
1146 .iter()
1147 .filter(|work| work.mapping.boundary_node_ids.contains(contract_id))
1148 .flat_map(|work| work.representable_paths.iter().cloned())
1149 .collect::<BTreeSet<_>>();
1150 let matching = inputs
1151 .iter()
1152 .filter(|input| {
1153 input.contract_node_id == *contract_id
1154 && input.file_path.as_ref().is_none_or(|path| {
1155 paths
1156 .iter()
1157 .any(|candidate| same_evidence_path(candidate, path))
1158 })
1159 })
1160 .collect::<Vec<_>>();
1161 Some(merge_contract_delta(contract, &matching))
1162 })
1163 .collect()
1164}
1165
1166fn merge_contract_delta(
1167 contract: &Node,
1168 inputs: &[&ContractCompatibilityInput],
1169) -> SemanticContractDelta {
1170 let reports = inputs
1171 .iter()
1172 .filter_map(|input| input.report.as_ref())
1173 .collect::<Vec<_>>();
1174 let mut status = reports
1175 .iter()
1176 .map(|report| report.status)
1177 .max_by_key(|value| compatibility_severity(*value))
1178 .unwrap_or(CompatibilityStatus::Unknown);
1179 let before = unique_fingerprint(
1180 reports
1181 .iter()
1182 .map(|report| report.before_fingerprint.as_str()),
1183 );
1184 let after = unique_fingerprint(
1185 reports
1186 .iter()
1187 .map(|report| report.after_fingerprint.as_str()),
1188 );
1189 if before.is_none() || after.is_none() {
1190 status = CompatibilityStatus::Unknown;
1191 }
1192 let mut findings = reports
1193 .iter()
1194 .flat_map(|report| report.findings.iter().cloned())
1195 .collect::<Vec<_>>();
1196 findings.sort_by(|left, right| {
1197 (
1198 compatibility_severity(left.status),
1199 &left.code,
1200 &left.path,
1201 &left.factors,
1202 &left.evidence,
1203 )
1204 .cmp(&(
1205 compatibility_severity(right.status),
1206 &right.code,
1207 &right.path,
1208 &right.factors,
1209 &right.evidence,
1210 ))
1211 .reverse()
1212 });
1213 findings.dedup();
1214 let factors = findings
1215 .iter()
1216 .flat_map(|finding| finding.factors.iter().cloned())
1217 .collect::<BTreeSet<_>>()
1218 .into_iter()
1219 .collect();
1220 let validations = findings
1221 .iter()
1222 .flat_map(|finding| finding.recommended_validations.iter().cloned())
1223 .collect::<BTreeSet<_>>()
1224 .into_iter()
1225 .collect();
1226 SemanticContractDelta {
1227 contract: contract.clone(),
1228 contract_kind: contract.kind,
1229 status,
1230 before_fingerprint: before,
1231 after_fingerprint: after,
1232 findings,
1233 factors,
1234 validations,
1235 }
1236}
1237
1238fn compatibility_severity(status: CompatibilityStatus) -> u8 {
1239 match status {
1240 CompatibilityStatus::Compatible => 0,
1241 CompatibilityStatus::Incomparable => 1,
1242 CompatibilityStatus::Unknown => 2,
1243 CompatibilityStatus::PotentiallyBreaking => 3,
1244 CompatibilityStatus::Breaking => 4,
1245 }
1246}
1247
1248fn unique_fingerprint<'a>(values: impl Iterator<Item = &'a str>) -> Option<String> {
1249 let values = values
1250 .filter(|value| !value.is_empty() && *value != "unavailable")
1251 .collect::<BTreeSet<_>>();
1252 (values.len() == 1).then(|| values.into_iter().next().unwrap_or_default().to_owned())
1253}
1254
1255fn impact_compatibility_input(delta: &SemanticContractDelta) -> CompatibilityInput {
1256 CompatibilityInput {
1257 contract_node_id: delta.contract.id.clone(),
1258 status: match delta.status {
1259 CompatibilityStatus::Breaking => ImpactCompatibilityStatus::Breaking,
1260 CompatibilityStatus::PotentiallyBreaking => {
1261 ImpactCompatibilityStatus::PotentiallyBreaking
1262 }
1263 CompatibilityStatus::Compatible => ImpactCompatibilityStatus::Compatible,
1264 CompatibilityStatus::Unknown | CompatibilityStatus::Incomparable => {
1265 ImpactCompatibilityStatus::Unknown
1266 }
1267 },
1268 evidence: delta
1269 .findings
1270 .iter()
1271 .map(|finding| finding.code.clone())
1272 .chain(delta.factors.iter().cloned())
1273 .collect::<BTreeSet<_>>()
1274 .into_iter()
1275 .collect(),
1276 recommended_validations: delta.validations.clone(),
1277 }
1278}
1279
1280fn freshness_for_change_set(
1281 change_set: &ChangeSet,
1282 freshness: &[RepoFreshness],
1283) -> Vec<RepoFreshness> {
1284 let mut normalized = freshness.to_vec();
1285 for item in &mut normalized {
1286 if item.repo_id != change_set.repo_id {
1287 continue;
1288 }
1289 if item.checkout_id != change_set.checkout_id {
1290 item.state = RepoFreshnessState::Unknown;
1291 item.reason =
1292 Some("snapshot checkout does not match the analyzed change set".to_owned());
1293 } else if item.head_commit.as_deref() != Some(change_set.checkout_head_sha.as_str()) {
1294 item.state = RepoFreshnessState::CommitsBehind;
1295 item.reason = Some("snapshot HEAD does not match the analyzed change set".to_owned());
1296 } else if item.manifest_hash != change_set.workspace_manifest_hash {
1297 item.state = RepoFreshnessState::ConfigChanged;
1298 item.reason =
1299 Some("snapshot manifest does not match the analyzed change set".to_owned());
1300 }
1301 }
1302 normalized.sort_by(|left, right| {
1303 (&left.repo_id, &left.checkout_id).cmp(&(&right.repo_id, &right.checkout_id))
1304 });
1305 normalized
1306}
1307
1308fn derive_service_memberships(nodes: &[Node], edges: &[Edge]) -> BTreeMap<NodeId, Vec<NodeId>> {
1309 let kinds = nodes
1310 .iter()
1311 .map(|node| (node.id.clone(), node.kind))
1312 .collect::<BTreeMap<_, _>>();
1313 let mut memberships = BTreeMap::<NodeId, BTreeSet<NodeId>>::new();
1314 for edge in edges {
1315 if edge.kind != code_system_graph_model::EdgeKind::Contains {
1316 continue;
1317 }
1318 match (kinds.get(&edge.source), kinds.get(&edge.target)) {
1319 (Some(NodeKind::Service), Some(_)) => {
1320 memberships
1321 .entry(edge.target.clone())
1322 .or_default()
1323 .insert(edge.source.clone());
1324 }
1325 (Some(_), Some(NodeKind::Service)) => {
1326 memberships
1327 .entry(edge.source.clone())
1328 .or_default()
1329 .insert(edge.target.clone());
1330 }
1331 _ => {}
1332 }
1333 }
1334 memberships
1335 .into_iter()
1336 .map(|(member, services)| (member, services.into_iter().collect()))
1337 .collect()
1338}
1339
1340fn aggregate_touched(
1341 change_set: &ChangeSet,
1342 changed_node_ids: &BTreeSet<NodeId>,
1343 nodes: &BTreeMap<NodeId, &Node>,
1344 community: Option<&CommunitySnapshot>,
1345 deltas: &[SemanticContractDelta],
1346 impacts: &[ImpactReport],
1347) -> (Vec<RepoId>, Vec<Node>, Vec<CommunityId>, Vec<Node>) {
1348 let mut repositories = BTreeSet::from([change_set.repo_id.clone()]);
1349 let mut services = BTreeMap::<NodeId, Node>::new();
1350 let mut communities = BTreeSet::new();
1351 let mut contracts = BTreeMap::<NodeId, Node>::new();
1352 for id in changed_node_ids {
1353 if let Some(node) = nodes.get(id).copied() {
1354 repositories.extend(node.repo_id.iter().cloned());
1355 if node.kind == NodeKind::Service {
1356 services.insert(node.id.clone(), node.clone());
1357 }
1358 if is_boundary_kind(node.kind) {
1359 contracts.insert(node.id.clone(), node.clone());
1360 }
1361 }
1362 }
1363 for delta in deltas {
1364 contracts.insert(delta.contract.id.clone(), delta.contract.clone());
1365 }
1366 for impact in impacts {
1367 repositories.extend(
1368 impact
1369 .affected_repositories
1370 .iter()
1371 .map(|item| item.repo_id.clone()),
1372 );
1373 services.extend(
1374 impact
1375 .affected_services
1376 .iter()
1377 .map(|item| (item.service.id.clone(), item.service.clone())),
1378 );
1379 communities.extend(
1380 impact
1381 .affected_communities
1382 .iter()
1383 .map(|item| item.community_id.clone()),
1384 );
1385 contracts.extend(
1386 impact
1387 .affected_contracts
1388 .iter()
1389 .map(|item| (item.contract.id.clone(), item.contract.clone())),
1390 );
1391 }
1392 if let Some(snapshot) = community {
1393 for item in &snapshot.communities {
1394 if item
1395 .members
1396 .iter()
1397 .any(|member| changed_node_ids.contains(member))
1398 {
1399 communities.insert(item.id.clone());
1400 }
1401 }
1402 }
1403 (
1404 repositories.into_iter().collect(),
1405 services.into_values().collect(),
1406 communities.into_iter().collect(),
1407 contracts.into_values().collect(),
1408 )
1409}
1410
1411fn summarize(
1412 coverage: &ChangeAnalysisCoverage,
1413 changed_entities: usize,
1414 changed_contracts: usize,
1415 impacts: &[ImpactReport],
1416) -> ChangeAnalysisSummary {
1417 let highest_risk = if coverage.complete {
1418 impacts
1419 .iter()
1420 .map(|impact| impact.risk)
1421 .max()
1422 .unwrap_or(RiskLevel::Low)
1423 } else {
1424 RiskLevel::Unknown
1425 };
1426 let conclusion = if !coverage.complete {
1427 ChangeConclusion::Unknown
1428 } else if changed_entities > 0 || changed_contracts > 0 || !impacts.is_empty() {
1429 ChangeConclusion::ImpactDetected
1430 } else {
1431 ChangeConclusion::NoSemanticImpactDetected
1432 };
1433 ChangeAnalysisSummary {
1434 conclusion,
1435 highest_risk,
1436 changed_entities,
1437 changed_contracts,
1438 impact_reports: impacts.len(),
1439 }
1440}
1441
1442#[cfg(test)]
1443mod tests {
1444 use std::collections::BTreeMap;
1445
1446 use code_system_graph_model::{
1447 CheckoutId, Community, CommunityAlgorithm, CommunityConfig, CommunityId, CommunityMetrics, CommunityScope, EdgeId, EdgeKind, EpistemicStatus, NativePathEncoding, Provenance
1448 };
1449
1450 use super::*;
1451 use crate::{ChangeHunk, ChangeScope};
1452
1453 type Fixture = (
1454 ChangeSet,
1455 Vec<Node>,
1456 Vec<Edge>,
1457 Vec<Evidence>,
1458 Vec<RepoFreshness>,
1459 Vec<ContractCompatibilityInput>,
1460 );
1461
1462 fn path(value: &str) -> NativePath {
1463 NativePath {
1464 encoding: NativePathEncoding::Utf8,
1465 bytes: value.as_bytes().to_vec(),
1466 display: value.to_owned(),
1467 }
1468 }
1469
1470 fn hunk(start: u32, count: u32) -> ChangeHunk {
1471 ChangeHunk {
1472 old_start: start,
1473 old_count: count,
1474 new_start: start,
1475 new_count: count,
1476 lines: Vec::new(),
1477 }
1478 }
1479
1480 fn file(status: ChangedFileStatus, value: &str) -> ChangedFile {
1481 ChangedFile {
1482 status,
1483 old_path: (status != ChangedFileStatus::Added
1484 && status != ChangedFileStatus::Untracked)
1485 .then(|| path(value)),
1486 new_path: (status != ChangedFileStatus::Deleted).then(|| path(value)),
1487 binary: false,
1488 hunks: vec![hunk(10, 2)],
1489 source: if status == ChangedFileStatus::Untracked {
1490 ChangeSourceLayer::Untracked
1491 } else {
1492 ChangeSourceLayer::Worktree
1493 },
1494 }
1495 }
1496
1497 fn rename(old: &str, new: &str) -> ChangedFile {
1498 ChangedFile {
1499 status: ChangedFileStatus::Renamed,
1500 old_path: Some(path(old)),
1501 new_path: Some(path(new)),
1502 binary: false,
1503 hunks: vec![hunk(10, 2)],
1504 source: ChangeSourceLayer::Commit,
1505 }
1506 }
1507
1508 fn change_set(files: Vec<ChangedFile>) -> ChangeSet {
1509 ChangeSet {
1510 repo_id: RepoId::new("repo:api"),
1511 checkout_id: CheckoutId::new("checkout:repo:api"),
1512 worktree: path("/workspace/api"),
1513 git_common_dir: path("/workspace/api/.git"),
1514 scope: ChangeScope::All,
1515 checkout_head_ref: Some("refs/heads/main".to_owned()),
1516 checkout_head_sha: "head".to_owned(),
1517 base_ref: Some("main".to_owned()),
1518 head_ref: Some("HEAD".to_owned()),
1519 head_sha: "head".to_owned(),
1520 staged_hash: "staged".to_owned(),
1521 worktree_hash: "worktree".to_owned(),
1522 exact_diff_fingerprint: "diff".to_owned(),
1523 workspace_manifest_hash: "manifest".to_owned(),
1524 contract_registry_hash: "registry".to_owned(),
1525 analyzer_versions: BTreeMap::from([("extractor".to_owned(), "1.0.0".to_owned())]),
1526 files,
1527 }
1528 }
1529
1530 fn node(id: &str, kind: NodeKind, repository: &str) -> Node {
1531 Node {
1532 id: NodeId::new(id),
1533 kind,
1534 repo_id: Some(RepoId::new(repository)),
1535 stable_key: id.to_owned(),
1536 label: id.to_owned(),
1537 }
1538 }
1539
1540 fn evidence(id: &str, file_path: &str, start: Option<u32>, end: Option<u32>) -> Evidence {
1541 Evidence {
1542 id: EvidenceId::new(id),
1543 repo_id: Some(RepoId::new("repo:api")),
1544 file_path: Some(file_path.to_owned()),
1545 start_line: start,
1546 end_line: end,
1547 extractor: "test".to_owned(),
1548 extractor_version: "1.0.0".to_owned(),
1549 provenance: Provenance::Extracted,
1550 confidence: 1.0,
1551 observed_at_commit: Some("head".to_owned()),
1552 content_hash: Some("content".to_owned()),
1553 note: None,
1554 }
1555 }
1556
1557 fn edge(id: &str, source: &str, target: &str, evidence_id: &str) -> Edge {
1558 Edge {
1559 id: EdgeId::new(id),
1560 source: NodeId::new(source),
1561 target: NodeId::new(target),
1562 kind: EdgeKind::Consumes,
1563 confidence: 1.0,
1564 status: EpistemicStatus::Confirmed,
1565 evidence: vec![EvidenceId::new(evidence_id)],
1566 }
1567 }
1568
1569 fn freshness(repository: &str) -> RepoFreshness {
1570 RepoFreshness {
1571 repo_id: RepoId::new(repository),
1572 checkout_id: CheckoutId::new(format!("checkout:{repository}")),
1573 head_commit: Some("head".to_owned()),
1574 manifest_hash: "manifest".to_owned(),
1575 state: RepoFreshnessState::Fresh,
1576 reason: None,
1577 }
1578 }
1579
1580 fn finding(status: CompatibilityStatus) -> CompatibilityFinding {
1581 CompatibilityFinding {
1582 code: "http.operation_removed".to_owned(),
1583 path: "GET /orders".to_owned(),
1584 status,
1585 factors: vec!["operation was removed".to_owned()],
1586 evidence: vec!["line:10".to_owned()],
1587 recommended_validations: vec!["run contract tests".to_owned()],
1588 }
1589 }
1590
1591 fn compatibility(status: CompatibilityStatus) -> ContractCompatibilityInput {
1592 ContractCompatibilityInput {
1593 file_path: Some("src/api.rs".to_owned()),
1594 contract_node_id: NodeId::new("contract"),
1595 report: Some(CompatibilityReport {
1596 status,
1597 before_fingerprint: "before".to_owned(),
1598 after_fingerprint: "after".to_owned(),
1599 findings: vec![finding(status)],
1600 }),
1601 }
1602 }
1603
1604 fn complete_fixture() -> Fixture {
1605 (
1606 change_set(vec![file(ChangedFileStatus::Modified, "src/api.rs")]),
1607 vec![
1608 node("contract", NodeKind::HttpOperation, "repo:api"),
1609 node("direct", NodeKind::Service, "repo:web"),
1610 node("transitive", NodeKind::TestCase, "repo:test"),
1611 ],
1612 vec![
1613 edge("edge:direct", "direct", "contract", "ev"),
1614 edge("edge:transitive", "transitive", "direct", "other"),
1615 ],
1616 vec![evidence("ev", "src/api.rs", Some(10), Some(11))],
1617 vec![
1618 freshness("repo:api"),
1619 freshness("repo:web"),
1620 freshness("repo:test"),
1621 ],
1622 vec![compatibility(CompatibilityStatus::Breaking)],
1623 )
1624 }
1625
1626 fn analyze_fixture(
1627 options: &ChangeAnalysisOptions,
1628 ) -> Result<ChangeImpactReport, ChangeAnalysisError> {
1629 let (changes, nodes, edges, evidence, freshness, compatibility) = complete_fixture();
1630 analyze_changes(
1631 &changes,
1632 &nodes,
1633 &edges,
1634 &evidence,
1635 None,
1636 &freshness,
1637 &compatibility,
1638 options,
1639 )
1640 }
1641
1642 #[test]
1643 fn mapping_should_intersect_exact_hunk_lines() {
1644 let changed = file(ChangedFileStatus::Modified, "src/api.rs");
1645 let nodes = BTreeMap::from([
1646 (
1647 NodeId::new("contract"),
1648 node("contract", NodeKind::HttpOperation, "repo:api"),
1649 ),
1650 (
1651 NodeId::new("consumer"),
1652 node("consumer", NodeKind::Service, "repo:web"),
1653 ),
1654 ]);
1655 let evidence = BTreeMap::from([(
1656 EvidenceId::new("ev"),
1657 evidence("ev", "src/api.rs", Some(11), Some(12)),
1658 )]);
1659 let node_refs = nodes
1660 .iter()
1661 .map(|(id, item)| (id.clone(), item))
1662 .collect::<BTreeMap<_, _>>();
1663 let evidence_refs = evidence
1664 .iter()
1665 .map(|(id, item)| (id.clone(), item))
1666 .collect::<BTreeMap<_, _>>();
1667
1668 let result = map_changed_file(
1669 &changed,
1670 &RepoId::new("repo:api"),
1671 &[edge("edge", "consumer", "contract", "ev")],
1672 &node_refs,
1673 &evidence_refs,
1674 );
1675
1676 assert_eq!(result.mapping.completeness, MappingCompleteness::Complete);
1677 }
1678
1679 #[test]
1680 fn mapping_should_exclude_evidence_outside_hunks() {
1681 let changed = file(ChangedFileStatus::Modified, "src/api.rs");
1682 let stored = evidence("ev", "src/api.rs", Some(30), Some(31));
1683 let evidence_refs = BTreeMap::from([(stored.id.clone(), &stored)]);
1684
1685 let result = map_changed_file(
1686 &changed,
1687 &RepoId::new("repo:api"),
1688 &[],
1689 &BTreeMap::new(),
1690 &evidence_refs,
1691 );
1692
1693 assert_eq!(result.mapping.matched_evidence_ids, Vec::new());
1694 }
1695
1696 #[test]
1697 fn mapping_should_not_normalize_distinct_native_path_bytes() {
1698 let changed = file(ChangedFileStatus::Modified, "src\\api.rs");
1699 let stored = evidence("ev", "src/api.rs", Some(10), Some(11));
1700 let evidence_refs = BTreeMap::from([(stored.id.clone(), &stored)]);
1701
1702 let result = map_changed_file(
1703 &changed,
1704 &RepoId::new("repo:api"),
1705 &[],
1706 &BTreeMap::new(),
1707 &evidence_refs,
1708 );
1709
1710 assert_eq!(result.mapping.matched_evidence_ids, Vec::new());
1711 }
1712
1713 #[test]
1714 fn mapping_should_use_file_fallback_without_line_evidence() {
1715 let changed = file(ChangedFileStatus::Modified, "src/api.rs");
1716 let stored = evidence("ev", "src/api.rs", None, None);
1717 let evidence_refs = BTreeMap::from([(stored.id.clone(), &stored)]);
1718
1719 let result = map_changed_file(
1720 &changed,
1721 &RepoId::new("repo:api"),
1722 &[],
1723 &BTreeMap::new(),
1724 &evidence_refs,
1725 );
1726
1727 assert!(matches!(
1728 result.mapping.matches.as_slice(),
1729 [HunkLineMatch {
1730 kind: EvidenceMatchKind::FilePathFallback,
1731 ..
1732 }]
1733 ));
1734 }
1735
1736 #[test]
1737 fn rename_should_include_old_and_new_neighborhoods() {
1738 let changed = rename("src/old.rs", "src/new.rs");
1739 let old = evidence("old", "src/old.rs", Some(10), Some(10));
1740 let new = evidence("new", "src/new.rs", Some(10), Some(10));
1741 let evidence_refs = BTreeMap::from([(old.id.clone(), &old), (new.id.clone(), &new)]);
1742
1743 let result = map_changed_file(
1744 &changed,
1745 &RepoId::new("repo:api"),
1746 &[],
1747 &BTreeMap::new(),
1748 &evidence_refs,
1749 );
1750
1751 assert_eq!(result.mapping.matched_evidence_ids.len(), 2);
1752 }
1753
1754 #[test]
1755 fn deletion_should_map_old_path_and_old_hunk() {
1756 let changed = file(ChangedFileStatus::Deleted, "src/old.rs");
1757 let old = evidence("old", "src/old.rs", Some(10), Some(10));
1758 let evidence_refs = BTreeMap::from([(old.id.clone(), &old)]);
1759
1760 let result = map_changed_file(
1761 &changed,
1762 &RepoId::new("repo:api"),
1763 &[],
1764 &BTreeMap::new(),
1765 &evidence_refs,
1766 );
1767
1768 assert_eq!(result.mapping.matches[0].path_side, ChangedPathSide::Old);
1769 }
1770
1771 #[test]
1772 fn binary_change_should_remain_incomplete() {
1773 let mut changed = file(ChangedFileStatus::Modified, "asset.bin");
1774 changed.binary = true;
1775 let stored = evidence("ev", "asset.bin", Some(10), Some(10));
1776 let evidence_refs = BTreeMap::from([(stored.id.clone(), &stored)]);
1777
1778 let result = map_changed_file(
1779 &changed,
1780 &RepoId::new("repo:api"),
1781 &[],
1782 &BTreeMap::new(),
1783 &evidence_refs,
1784 );
1785
1786 assert_ne!(result.mapping.completeness, MappingCompleteness::Complete);
1787 }
1788
1789 #[test]
1790 fn untracked_change_should_remain_incomplete() {
1791 let changed = file(ChangedFileStatus::Untracked, "src/new.rs");
1792 let stored = evidence("ev", "src/new.rs", None, None);
1793 let evidence_refs = BTreeMap::from([(stored.id.clone(), &stored)]);
1794
1795 let result = map_changed_file(
1796 &changed,
1797 &RepoId::new("repo:api"),
1798 &[],
1799 &BTreeMap::new(),
1800 &evidence_refs,
1801 );
1802
1803 assert_eq!(result.mapping.completeness, MappingCompleteness::Partial);
1804 }
1805
1806 #[test]
1807 fn non_unicode_native_path_should_be_unknown() {
1808 let mut changed = file(ChangedFileStatus::Modified, "ignored");
1809 changed.new_path = Some(NativePath {
1810 encoding: NativePathEncoding::UnixBytes,
1811 bytes: vec![0xff],
1812 display: "�".to_owned(),
1813 });
1814
1815 let result = map_changed_file(
1816 &changed,
1817 &RepoId::new("repo:api"),
1818 &[],
1819 &BTreeMap::new(),
1820 &BTreeMap::new(),
1821 );
1822
1823 assert_eq!(result.mapping.completeness, MappingCompleteness::Unknown);
1824 }
1825
1826 #[test]
1827 fn edge_evidence_should_map_artifact_symbol_and_boundary_nodes() {
1828 let changed = file(ChangedFileStatus::Modified, "src/api.rs");
1829 let node_values = [
1830 node("artifact", NodeKind::Artifact, "repo:api"),
1831 node("symbol", NodeKind::SymbolRef, "repo:api"),
1832 node("contract", NodeKind::HttpOperation, "repo:api"),
1833 ];
1834 let nodes = node_values
1835 .iter()
1836 .map(|item| (item.id.clone(), item))
1837 .collect::<BTreeMap<_, _>>();
1838 let stored = evidence("ev", "src/api.rs", Some(10), Some(10));
1839 let evidence_refs = BTreeMap::from([(stored.id.clone(), &stored)]);
1840 let edges = vec![
1841 edge("one", "artifact", "symbol", "ev"),
1842 edge("two", "symbol", "contract", "ev"),
1843 ];
1844
1845 let result = map_changed_file(
1846 &changed,
1847 &RepoId::new("repo:api"),
1848 &edges,
1849 &nodes,
1850 &evidence_refs,
1851 );
1852
1853 assert!(
1854 result.mapping.artifact_node_ids == vec![NodeId::new("artifact")]
1855 && result.mapping.symbol_ref_node_ids == vec![NodeId::new("symbol")]
1856 && result.mapping.boundary_node_ids == vec![NodeId::new("contract")]
1857 );
1858 }
1859
1860 #[test]
1861 fn breaking_delta_should_propagate_direct_and_transitive_impact()
1862 -> Result<(), ChangeAnalysisError> {
1863 let result = analyze_fixture(&ChangeAnalysisOptions::default())?;
1864
1865 assert!(
1866 result.contract_deltas[0].status == CompatibilityStatus::Breaking
1867 && result.impacts[0]
1868 .direct_consumers
1869 .iter()
1870 .any(|item| item.node.id == NodeId::new("direct"))
1871 && result.impacts[0]
1872 .transitive_consumers
1873 .iter()
1874 .any(|item| item.node.id == NodeId::new("transitive"))
1875 );
1876 Ok(())
1877 }
1878
1879 #[test]
1880 fn changed_nodes_should_aggregate_community() -> Result<(), ChangeAnalysisError> {
1881 let (changes, nodes, edges, evidence, freshness, compatibility) = complete_fixture();
1882 let community = CommunitySnapshot {
1883 snapshot_id: "snapshot".to_owned(),
1884 engine_version: "1.0.0".to_owned(),
1885 config: CommunityConfig {
1886 algorithm: CommunityAlgorithm::ConnectedComponents,
1887 scope: CommunityScope::Federated,
1888 seed: 0,
1889 resolution: 1.0,
1890 minimum_confidence: 0.8,
1891 edge_weights: Vec::new(),
1892 max_iterations: 10,
1893 },
1894 communities: vec![Community {
1895 id: CommunityId::new("community"),
1896 label: "orders".to_owned(),
1897 members: vec![NodeId::new("contract"), NodeId::new("direct")],
1898 central_nodes: vec![NodeId::new("contract")],
1899 repositories: vec![RepoId::new("repo:api"), RepoId::new("repo:web")],
1900 services: vec![NodeId::new("direct")],
1901 inbound_contracts: Vec::new(),
1902 outbound_contracts: vec![NodeId::new("contract")],
1903 metrics: CommunityMetrics {
1904 size: 2,
1905 density: 1.0,
1906 cohesion: 1.0,
1907 coupling: 0.0,
1908 cross_community_edges: 0,
1909 },
1910 label_evidence: Vec::new(),
1911 limitations: Vec::new(),
1912 }],
1913 };
1914
1915 let result = analyze_changes(
1916 &changes,
1917 &nodes,
1918 &edges,
1919 &evidence,
1920 Some(&community),
1921 &freshness,
1922 &compatibility,
1923 &ChangeAnalysisOptions::default(),
1924 )?;
1925
1926 assert_eq!(
1927 result.touched_communities,
1928 vec![CommunityId::new("community")]
1929 );
1930 Ok(())
1931 }
1932
1933 #[test]
1934 fn shuffled_inputs_should_produce_same_fingerprint_and_output()
1935 -> Result<(), ChangeAnalysisError> {
1936 let (changes, mut nodes, mut edges, mut evidence, mut freshness, compatibility) =
1937 complete_fixture();
1938 let first = analyze_changes(
1939 &changes,
1940 &nodes,
1941 &edges,
1942 &evidence,
1943 None,
1944 &freshness,
1945 &compatibility,
1946 &ChangeAnalysisOptions::default(),
1947 )?;
1948 nodes.reverse();
1949 edges.reverse();
1950 evidence.reverse();
1951 freshness.reverse();
1952 let second = analyze_changes(
1953 &changes,
1954 &nodes,
1955 &edges,
1956 &evidence,
1957 None,
1958 &freshness,
1959 &compatibility,
1960 &ChangeAnalysisOptions::default(),
1961 )?;
1962
1963 assert!(
1964 first.analyzer_fingerprint == second.analyzer_fingerprint
1965 && first.mappings == second.mappings
1966 && first.impacts == second.impacts
1967 );
1968 Ok(())
1969 }
1970
1971 #[test]
1972 fn changed_file_limit_should_force_unknown_coverage() -> Result<(), ChangeAnalysisError> {
1973 let (mut changes, nodes, edges, evidence, freshness, compatibility) = complete_fixture();
1974 changes
1975 .files
1976 .push(file(ChangedFileStatus::Modified, "src/other.rs"));
1977 let options = ChangeAnalysisOptions {
1978 max_changed_files: 1,
1979 ..ChangeAnalysisOptions::default()
1980 };
1981
1982 let result = analyze_changes(
1983 &changes,
1984 &nodes,
1985 &edges,
1986 &evidence,
1987 None,
1988 &freshness,
1989 &compatibility,
1990 &options,
1991 )?;
1992
1993 assert!(
1994 result.coverage.truncated
1995 && result.summary.conclusion == ChangeConclusion::Unknown
1996 && result.summary.highest_risk == RiskLevel::Unknown
1997 );
1998 Ok(())
1999 }
2000
2001 #[test]
2002 fn changed_node_limit_should_bound_entities() -> Result<(), ChangeAnalysisError> {
2003 let (changes, mut nodes, mut edges, evidence, freshness, compatibility) =
2004 complete_fixture();
2005 nodes.push(node("artifact", NodeKind::Artifact, "repo:api"));
2006 edges.push(edge("edge:artifact", "artifact", "contract", "ev"));
2007 let options = ChangeAnalysisOptions {
2008 max_changed_nodes: 1,
2009 ..ChangeAnalysisOptions::default()
2010 };
2011
2012 let result = analyze_changes(
2013 &changes,
2014 &nodes,
2015 &edges,
2016 &evidence,
2017 None,
2018 &freshness,
2019 &compatibility,
2020 &options,
2021 )?;
2022
2023 assert!(
2024 result.coverage.retained_changed_nodes == 1
2025 && result.coverage.total_changed_nodes == 2
2026 && result.coverage.truncated
2027 );
2028 Ok(())
2029 }
2030
2031 #[test]
2032 fn impact_target_limit_should_bound_reports() -> Result<(), ChangeAnalysisError> {
2033 let (changes, mut nodes, mut edges, evidence, freshness, mut compatibility) =
2034 complete_fixture();
2035 nodes.push(node("contract-two", NodeKind::RpcMethod, "repo:api"));
2036 edges.push(edge("edge:two", "direct", "contract-two", "ev"));
2037 compatibility.push(ContractCompatibilityInput {
2038 file_path: Some("src/api.rs".to_owned()),
2039 contract_node_id: NodeId::new("contract-two"),
2040 report: Some(CompatibilityReport {
2041 status: CompatibilityStatus::Compatible,
2042 before_fingerprint: "before-two".to_owned(),
2043 after_fingerprint: "after-two".to_owned(),
2044 findings: Vec::new(),
2045 }),
2046 });
2047 let options = ChangeAnalysisOptions {
2048 max_impact_targets: 1,
2049 ..ChangeAnalysisOptions::default()
2050 };
2051
2052 let result = analyze_changes(
2053 &changes,
2054 &nodes,
2055 &edges,
2056 &evidence,
2057 None,
2058 &freshness,
2059 &compatibility,
2060 &options,
2061 )?;
2062
2063 assert!(
2064 result.impacts.len() == 1
2065 && result.coverage.total_impact_targets == 2
2066 && result.coverage.truncated
2067 );
2068 Ok(())
2069 }
2070
2071 #[test]
2072 fn entity_pagination_should_follow_stable_node_order() -> Result<(), ChangeAnalysisError> {
2073 let (changes, mut nodes, mut edges, evidence, freshness, compatibility) =
2074 complete_fixture();
2075 nodes.push(node("artifact", NodeKind::Artifact, "repo:api"));
2076 nodes.push(node("symbol", NodeKind::SymbolRef, "repo:api"));
2077 edges.push(edge("edge:artifact", "artifact", "symbol", "ev"));
2078 edges.push(edge("edge:symbol", "symbol", "contract", "ev"));
2079 let options = ChangeAnalysisOptions {
2080 offset: 1,
2081 limit: 1,
2082 ..ChangeAnalysisOptions::default()
2083 };
2084
2085 let result = analyze_changes(
2086 &changes,
2087 &nodes,
2088 &edges,
2089 &evidence,
2090 None,
2091 &freshness,
2092 &compatibility,
2093 &options,
2094 )?;
2095
2096 assert_eq!(result.changed_entities[0].node.id, NodeId::new("contract"));
2097 Ok(())
2098 }
2099
2100 #[test]
2101 fn summary_only_should_omit_detailed_entities_and_impact_items()
2102 -> Result<(), ChangeAnalysisError> {
2103 let options = ChangeAnalysisOptions {
2104 summary_only: true,
2105 ..ChangeAnalysisOptions::default()
2106 };
2107
2108 let result = analyze_fixture(&options)?;
2109
2110 assert!(
2111 result.changed_entities.is_empty()
2112 && result.impacts[0].direct_consumers.is_empty()
2113 && result.summary.impact_reports == 1
2114 );
2115 Ok(())
2116 }
2117
2118 #[test]
2119 fn missing_compatibility_input_should_be_unknown() -> Result<(), ChangeAnalysisError> {
2120 let (changes, nodes, edges, evidence, freshness, _) = complete_fixture();
2121
2122 let result = analyze_changes(
2123 &changes,
2124 &nodes,
2125 &edges,
2126 &evidence,
2127 None,
2128 &freshness,
2129 &[],
2130 &ChangeAnalysisOptions::default(),
2131 )?;
2132
2133 assert_eq!(
2134 result.contract_deltas[0].status,
2135 CompatibilityStatus::Unknown
2136 );
2137 Ok(())
2138 }
2139
2140 #[test]
2141 fn absent_contract_fingerprint_should_be_unknown() -> Result<(), ChangeAnalysisError> {
2142 let (changes, nodes, edges, evidence, freshness, mut compatibility) = complete_fixture();
2143 compatibility[0].report = Some(CompatibilityReport {
2144 status: CompatibilityStatus::Compatible,
2145 before_fingerprint: String::new(),
2146 after_fingerprint: "after".to_owned(),
2147 findings: Vec::new(),
2148 });
2149
2150 let result = analyze_changes(
2151 &changes,
2152 &nodes,
2153 &edges,
2154 &evidence,
2155 None,
2156 &freshness,
2157 &compatibility,
2158 &ChangeAnalysisOptions::default(),
2159 )?;
2160
2161 assert_eq!(
2162 result.contract_deltas[0].status,
2163 CompatibilityStatus::Unknown
2164 );
2165 Ok(())
2166 }
2167
2168 #[test]
2169 fn validation_should_invalidate_changed_head() -> Result<(), ChangeAnalysisError> {
2170 let report = analyze_fixture(&ChangeAnalysisOptions::default())?;
2171 let mut current = ChangeValidityInput::from(&report.change_set);
2172 current.checkout_head_sha = "advanced".to_owned();
2173
2174 let result = validate_change_analysis(&report, ¤t);
2175
2176 assert!(matches!(result, ChangeValidity::Stale { .. }));
2177 Ok(())
2178 }
2179
2180 #[test]
2181 fn validation_should_invalidate_changed_manifest() -> Result<(), ChangeAnalysisError> {
2182 let report = analyze_fixture(&ChangeAnalysisOptions::default())?;
2183 let mut current = ChangeValidityInput::from(&report.change_set);
2184 current.workspace_manifest_hash = "new-manifest".to_owned();
2185
2186 let result = validate_change_analysis(&report, ¤t);
2187
2188 assert!(matches!(result, ChangeValidity::Stale { .. }));
2189 Ok(())
2190 }
2191
2192 #[test]
2193 fn zero_bounds_should_be_rejected() {
2194 let options = ChangeAnalysisOptions {
2195 max_impact_targets: 0,
2196 ..ChangeAnalysisOptions::default()
2197 };
2198
2199 let result = analyze_fixture(&options);
2200
2201 assert!(matches!(result, Err(ChangeAnalysisError::InvalidBounds)));
2202 }
2203
2204 #[test]
2205 fn serialized_report_should_contain_positions_but_no_diff_body()
2206 -> Result<(), Box<dyn std::error::Error>> {
2207 let report = analyze_fixture(&ChangeAnalysisOptions::default())?;
2208
2209 let encoded = serde_json::to_string(&report)?;
2210
2211 assert!(
2212 encoded.contains("\"old_start\":10")
2213 && encoded.contains("\"new_start\":10")
2214 && !encoded.contains("\"source_body\"")
2215 && !encoded.contains("\"diff_body\"")
2216 );
2217 Ok(())
2218 }
2219}