Skip to main content

code_system_graph_core/
impact.rs

1//! Deterministic, conservative cross-repository impact and risk analysis.
2
3use std::cmp::Ordering;
4use std::collections::{BTreeMap, BTreeSet, VecDeque};
5
6use code_system_graph_model::{
7    CommunityId, CommunitySnapshot, Edge, EdgeId, EdgeKind, EpistemicStatus, EvidenceId, Node, NodeId, NodeKind, RepoFreshness, RepoFreshnessState, RepoId
8};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13const RISK_MODEL_VERSION: &str = "1.0.0";
14const MAX_DEPTH: usize = 128;
15const MAX_NODES: usize = 100_000;
16const MAX_EDGES: usize = 1_000_000;
17const MAX_LIMIT: usize = 10_000;
18const MAX_OFFSET: usize = 1_000_000;
19
20/// Conservative risk classification for an impact result.
21#[derive(
22    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
23)]
24#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
25pub enum RiskLevel {
26    /// Fresh, complete coverage found only bounded low-risk factors.
27    Low,
28    /// Material but bounded impact was found.
29    Medium,
30    /// Broad, breaking, or otherwise severe impact was found.
31    High,
32    /// Explicit critical-domain evidence and a sufficiently high score were found.
33    Critical,
34    /// Coverage is insufficient for a numeric risk conclusion.
35    Unknown,
36}
37
38/// Direction in which impact propagates from the resolved target.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
40#[serde(rename_all = "snake_case")]
41pub enum ImpactDirection {
42    /// Follow incoming relationships to dependents and consumers.
43    Upstream,
44    /// Follow outgoing relationships to dependencies and providers.
45    Downstream,
46    /// Follow both incoming and outgoing relationships.
47    Both,
48}
49
50/// Confidence-aware classification of one affected graph entity.
51#[derive(
52    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
53)]
54#[serde(rename_all = "snake_case")]
55pub enum ImpactClassification {
56    /// A confirmed high-confidence edge directly links the entity to the target.
57    DirectlyDependent,
58    /// A confirmed high-confidence path transitively links the entity to the target.
59    TransitivelyAffected,
60    /// Candidate, inferred, ambiguous, or low-confidence evidence may link the entity.
61    PossiblyAffected,
62    /// Stale or incomplete evidence prevents a stronger classification.
63    UnknownDueToCoverage,
64}
65
66/// Selector used to resolve exactly one graph target.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
68#[serde(rename_all = "snake_case", untagged)]
69pub enum ImpactTarget {
70    /// Resolve an exact graph node identifier.
71    NodeId {
72        /// Exact persisted node identifier returned by query or source context.
73        node_id: NodeId,
74    },
75    /// Resolve an exact versioned stable key.
76    StableKey {
77        /// Exact stable key returned by query or another structured result.
78        stable_key: String,
79    },
80}
81
82impl<'de> Deserialize<'de> for ImpactTarget {
83    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
84    where
85        D: serde::Deserializer<'de>,
86    {
87        #[derive(Deserialize)]
88        #[serde(deny_unknown_fields)]
89        struct NodeIdTarget {
90            node_id: NodeId,
91        }
92
93        #[derive(Deserialize)]
94        #[serde(deny_unknown_fields)]
95        struct StableKeyTarget {
96            stable_key: String,
97        }
98
99        #[derive(Deserialize)]
100        #[serde(untagged)]
101        enum WireTarget {
102            NodeId(NodeIdTarget),
103            StableKey(StableKeyTarget),
104        }
105
106        match WireTarget::deserialize(deserializer)? {
107            WireTarget::NodeId(target) => Ok(Self::NodeId {
108                node_id: target.node_id,
109            }),
110            WireTarget::StableKey(target) => Ok(Self::StableKey {
111                stable_key: target.stable_key,
112            }),
113        }
114    }
115}
116
117/// Exact graph target selected for analysis.
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
119pub struct ResolvedTarget {
120    /// Resolved graph node.
121    pub node: Node,
122    /// Canonical selector form used to resolve the node.
123    pub resolved_by: String,
124}
125
126/// One directed relationship in an impact path.
127#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
128pub struct ImpactPathStep {
129    /// Node from which this traversal step began.
130    pub from: NodeId,
131    /// Node reached by this traversal step.
132    pub to: NodeId,
133    /// Existing graph relationship used by this step.
134    pub edge_id: EdgeId,
135    /// Relationship kind.
136    pub kind: EdgeKind,
137    /// Whether the underlying edge was followed from target to source.
138    pub reversed: bool,
139    /// Edge confidence as supplied by the graph.
140    pub confidence: f32,
141    /// Edge epistemic status as supplied by the graph.
142    pub status: EpistemicStatus,
143}
144
145/// One deterministically selected affected graph entity.
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
147pub struct ImpactItem {
148    /// Affected node.
149    pub node: Node,
150    /// Conservative impact classification.
151    pub classification: ImpactClassification,
152    /// Number of graph relationships from the target.
153    pub depth: usize,
154    /// Deterministic shortest and strongest path selected for this node.
155    pub path: Vec<ImpactPathStep>,
156    /// Sorted evidence identifiers supporting the selected path.
157    pub evidence: Vec<EvidenceId>,
158}
159
160/// One explainable component of the versioned risk model.
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
162pub struct RiskFactor {
163    /// Stable machine-readable factor code.
164    pub code: String,
165    /// Non-negative score contribution before the final 100-point cap.
166    pub weight: f32,
167    /// Bounded human-readable explanation.
168    pub explanation: String,
169    /// Sorted evidence identifiers or explicit context references.
170    pub evidence: Vec<String>,
171}
172
173/// Aggregate impact for one repository.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
175pub struct RepositoryImpact {
176    /// Affected repository.
177    pub repo_id: RepoId,
178    /// Strongest impact classification observed in the repository.
179    pub classification: ImpactClassification,
180    /// Minimum path depth among affected nodes.
181    pub minimum_depth: usize,
182    /// Number of affected graph nodes before pagination.
183    pub affected_nodes: usize,
184}
185
186/// Aggregate impact for one service.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
188pub struct ServiceImpact {
189    /// Service node.
190    pub service: Node,
191    /// Strongest impact classification observed for service members.
192    pub classification: ImpactClassification,
193    /// Minimum path depth among affected service members.
194    pub minimum_depth: usize,
195    /// Number of affected service members.
196    pub affected_nodes: usize,
197}
198
199/// Impact on a modeled public or private contract.
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
201pub struct ContractImpact {
202    /// Affected contract node.
203    pub contract: Node,
204    /// Conservative impact classification.
205    pub classification: ImpactClassification,
206    /// Minimum path depth.
207    pub depth: usize,
208    /// Whether the contract was explicitly declared public in the analysis context.
209    pub public: bool,
210}
211
212/// Aggregate impact for one detected graph community.
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
214pub struct CommunityImpact {
215    /// Community identity.
216    pub community_id: CommunityId,
217    /// Deterministic community label.
218    pub label: String,
219    /// Strongest member impact classification.
220    pub classification: ImpactClassification,
221    /// Number of affected community members.
222    pub affected_members: usize,
223    /// Accepted edge weight crossing the community boundary.
224    pub coupling: f64,
225    /// Explicit community limitations copied from the immutable snapshot.
226    pub limitations: Vec<String>,
227}
228
229/// Availability state of optional repository-local enrichment.
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
231#[serde(rename_all = "snake_case")]
232pub enum LocalEnrichmentStatus {
233    /// The local provider completed with current inputs.
234    Available,
235    /// The local provider returned only part of the requested result.
236    Partial,
237    /// The local index does not match current repository inputs.
238    Stale,
239    /// The local capability or repository index is unavailable.
240    Unavailable,
241}
242
243/// One repository-local symbol supplied as optional input data.
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
245pub struct LocalImpactItem {
246    /// Provider-local symbol name.
247    pub symbol: String,
248    /// Repository-relative source path.
249    pub file_path: String,
250    /// One-based source start line when available.
251    pub start_line: Option<usize>,
252    /// Local traversal depth.
253    pub depth: usize,
254}
255
256/// Optional local impact input produced before this pure analysis call.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
258pub struct LocalEnrichmentInput {
259    /// Repository to which this local result belongs.
260    pub repo_id: RepoId,
261    /// Exact local anchor requested from the provider.
262    pub anchor: String,
263    /// Provider/index availability.
264    pub status: LocalEnrichmentStatus,
265    /// Bounded affected local symbols.
266    pub affected: Vec<LocalImpactItem>,
267    /// Bounded affected test paths.
268    pub affected_tests: Vec<String>,
269    /// Whether provider or adapter bounds truncated this local result.
270    pub truncated: bool,
271    /// Explicit provider degradations and remediation.
272    pub degradations: Vec<String>,
273}
274
275/// Visible repository-local enrichment included in the report.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
277pub struct LocalImpactSummary {
278    /// Repository to which the local result belongs.
279    pub repo_id: RepoId,
280    /// Exact local anchor requested from the provider.
281    pub anchor: String,
282    /// Provider/index availability.
283    pub status: LocalEnrichmentStatus,
284    /// Number of local symbols returned.
285    pub affected_count: usize,
286    /// Maximum local depth observed.
287    pub maximum_depth: usize,
288    /// Whether the local result was truncated.
289    pub truncated: bool,
290    /// Explicit provider degradations and remediation.
291    pub degradations: Vec<String>,
292}
293
294/// Origin of a recommended test.
295#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
296#[serde(rename_all = "snake_case")]
297pub enum TestRecommendationSource {
298    /// A graph `TestCase` linked by `Validates`.
299    Graph,
300    /// An affected-test result supplied by optional local enrichment.
301    LocalEnrichment,
302}
303
304/// Ranked, non-executing recommendation for impact validation.
305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
306pub struct TestRecommendation {
307    /// Stable graph node when the recommendation came from a modeled test case.
308    pub test_node_id: Option<NodeId>,
309    /// Test label or repository-relative test path.
310    pub test: String,
311    /// Repository containing the test when known.
312    pub repo_id: Option<RepoId>,
313    /// Recommendation origin.
314    pub source: TestRecommendationSource,
315    /// One-based deterministic rank.
316    pub rank: usize,
317    /// Reasons this test is relevant.
318    pub reasons: Vec<String>,
319    /// Owner nodes linked to the test or validated impact target.
320    pub owners: Vec<Node>,
321    /// Explicit commands supplied by context; these are never executed.
322    pub recommended_commands: Vec<String>,
323}
324
325/// Coverage details that control whether a numeric risk score is permitted.
326#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
327pub struct CoverageSummary {
328    /// Whether all required graph, freshness, and enrichment inputs are sufficient.
329    pub sufficient_for_score: bool,
330    /// Relevant repositories discovered from the target and affected nodes.
331    pub relevant_repositories: Vec<RepoId>,
332    /// Relevant repositories with fresh inputs.
333    pub fresh_repositories: Vec<RepoId>,
334    /// Relevant repositories with stale or changed inputs.
335    pub stale_repositories: Vec<RepoId>,
336    /// Relevant repositories with partial inputs.
337    pub partial_repositories: Vec<RepoId>,
338    /// Relevant repositories whose checkout or data is unavailable.
339    pub unavailable_repositories: Vec<RepoId>,
340    /// Relevant repositories without a freshness record.
341    pub missing_repositories: Vec<RepoId>,
342    /// Number of candidate or low-confidence edges selected by traversal.
343    pub possible_edges: usize,
344    /// Number of stale or incomplete edges selected by traversal.
345    pub unknown_edges: usize,
346    /// Explicit coverage limitations in deterministic order.
347    pub gaps: Vec<String>,
348    /// Concrete remediation guidance in deterministic order.
349    pub remediation: Vec<String>,
350    /// Total affected items before pagination.
351    pub total_items: usize,
352}
353
354/// Configured bound that stopped complete traversal or result delivery.
355#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
356pub struct TruncationInfo {
357    /// Stable machine-readable bound name.
358    pub bound: String,
359    /// Configured bound value.
360    pub limit: usize,
361    /// Number observed when the bound stopped analysis.
362    pub observed: usize,
363    /// Explanation of the uncertainty introduced by truncation.
364    pub explanation: String,
365}
366
367/// Counts of impact classifications at one exact path depth.
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
369pub struct ImpactDepthBucket {
370    /// Exact path depth represented by this bucket.
371    pub depth: usize,
372    /// Directly dependent item count.
373    pub directly_dependent: usize,
374    /// Transitively affected item count.
375    pub transitively_affected: usize,
376    /// Possibly affected item count.
377    pub possibly_affected: usize,
378    /// Coverage-unknown item count.
379    pub unknown_due_to_coverage: usize,
380}
381
382/// Deterministic bounds and presentation controls for impact analysis.
383#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
384pub struct ImpactOptions {
385    /// Maximum graph path depth.
386    #[serde(default = "default_impact_max_depth")]
387    pub max_depth: usize,
388    /// Maximum number of distinct affected nodes.
389    #[serde(default = "default_impact_node_limit")]
390    pub node_limit: usize,
391    /// Maximum number of graph edges examined.
392    #[serde(default = "default_impact_edge_limit")]
393    pub edge_limit: usize,
394    /// Minimum confidence required for a confirmed edge.
395    #[serde(default = "default_confirmed_confidence")]
396    pub confirmed_confidence: f32,
397    /// Zero-based offset over the stable combined impact order.
398    #[serde(default)]
399    pub offset: usize,
400    /// Maximum number of detailed items returned.
401    #[serde(default = "default_impact_limit")]
402    pub limit: usize,
403    /// Omit detailed impact-item lists while retaining aggregates and counts.
404    #[serde(default)]
405    pub summary_only: bool,
406    /// Include exact-depth classification buckets.
407    #[serde(default = "default_include_depth_buckets")]
408    pub include_depth_buckets: bool,
409}
410
411impl Default for ImpactOptions {
412    fn default() -> Self {
413        Self {
414            max_depth: default_impact_max_depth(),
415            node_limit: default_impact_node_limit(),
416            edge_limit: default_impact_edge_limit(),
417            confirmed_confidence: default_confirmed_confidence(),
418            offset: 0,
419            limit: default_impact_limit(),
420            summary_only: false,
421            include_depth_buckets: default_include_depth_buckets(),
422        }
423    }
424}
425
426const fn default_impact_max_depth() -> usize {
427    8
428}
429
430const fn default_impact_node_limit() -> usize {
431    10_000
432}
433
434const fn default_impact_edge_limit() -> usize {
435    50_000
436}
437
438const fn default_confirmed_confidence() -> f32 {
439    0.8
440}
441
442const fn default_impact_limit() -> usize {
443    100
444}
445
446const fn default_include_depth_buckets() -> bool {
447    true
448}
449
450/// Request for one deterministic impact analysis.
451#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
452pub struct ImpactRequest {
453    /// Exact node identifier or stable key selector.
454    pub target: ImpactTarget,
455    /// Requested propagation direction.
456    pub direction: ImpactDirection,
457    /// Traversal and presentation controls.
458    #[serde(default)]
459    pub options: ImpactOptions,
460}
461
462impl<'de> Deserialize<'de> for ImpactRequest {
463    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
464    where
465        D: serde::Deserializer<'de>,
466    {
467        #[derive(Deserialize)]
468        struct WireImpactRequest {
469            #[serde(default)]
470            target: Option<ImpactTarget>,
471            #[serde(default)]
472            node_id: Option<NodeId>,
473            #[serde(default, alias = "key")]
474            stable_key: Option<String>,
475            #[serde(default)]
476            direction: Option<ImpactDirection>,
477            #[serde(default)]
478            options: ImpactOptions,
479        }
480
481        let wire = WireImpactRequest::deserialize(deserializer)?;
482        let selector_count = usize::from(wire.target.is_some())
483            + usize::from(wire.node_id.is_some())
484            + usize::from(wire.stable_key.is_some());
485        if selector_count != 1 {
486            return Err(serde::de::Error::custom(
487                "exactly one of target, node_id, stable_key, or key is required",
488            ));
489        }
490        let target = wire
491            .target
492            .or_else(|| wire.node_id.map(|node_id| ImpactTarget::NodeId { node_id }))
493            .or_else(|| {
494                wire.stable_key
495                    .map(|stable_key| ImpactTarget::StableKey { stable_key })
496            })
497            .ok_or_else(|| {
498                serde::de::Error::missing_field("target, node_id, stable_key, or key")
499            })?;
500        Ok(Self {
501            target,
502            direction: wire.direction.unwrap_or(ImpactDirection::Both),
503            options: wire.options,
504        })
505    }
506}
507
508/// Compatibility classification supplied to the impact engine.
509#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
510#[serde(rename_all = "snake_case")]
511pub enum ImpactCompatibilityStatus {
512    /// A supported compatibility rule proves a breaking change.
513    Breaking,
514    /// The change can be breaking but requires runtime or policy confirmation.
515    PotentiallyBreaking,
516    /// Modeled rules prove compatibility under complete inputs.
517    Compatible,
518    /// Compatibility coverage is insufficient.
519    Unknown,
520}
521
522/// Compatibility result associated with a graph contract.
523#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
524pub struct CompatibilityInput {
525    /// Contract node to which this result applies.
526    pub contract_node_id: NodeId,
527    /// Conservative compatibility classification.
528    pub status: ImpactCompatibilityStatus,
529    /// Stable rule codes or bounded evidence references.
530    pub evidence: Vec<String>,
531    /// Recommended compatibility validations.
532    pub recommended_validations: Vec<String>,
533}
534
535/// Explicit critical-domain tag; labels are never interpreted as tags.
536#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
537#[serde(rename_all = "snake_case")]
538pub enum CriticalityTag {
539    /// Explicitly designated critical system or process.
540    Critical,
541    /// Authentication or authorization boundary.
542    Authentication,
543    /// Security-sensitive boundary.
544    Security,
545    /// Payment or financial boundary.
546    Payment,
547    /// Data governance, privacy, or storage boundary.
548    DataBoundary,
549}
550
551/// Explicit, evidence-backed critical-domain assignment.
552#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
553pub struct CriticalityAssignment {
554    /// Tagged graph node.
555    pub node_id: NodeId,
556    /// Explicit critical-domain tag.
557    pub tag: CriticalityTag,
558    /// Non-empty evidence or policy reference supplied by the caller.
559    pub evidence: Vec<String>,
560}
561
562/// Explicit deployment environment associated with a graph node.
563#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
564pub struct EnvironmentAssignment {
565    /// Deployment, service, contract, or repository node.
566    pub node_id: NodeId,
567    /// Canonical environment name supplied by configuration.
568    pub environment: String,
569}
570
571/// Explicit non-executing validation command supplied by configuration.
572#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
573pub struct RecommendedCommand {
574    /// Repository in which the command is valid.
575    pub repo_id: RepoId,
576    /// Command displayed to the caller but never executed by this module.
577    pub command: String,
578    /// Bounded explanation of the command's purpose.
579    pub description: String,
580}
581
582/// Complete immutable input context for pure impact analysis.
583#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
584pub struct ImpactContext {
585    /// Federated graph nodes.
586    pub nodes: Vec<Node>,
587    /// Federated graph relationships.
588    pub edges: Vec<Edge>,
589    /// Optional immutable community analysis for this graph snapshot.
590    pub communities: Option<CommunitySnapshot>,
591    /// Repository freshness records.
592    pub freshness: Vec<RepoFreshness>,
593    /// Compatibility results computed before this call.
594    pub compatibility: Vec<CompatibilityInput>,
595    /// Optional repository-local impact and affected-test inputs.
596    pub local_enrichment: Vec<LocalEnrichmentInput>,
597    /// Nodes explicitly declared to be public contracts.
598    pub public_contracts: Vec<NodeId>,
599    /// Explicit critical-domain assignments.
600    pub criticality: Vec<CriticalityAssignment>,
601    /// Normalized centrality scores keyed by graph node.
602    pub centrality: BTreeMap<NodeId, f32>,
603    /// Service memberships keyed by member node.
604    pub service_memberships: BTreeMap<NodeId, Vec<NodeId>>,
605    /// Explicit deployment environment assignments.
606    pub environments: Vec<EnvironmentAssignment>,
607    /// Explicit non-executing validation commands.
608    pub recommended_commands: Vec<RecommendedCommand>,
609    /// Whether graph extraction and linking completed for the requested workspace.
610    pub graph_complete: bool,
611    /// Additional known coverage gaps.
612    pub coverage_gaps: Vec<String>,
613}
614
615/// Complete deterministic impact and risk result.
616#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
617pub struct ImpactReport {
618    /// Version of the deterministic risk model.
619    pub risk_model_version: String,
620    /// Exact target selected for analysis.
621    pub target: ResolvedTarget,
622    /// Applied propagation direction.
623    pub direction: ImpactDirection,
624    /// Conservative aggregate risk.
625    pub risk: RiskLevel,
626    /// Positive score in `0..=100`, omitted whenever risk is unknown.
627    pub risk_score: Option<f32>,
628    /// Deterministically ordered risk factors.
629    pub reasons: Vec<RiskFactor>,
630    /// Confirmed depth-one dependents in the selected page.
631    pub direct_consumers: Vec<ImpactItem>,
632    /// Confirmed depth-two-or-greater impacts in the selected page.
633    pub transitive_consumers: Vec<ImpactItem>,
634    /// Candidate, inferred, ambiguous, or low-confidence impacts in the selected page.
635    pub possibly_affected: Vec<ImpactItem>,
636    /// Impacts whose selected path contains stale or incomplete evidence.
637    pub unknown_due_to_coverage: Vec<ImpactItem>,
638    /// Repository aggregates computed before pagination.
639    pub affected_repositories: Vec<RepositoryImpact>,
640    /// Service aggregates computed before pagination.
641    pub affected_services: Vec<ServiceImpact>,
642    /// Contract impacts computed before pagination.
643    pub affected_contracts: Vec<ContractImpact>,
644    /// Community aggregates computed before pagination.
645    pub affected_communities: Vec<CommunityImpact>,
646    /// Optional local-enrichment summaries.
647    pub local_impact_summaries: Vec<LocalImpactSummary>,
648    /// Ranked test recommendations.
649    pub test_recommendations: Vec<TestRecommendation>,
650    /// Optional exact-depth counts computed before pagination.
651    pub depth_buckets: Vec<ImpactDepthBucket>,
652    /// Coverage and remediation details.
653    pub coverage: CoverageSummary,
654    /// First configured bound that introduced uncertainty.
655    pub truncation: Option<TruncationInfo>,
656}
657
658/// Validation error returned before impact analysis begins.
659#[derive(Debug, Error, PartialEq)]
660pub enum ImpactError {
661    /// More than one graph node has the same identifier.
662    #[error("duplicate node identifier `{0}`")]
663    DuplicateNode(String),
664    /// More than one graph relationship has the same identifier.
665    #[error("duplicate edge identifier `{0}`")]
666    DuplicateEdge(String),
667    /// More than one freshness record exists for the same repository.
668    #[error("duplicate freshness record for repository `{0}`")]
669    DuplicateFreshness(String),
670    /// A graph relationship references a missing endpoint.
671    #[error("edge `{edge}` references missing node `{node}`")]
672    DanglingEdge {
673        /// Relationship identifier.
674        edge: String,
675        /// Missing endpoint identifier.
676        node: String,
677    },
678    /// An input edge has non-finite or out-of-range confidence.
679    #[error("edge `{0}` confidence must be finite and in the inclusive range 0..=1")]
680    InvalidEdgeConfidence(String),
681    /// The configured confirmed-confidence threshold is invalid.
682    #[error("confirmed confidence must be finite and in the inclusive range 0..=1")]
683    InvalidConfirmedConfidence,
684    /// One or more traversal or pagination bounds are invalid.
685    #[error("impact traversal or pagination bounds are outside supported limits")]
686    InvalidBounds,
687    /// A supplied centrality score is non-finite or out of range.
688    #[error("centrality for node `{0}` must be finite and in the inclusive range 0..=1")]
689    InvalidCentrality(String),
690    /// An explicit criticality assignment has no evidence.
691    #[error("criticality assignment for node `{0}` requires explicit evidence")]
692    CriticalityWithoutEvidence(String),
693    /// An input context references a node absent from the graph.
694    #[error("{context} references missing node `{node}`")]
695    UnknownContextNode {
696        /// Context collection containing the reference.
697        context: &'static str,
698        /// Missing node identifier.
699        node: String,
700    },
701    /// No graph node matches the requested target.
702    #[error("impact target was not found")]
703    UnknownTarget,
704    /// A stable-key selector resolves to more than one node.
705    #[error("stable key `{0}` resolves to more than one node")]
706    AmbiguousTarget(String),
707}
708
709#[derive(Debug, Clone)]
710struct TraversalState {
711    node_id: NodeId,
712    certainty: PathCertainty,
713    path: Vec<ImpactPathStep>,
714    evidence: BTreeSet<EvidenceId>,
715}
716
717#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
718enum PathCertainty {
719    Confirmed,
720    Possible,
721    Unknown,
722}
723
724#[derive(Debug, Clone)]
725struct Adjacency<'a> {
726    neighbor: NodeId,
727    edge: &'a Edge,
728    reversed: bool,
729}
730
731#[derive(Debug, Clone, Copy)]
732struct Aggregate {
733    classification: ImpactClassification,
734    minimum_depth: usize,
735    affected_nodes: usize,
736}
737
738/// Performs pure deterministic impact propagation, aggregation, and conservative risk analysis.
739///
740/// The function never invokes providers or executes commands. Optional compatibility, local
741/// intelligence, environment, criticality, and command data must already be present in `context`.
742///
743/// # Errors
744///
745/// Returns [`ImpactError`] when graph identities, references, confidence values, centrality
746/// scores, criticality evidence, target resolution, or configured bounds are invalid.
747#[must_use = "impact reports and validation errors must be handled"]
748pub fn analyze_impact(
749    request: &ImpactRequest,
750    context: &ImpactContext,
751) -> Result<ImpactReport, ImpactError> {
752    let nodes = validate_context(request, context)?;
753    let target = resolve_target(&request.target, &nodes)?;
754    let (mut items, truncation, possible_edges, unknown_edges) =
755        traverse(request, context, &nodes, &target.node)?;
756    sort_items(&mut items);
757
758    let repositories = aggregate_repositories(&items);
759    let services = aggregate_services(&items, context, &nodes);
760    let contracts = aggregate_contracts(&items, context);
761    let communities = aggregate_communities(&items, context);
762    let local_summaries = summarize_local_enrichment(context);
763    let tests = recommend_tests(&items, context, &nodes);
764    let depth_buckets = if request.options.include_depth_buckets {
765        build_depth_buckets(&items)
766    } else {
767        Vec::new()
768    };
769    let coverage = coverage_summary(
770        &target.node,
771        &items,
772        context,
773        truncation.as_ref(),
774        possible_edges,
775        unknown_edges,
776    );
777    let (risk, risk_score, reasons) = assess_risk(
778        &target.node,
779        &items,
780        &repositories,
781        &services,
782        &contracts,
783        &communities,
784        &tests,
785        context,
786        &coverage,
787        truncation.as_ref(),
788    );
789
790    let page = if request.options.summary_only {
791        Vec::new()
792    } else {
793        items
794            .iter()
795            .skip(request.options.offset.min(items.len()))
796            .take(request.options.limit)
797            .cloned()
798            .collect()
799    };
800    let (direct, transitive, possible, unknown) = split_classifications(page);
801
802    Ok(ImpactReport {
803        risk_model_version: RISK_MODEL_VERSION.to_owned(),
804        target,
805        direction: request.direction,
806        risk,
807        risk_score,
808        reasons,
809        direct_consumers: direct,
810        transitive_consumers: transitive,
811        possibly_affected: possible,
812        unknown_due_to_coverage: unknown,
813        affected_repositories: repositories,
814        affected_services: services,
815        affected_contracts: contracts,
816        affected_communities: communities,
817        local_impact_summaries: local_summaries,
818        test_recommendations: tests,
819        depth_buckets,
820        coverage,
821        truncation,
822    })
823}
824
825fn validate_context<'a>(
826    request: &ImpactRequest,
827    context: &'a ImpactContext,
828) -> Result<BTreeMap<NodeId, &'a Node>, ImpactError> {
829    let options = &request.options;
830    if options.max_depth == 0
831        || options.max_depth > MAX_DEPTH
832        || options.node_limit == 0
833        || options.node_limit > MAX_NODES
834        || options.edge_limit == 0
835        || options.edge_limit > MAX_EDGES
836        || options.limit == 0
837        || options.limit > MAX_LIMIT
838        || options.offset > MAX_OFFSET
839    {
840        return Err(ImpactError::InvalidBounds);
841    }
842    if !options.confirmed_confidence.is_finite()
843        || !(0.0..=1.0).contains(&options.confirmed_confidence)
844    {
845        return Err(ImpactError::InvalidConfirmedConfidence);
846    }
847
848    let mut nodes = BTreeMap::new();
849    for node in &context.nodes {
850        if nodes.insert(node.id.clone(), node).is_some() {
851            return Err(ImpactError::DuplicateNode(node.id.as_str().to_owned()));
852        }
853    }
854    let mut edge_ids = BTreeSet::new();
855    for edge in &context.edges {
856        if !edge_ids.insert(edge.id.clone()) {
857            return Err(ImpactError::DuplicateEdge(edge.id.as_str().to_owned()));
858        }
859        if !edge.confidence.is_finite() || !(0.0..=1.0).contains(&edge.confidence) {
860            return Err(ImpactError::InvalidEdgeConfidence(
861                edge.id.as_str().to_owned(),
862            ));
863        }
864        for endpoint in [&edge.source, &edge.target] {
865            if !nodes.contains_key(endpoint) {
866                return Err(ImpactError::DanglingEdge {
867                    edge: edge.id.as_str().to_owned(),
868                    node: endpoint.as_str().to_owned(),
869                });
870            }
871        }
872    }
873    let mut freshness_repositories = BTreeSet::new();
874    for record in &context.freshness {
875        if !freshness_repositories.insert(&record.repo_id) {
876            return Err(ImpactError::DuplicateFreshness(
877                record.repo_id.as_str().to_owned(),
878            ));
879        }
880    }
881    for (node_id, centrality) in &context.centrality {
882        validate_node_reference(&nodes, node_id, "centrality")?;
883        if !centrality.is_finite() || !(0.0..=1.0).contains(centrality) {
884            return Err(ImpactError::InvalidCentrality(node_id.as_str().to_owned()));
885        }
886    }
887    for assignment in &context.criticality {
888        validate_node_reference(&nodes, &assignment.node_id, "criticality")?;
889        if assignment.evidence.is_empty()
890            || assignment
891                .evidence
892                .iter()
893                .any(|value| value.trim().is_empty())
894        {
895            return Err(ImpactError::CriticalityWithoutEvidence(
896                assignment.node_id.as_str().to_owned(),
897            ));
898        }
899    }
900    for compatibility in &context.compatibility {
901        validate_node_reference(&nodes, &compatibility.contract_node_id, "compatibility")?;
902    }
903    for node_id in &context.public_contracts {
904        validate_node_reference(&nodes, node_id, "public_contracts")?;
905    }
906    for assignment in &context.environments {
907        validate_node_reference(&nodes, &assignment.node_id, "environments")?;
908    }
909    for (member, services) in &context.service_memberships {
910        validate_node_reference(&nodes, member, "service_memberships")?;
911        for service in services {
912            validate_node_reference(&nodes, service, "service_memberships")?;
913        }
914    }
915    Ok(nodes)
916}
917
918fn validate_node_reference(
919    nodes: &BTreeMap<NodeId, &Node>,
920    node_id: &NodeId,
921    context: &'static str,
922) -> Result<(), ImpactError> {
923    if nodes.contains_key(node_id) {
924        Ok(())
925    } else {
926        Err(ImpactError::UnknownContextNode {
927            context,
928            node: node_id.as_str().to_owned(),
929        })
930    }
931}
932
933fn resolve_target(
934    selector: &ImpactTarget,
935    nodes: &BTreeMap<NodeId, &Node>,
936) -> Result<ResolvedTarget, ImpactError> {
937    match selector {
938        ImpactTarget::NodeId { node_id } => nodes
939            .get(node_id)
940            .map(|node| ResolvedTarget {
941                node: (*node).clone(),
942                resolved_by: "node_id".to_owned(),
943            })
944            .ok_or(ImpactError::UnknownTarget),
945        ImpactTarget::StableKey { stable_key } => {
946            let mut matches = nodes.values().filter(|node| node.stable_key == *stable_key);
947            let Some(node) = matches.next() else {
948                return Err(ImpactError::UnknownTarget);
949            };
950            if matches.next().is_some() {
951                return Err(ImpactError::AmbiguousTarget(stable_key.clone()));
952            }
953            Ok(ResolvedTarget {
954                node: (*node).clone(),
955                resolved_by: "stable_key".to_owned(),
956            })
957        }
958    }
959}
960
961#[expect(
962    clippy::too_many_lines,
963    reason = "The bounded BFS state transitions remain together for auditability"
964)]
965fn traverse(
966    request: &ImpactRequest,
967    context: &ImpactContext,
968    nodes: &BTreeMap<NodeId, &Node>,
969    target: &Node,
970) -> Result<(Vec<ImpactItem>, Option<TruncationInfo>, usize, usize), ImpactError> {
971    let adjacency = build_adjacency(&context.edges, request.direction);
972    let mut queue = VecDeque::from([TraversalState {
973        node_id: target.id.clone(),
974        certainty: PathCertainty::Confirmed,
975        path: Vec::new(),
976        evidence: BTreeSet::new(),
977    }]);
978    let mut best = BTreeMap::<NodeId, (PathCertainty, usize)>::new();
979    best.insert(target.id.clone(), (PathCertainty::Confirmed, 0));
980    let mut items = BTreeMap::<NodeId, ImpactItem>::new();
981    let mut examined_edges = 0_usize;
982    let mut possible_edges = 0_usize;
983    let mut unknown_edges = 0_usize;
984    let mut truncation = None;
985
986    while let Some(state) = queue.pop_front() {
987        let depth = state.path.len();
988        let neighbors = adjacency.get(&state.node_id).map_or(&[][..], Vec::as_slice);
989        if depth == request.options.max_depth {
990            if neighbors.iter().any(|entry| {
991                is_propagating(entry.edge.kind)
992                    && !is_structural_direction_pivot(&state.path, entry)
993                    && !state.path.iter().any(|step| step.from == entry.neighbor)
994            }) {
995                truncation.get_or_insert_with(|| TruncationInfo {
996                    bound: "max_depth".to_owned(),
997                    limit: request.options.max_depth,
998                    observed: depth,
999                    explanation: "additional graph relationships exist beyond maximum depth"
1000                        .to_owned(),
1001                });
1002            }
1003            continue;
1004        }
1005        for entry in neighbors {
1006            if !is_propagating(entry.edge.kind) || is_structural_direction_pivot(&state.path, entry)
1007            {
1008                continue;
1009            }
1010            examined_edges = examined_edges.saturating_add(1);
1011            if examined_edges > request.options.edge_limit {
1012                truncation.get_or_insert_with(|| TruncationInfo {
1013                    bound: "edge_limit".to_owned(),
1014                    limit: request.options.edge_limit,
1015                    observed: examined_edges,
1016                    explanation: "edge examination limit stopped impact propagation".to_owned(),
1017                });
1018                break;
1019            }
1020            if entry.neighbor == target.id
1021                || state
1022                    .path
1023                    .iter()
1024                    .any(|step| step.from == entry.neighbor || step.to == entry.neighbor)
1025            {
1026                continue;
1027            }
1028            let edge_certainty = edge_certainty(entry.edge, request.options.confirmed_confidence);
1029            match edge_certainty {
1030                PathCertainty::Confirmed => {}
1031                PathCertainty::Possible => possible_edges = possible_edges.saturating_add(1),
1032                PathCertainty::Unknown => unknown_edges = unknown_edges.saturating_add(1),
1033            }
1034            let certainty = state.certainty.max(edge_certainty);
1035            let next_depth = depth.saturating_add(1);
1036            if best
1037                .get(&entry.neighbor)
1038                .is_some_and(|existing| *existing <= (certainty, next_depth))
1039            {
1040                continue;
1041            }
1042            if !items.contains_key(&entry.neighbor) && items.len() >= request.options.node_limit {
1043                truncation.get_or_insert_with(|| TruncationInfo {
1044                    bound: "node_limit".to_owned(),
1045                    limit: request.options.node_limit,
1046                    observed: items.len().saturating_add(1),
1047                    explanation: "distinct-node limit stopped impact propagation".to_owned(),
1048                });
1049                break;
1050            }
1051            let mut path = state.path.clone();
1052            path.push(ImpactPathStep {
1053                from: state.node_id.clone(),
1054                to: entry.neighbor.clone(),
1055                edge_id: entry.edge.id.clone(),
1056                kind: entry.edge.kind,
1057                reversed: entry.reversed,
1058                confidence: entry.edge.confidence,
1059                status: entry.edge.status,
1060            });
1061            let mut evidence = state.evidence.clone();
1062            evidence.extend(entry.edge.evidence.iter().cloned());
1063            let classification = classify(certainty, next_depth);
1064            let Some(node) = nodes.get(&entry.neighbor) else {
1065                return Err(ImpactError::DanglingEdge {
1066                    edge: entry.edge.id.as_str().to_owned(),
1067                    node: entry.neighbor.as_str().to_owned(),
1068                });
1069            };
1070            best.insert(entry.neighbor.clone(), (certainty, next_depth));
1071            items.insert(
1072                entry.neighbor.clone(),
1073                ImpactItem {
1074                    node: (*node).clone(),
1075                    classification,
1076                    depth: next_depth,
1077                    path: path.clone(),
1078                    evidence: evidence.iter().cloned().collect(),
1079                },
1080            );
1081            queue.push_back(TraversalState {
1082                node_id: entry.neighbor.clone(),
1083                certainty,
1084                path,
1085                evidence,
1086            });
1087        }
1088        if truncation
1089            .as_ref()
1090            .is_some_and(|value| value.bound == "edge_limit" || value.bound == "node_limit")
1091        {
1092            break;
1093        }
1094    }
1095    Ok((
1096        items.into_values().collect(),
1097        truncation,
1098        possible_edges,
1099        unknown_edges,
1100    ))
1101}
1102
1103fn is_structural_direction_pivot(path: &[ImpactPathStep], next: &Adjacency<'_>) -> bool {
1104    path.last().is_some_and(|previous| {
1105        previous.kind == EdgeKind::Contains
1106            && next.edge.kind == EdgeKind::Contains
1107            && previous.reversed != next.reversed
1108    })
1109}
1110
1111fn build_adjacency(
1112    edges: &[Edge],
1113    direction: ImpactDirection,
1114) -> BTreeMap<NodeId, Vec<Adjacency<'_>>> {
1115    let mut adjacency = BTreeMap::<NodeId, Vec<Adjacency<'_>>>::new();
1116    for edge in edges {
1117        if matches!(
1118            direction,
1119            ImpactDirection::Downstream | ImpactDirection::Both
1120        ) {
1121            adjacency
1122                .entry(edge.source.clone())
1123                .or_default()
1124                .push(Adjacency {
1125                    neighbor: edge.target.clone(),
1126                    edge,
1127                    reversed: false,
1128                });
1129        }
1130        if matches!(direction, ImpactDirection::Upstream | ImpactDirection::Both) {
1131            adjacency
1132                .entry(edge.target.clone())
1133                .or_default()
1134                .push(Adjacency {
1135                    neighbor: edge.source.clone(),
1136                    edge,
1137                    reversed: true,
1138                });
1139        }
1140    }
1141    for entries in adjacency.values_mut() {
1142        entries.sort_by(|left, right| {
1143            left.neighbor
1144                .cmp(&right.neighbor)
1145                .then_with(|| left.edge.id.cmp(&right.edge.id))
1146                .then_with(|| left.reversed.cmp(&right.reversed))
1147        });
1148    }
1149    adjacency
1150}
1151
1152fn is_propagating(kind: EdgeKind) -> bool {
1153    !matches!(
1154        kind,
1155        EdgeKind::Validates
1156            | EdgeKind::OwnedBy
1157            | EdgeKind::Documents
1158            | EdgeKind::MemberOf
1159            | EdgeKind::Precedes
1160            | EdgeKind::Reverts
1161            | EdgeKind::CompatibleWith
1162    )
1163}
1164
1165fn edge_certainty(edge: &Edge, confirmed_confidence: f32) -> PathCertainty {
1166    match edge.status {
1167        EpistemicStatus::Confirmed if edge.confidence >= confirmed_confidence => {
1168            PathCertainty::Confirmed
1169        }
1170        EpistemicStatus::Confirmed | EpistemicStatus::Inferred | EpistemicStatus::Ambiguous => {
1171            PathCertainty::Possible
1172        }
1173        EpistemicStatus::Stale | EpistemicStatus::Incomplete => PathCertainty::Unknown,
1174    }
1175}
1176
1177fn classify(certainty: PathCertainty, depth: usize) -> ImpactClassification {
1178    match (certainty, depth) {
1179        (PathCertainty::Confirmed, 1) => ImpactClassification::DirectlyDependent,
1180        (PathCertainty::Confirmed, _) => ImpactClassification::TransitivelyAffected,
1181        (PathCertainty::Possible, _) => ImpactClassification::PossiblyAffected,
1182        (PathCertainty::Unknown, _) => ImpactClassification::UnknownDueToCoverage,
1183    }
1184}
1185
1186fn classification_rank(classification: ImpactClassification) -> u8 {
1187    match classification {
1188        ImpactClassification::DirectlyDependent => 0,
1189        ImpactClassification::TransitivelyAffected => 1,
1190        ImpactClassification::PossiblyAffected => 2,
1191        ImpactClassification::UnknownDueToCoverage => 3,
1192    }
1193}
1194
1195fn stronger(left: ImpactClassification, right: ImpactClassification) -> ImpactClassification {
1196    if classification_rank(left) <= classification_rank(right) {
1197        left
1198    } else {
1199        right
1200    }
1201}
1202
1203fn sort_items(items: &mut [ImpactItem]) {
1204    items.sort_by(|left, right| {
1205        classification_rank(left.classification)
1206            .cmp(&classification_rank(right.classification))
1207            .then_with(|| left.depth.cmp(&right.depth))
1208            .then_with(|| left.node.repo_id.cmp(&right.node.repo_id))
1209            .then_with(|| left.node.stable_key.cmp(&right.node.stable_key))
1210            .then_with(|| left.node.id.cmp(&right.node.id))
1211            .then_with(|| path_key(&left.path).cmp(&path_key(&right.path)))
1212    });
1213}
1214
1215fn path_key(path: &[ImpactPathStep]) -> Vec<(&str, bool)> {
1216    path.iter()
1217        .map(|step| (step.edge_id.as_str(), step.reversed))
1218        .collect()
1219}
1220
1221fn aggregate_repositories(items: &[ImpactItem]) -> Vec<RepositoryImpact> {
1222    let mut aggregates = BTreeMap::<RepoId, Aggregate>::new();
1223    for item in items {
1224        let Some(repo_id) = &item.node.repo_id else {
1225            continue;
1226        };
1227        update_aggregate(&mut aggregates, repo_id.clone(), item);
1228    }
1229    aggregates
1230        .into_iter()
1231        .map(|(repo_id, aggregate)| RepositoryImpact {
1232            repo_id,
1233            classification: aggregate.classification,
1234            minimum_depth: aggregate.minimum_depth,
1235            affected_nodes: aggregate.affected_nodes,
1236        })
1237        .collect()
1238}
1239
1240fn aggregate_services(
1241    items: &[ImpactItem],
1242    context: &ImpactContext,
1243    nodes: &BTreeMap<NodeId, &Node>,
1244) -> Vec<ServiceImpact> {
1245    let mut aggregates = BTreeMap::<NodeId, Aggregate>::new();
1246    for item in items {
1247        if item.node.kind == NodeKind::Service {
1248            update_aggregate(&mut aggregates, item.node.id.clone(), item);
1249        }
1250        if let Some(service_ids) = context.service_memberships.get(&item.node.id) {
1251            for service_id in service_ids {
1252                update_aggregate(&mut aggregates, service_id.clone(), item);
1253            }
1254        }
1255    }
1256    aggregates
1257        .into_iter()
1258        .filter_map(|(service_id, aggregate)| {
1259            nodes.get(&service_id).map(|service| ServiceImpact {
1260                service: (*service).clone(),
1261                classification: aggregate.classification,
1262                minimum_depth: aggregate.minimum_depth,
1263                affected_nodes: aggregate.affected_nodes,
1264            })
1265        })
1266        .collect()
1267}
1268
1269fn update_aggregate<K: Ord>(aggregates: &mut BTreeMap<K, Aggregate>, key: K, item: &ImpactItem) {
1270    aggregates
1271        .entry(key)
1272        .and_modify(|aggregate| {
1273            aggregate.classification = stronger(aggregate.classification, item.classification);
1274            aggregate.minimum_depth = aggregate.minimum_depth.min(item.depth);
1275            aggregate.affected_nodes = aggregate.affected_nodes.saturating_add(1);
1276        })
1277        .or_insert(Aggregate {
1278            classification: item.classification,
1279            minimum_depth: item.depth,
1280            affected_nodes: 1,
1281        });
1282}
1283
1284fn aggregate_contracts(items: &[ImpactItem], context: &ImpactContext) -> Vec<ContractImpact> {
1285    let public = context.public_contracts.iter().collect::<BTreeSet<_>>();
1286    items
1287        .iter()
1288        .filter(|item| is_contract(item.node.kind))
1289        .map(|item| ContractImpact {
1290            contract: item.node.clone(),
1291            classification: item.classification,
1292            depth: item.depth,
1293            public: public.contains(&item.node.id),
1294        })
1295        .collect()
1296}
1297
1298fn is_contract(kind: NodeKind) -> bool {
1299    matches!(
1300        kind,
1301        NodeKind::HttpOperation
1302            | NodeKind::GraphqlOperation
1303            | NodeKind::RpcMethod
1304            | NodeKind::EventChannel
1305            | NodeKind::EventSchema
1306            | NodeKind::DatabaseTable
1307            | NodeKind::DatabaseColumn
1308            | NodeKind::ConfigKey
1309    )
1310}
1311
1312fn aggregate_communities(items: &[ImpactItem], context: &ImpactContext) -> Vec<CommunityImpact> {
1313    let Some(snapshot) = &context.communities else {
1314        return Vec::new();
1315    };
1316    let impacted = items
1317        .iter()
1318        .map(|item| (&item.node.id, item))
1319        .collect::<BTreeMap<_, _>>();
1320    let mut result = Vec::new();
1321    for community in &snapshot.communities {
1322        let mut aggregate = None::<Aggregate>;
1323        for member in &community.members {
1324            if let Some(item) = impacted.get(member) {
1325                let current = aggregate.get_or_insert(Aggregate {
1326                    classification: item.classification,
1327                    minimum_depth: item.depth,
1328                    affected_nodes: 0,
1329                });
1330                current.classification = stronger(current.classification, item.classification);
1331                current.minimum_depth = current.minimum_depth.min(item.depth);
1332                current.affected_nodes = current.affected_nodes.saturating_add(1);
1333            }
1334        }
1335        if let Some(aggregate) = aggregate {
1336            result.push(CommunityImpact {
1337                community_id: community.id.clone(),
1338                label: community.label.clone(),
1339                classification: aggregate.classification,
1340                affected_members: aggregate.affected_nodes,
1341                coupling: community.metrics.coupling,
1342                limitations: community.limitations.clone(),
1343            });
1344        }
1345    }
1346    result.sort_by(|left, right| left.community_id.cmp(&right.community_id));
1347    result
1348}
1349
1350fn summarize_local_enrichment(context: &ImpactContext) -> Vec<LocalImpactSummary> {
1351    let mut summaries = context
1352        .local_enrichment
1353        .iter()
1354        .map(|input| LocalImpactSummary {
1355            repo_id: input.repo_id.clone(),
1356            anchor: input.anchor.clone(),
1357            status: input.status,
1358            affected_count: input.affected.len(),
1359            maximum_depth: input
1360                .affected
1361                .iter()
1362                .map(|item| item.depth)
1363                .max()
1364                .unwrap_or(0),
1365            truncated: input.truncated,
1366            degradations: sorted_unique(input.degradations.clone()),
1367        })
1368        .collect::<Vec<_>>();
1369    summaries.sort_by(|left, right| {
1370        left.repo_id
1371            .cmp(&right.repo_id)
1372            .then_with(|| left.anchor.cmp(&right.anchor))
1373    });
1374    summaries
1375}
1376
1377fn recommend_tests(
1378    items: &[ImpactItem],
1379    context: &ImpactContext,
1380    nodes: &BTreeMap<NodeId, &Node>,
1381) -> Vec<TestRecommendation> {
1382    let impacted = items
1383        .iter()
1384        .map(|item| (&item.node.id, item))
1385        .collect::<BTreeMap<_, _>>();
1386    let mut recommendations = Vec::new();
1387    for edge in &context.edges {
1388        if edge.kind != EdgeKind::Validates {
1389            continue;
1390        }
1391        let (test_id, validated_id) = if nodes
1392            .get(&edge.source)
1393            .is_some_and(|node| node.kind == NodeKind::TestCase)
1394        {
1395            (&edge.source, &edge.target)
1396        } else if nodes
1397            .get(&edge.target)
1398            .is_some_and(|node| node.kind == NodeKind::TestCase)
1399        {
1400            (&edge.target, &edge.source)
1401        } else {
1402            continue;
1403        };
1404        let Some(item) = impacted.get(validated_id) else {
1405            continue;
1406        };
1407        let Some(test) = nodes.get(test_id) else {
1408            continue;
1409        };
1410        recommendations.push(TestRecommendation {
1411            test_node_id: Some(test.id.clone()),
1412            test: test.label.clone(),
1413            repo_id: test.repo_id.clone(),
1414            source: TestRecommendationSource::Graph,
1415            rank: 0,
1416            reasons: vec![format!(
1417                "validates impacted node `{}` at depth {}",
1418                item.node.stable_key, item.depth
1419            )],
1420            owners: owners_for(&test.id, validated_id, context, nodes),
1421            recommended_commands: commands_for(test.repo_id.as_ref(), context),
1422        });
1423    }
1424    for local in &context.local_enrichment {
1425        for test in &local.affected_tests {
1426            recommendations.push(TestRecommendation {
1427                test_node_id: None,
1428                test: test.clone(),
1429                repo_id: Some(local.repo_id.clone()),
1430                source: TestRecommendationSource::LocalEnrichment,
1431                rank: 0,
1432                reasons: vec![format!(
1433                    "optional local enrichment for anchor `{}` reported this test",
1434                    local.anchor
1435                )],
1436                owners: Vec::new(),
1437                recommended_commands: commands_for(Some(&local.repo_id), context),
1438            });
1439        }
1440    }
1441    recommendations.sort_by(|left, right| {
1442        test_source_rank(left.source)
1443            .cmp(&test_source_rank(right.source))
1444            .then_with(|| left.repo_id.cmp(&right.repo_id))
1445            .then_with(|| left.test.cmp(&right.test))
1446            .then_with(|| left.test_node_id.cmp(&right.test_node_id))
1447    });
1448    recommendations.dedup_by(|left, right| {
1449        left.test_node_id == right.test_node_id
1450            && left.repo_id == right.repo_id
1451            && left.test == right.test
1452    });
1453    for (index, recommendation) in recommendations.iter_mut().enumerate() {
1454        recommendation.rank = index.saturating_add(1);
1455    }
1456    recommendations
1457}
1458
1459fn test_source_rank(source: TestRecommendationSource) -> u8 {
1460    match source {
1461        TestRecommendationSource::Graph => 0,
1462        TestRecommendationSource::LocalEnrichment => 1,
1463    }
1464}
1465
1466fn owners_for(
1467    test_id: &NodeId,
1468    validated_id: &NodeId,
1469    context: &ImpactContext,
1470    nodes: &BTreeMap<NodeId, &Node>,
1471) -> Vec<Node> {
1472    let mut owner_ids = BTreeSet::new();
1473    for edge in &context.edges {
1474        if edge.kind == EdgeKind::OwnedBy
1475            && (&edge.source == test_id || &edge.source == validated_id)
1476            && nodes
1477                .get(&edge.target)
1478                .is_some_and(|node| node.kind == NodeKind::Owner)
1479        {
1480            owner_ids.insert(edge.target.clone());
1481        }
1482    }
1483    owner_ids
1484        .iter()
1485        .filter_map(|owner_id| nodes.get(owner_id).map(|node| (*node).clone()))
1486        .collect()
1487}
1488
1489fn commands_for(repo_id: Option<&RepoId>, context: &ImpactContext) -> Vec<String> {
1490    let mut commands = context
1491        .recommended_commands
1492        .iter()
1493        .filter(|command| repo_id.is_some_and(|repo| repo == &command.repo_id))
1494        .map(|command| command.command.clone())
1495        .collect::<Vec<_>>();
1496    commands.sort();
1497    commands.dedup();
1498    commands
1499}
1500
1501fn build_depth_buckets(items: &[ImpactItem]) -> Vec<ImpactDepthBucket> {
1502    let mut buckets = BTreeMap::<usize, ImpactDepthBucket>::new();
1503    for item in items {
1504        let bucket = buckets.entry(item.depth).or_insert(ImpactDepthBucket {
1505            depth: item.depth,
1506            directly_dependent: 0,
1507            transitively_affected: 0,
1508            possibly_affected: 0,
1509            unknown_due_to_coverage: 0,
1510        });
1511        match item.classification {
1512            ImpactClassification::DirectlyDependent => {
1513                bucket.directly_dependent = bucket.directly_dependent.saturating_add(1);
1514            }
1515            ImpactClassification::TransitivelyAffected => {
1516                bucket.transitively_affected = bucket.transitively_affected.saturating_add(1);
1517            }
1518            ImpactClassification::PossiblyAffected => {
1519                bucket.possibly_affected = bucket.possibly_affected.saturating_add(1);
1520            }
1521            ImpactClassification::UnknownDueToCoverage => {
1522                bucket.unknown_due_to_coverage = bucket.unknown_due_to_coverage.saturating_add(1);
1523            }
1524        }
1525    }
1526    buckets.into_values().collect()
1527}
1528
1529#[expect(
1530    clippy::too_many_lines,
1531    reason = "Coverage states and their paired remediations remain visibly exhaustive"
1532)]
1533fn coverage_summary(
1534    target: &Node,
1535    items: &[ImpactItem],
1536    context: &ImpactContext,
1537    truncation: Option<&TruncationInfo>,
1538    possible_edges: usize,
1539    unknown_edges: usize,
1540) -> CoverageSummary {
1541    let mut relevant = items
1542        .iter()
1543        .filter_map(|item| item.node.repo_id.clone())
1544        .collect::<BTreeSet<_>>();
1545    relevant.extend(target.repo_id.iter().cloned());
1546    let freshness = context
1547        .freshness
1548        .iter()
1549        .map(|record| (&record.repo_id, record.state))
1550        .collect::<BTreeMap<_, _>>();
1551    let mut fresh = Vec::new();
1552    let mut stale = Vec::new();
1553    let mut partial = Vec::new();
1554    let mut unavailable = Vec::new();
1555    let mut missing = Vec::new();
1556    for repo_id in &relevant {
1557        match freshness.get(repo_id) {
1558            Some(RepoFreshnessState::Fresh) => fresh.push(repo_id.clone()),
1559            Some(
1560                RepoFreshnessState::WorkingTreeChanged
1561                | RepoFreshnessState::CommitsBehind
1562                | RepoFreshnessState::ConfigChanged
1563                | RepoFreshnessState::ExtractorChanged
1564                | RepoFreshnessState::CodegraphPending,
1565            ) => stale.push(repo_id.clone()),
1566            Some(RepoFreshnessState::Partial) => partial.push(repo_id.clone()),
1567            Some(RepoFreshnessState::Unavailable | RepoFreshnessState::Corrupt) => {
1568                unavailable.push(repo_id.clone());
1569            }
1570            Some(RepoFreshnessState::Unknown) | None => missing.push(repo_id.clone()),
1571        }
1572    }
1573    let mut gaps = context.coverage_gaps.clone();
1574    let mut remediation = Vec::new();
1575    if !context.coverage_gaps.is_empty() {
1576        remediation.push("resolve each caller-supplied coverage gap and rerun analysis".to_owned());
1577    }
1578    if !context.graph_complete {
1579        gaps.push("federated graph extraction or linking is incomplete".to_owned());
1580        remediation.push("complete a fresh workspace scan and relink the graph".to_owned());
1581    }
1582    if !stale.is_empty() {
1583        gaps.push("one or more relevant repositories are stale".to_owned());
1584        remediation.push("rescan stale repositories at their current revisions".to_owned());
1585    }
1586    if !partial.is_empty() {
1587        gaps.push("one or more relevant repositories have partial coverage".to_owned());
1588        remediation.push("resolve extractor limitations and complete partial scans".to_owned());
1589    }
1590    if !unavailable.is_empty() {
1591        gaps.push("one or more relevant repositories are unavailable or corrupt".to_owned());
1592        remediation.push("restore unavailable repositories or valid graph snapshots".to_owned());
1593    }
1594    if !missing.is_empty() {
1595        gaps.push("freshness is missing or unknown for relevant repositories".to_owned());
1596        remediation.push("record current freshness for every relevant repository".to_owned());
1597    }
1598    if possible_edges > 0 {
1599        gaps.push(
1600            "candidate, inferred, ambiguous, or low-confidence relationships were used".to_owned(),
1601        );
1602        remediation.push("corroborate candidate relationships with direct evidence".to_owned());
1603    }
1604    if unknown_edges > 0 {
1605        gaps.push("stale or incomplete relationships were used".to_owned());
1606        remediation
1607            .push("refresh or complete evidence for coverage-unknown relationships".to_owned());
1608    }
1609    let impacted_ids = items
1610        .iter()
1611        .map(|item| &item.node.id)
1612        .chain(std::iter::once(&target.id))
1613        .collect::<BTreeSet<_>>();
1614    let unknown_compatibility = context.compatibility.iter().filter(|input| {
1615        impacted_ids.contains(&input.contract_node_id)
1616            && input.status == ImpactCompatibilityStatus::Unknown
1617    });
1618    let mut compatibility_unknown = false;
1619    for input in unknown_compatibility {
1620        compatibility_unknown = true;
1621        gaps.push(format!(
1622            "compatibility is unknown for contract node `{}`",
1623            input.contract_node_id.as_str()
1624        ));
1625        remediation.extend(input.recommended_validations.iter().cloned());
1626    }
1627    for local in &context.local_enrichment {
1628        if local.status != LocalEnrichmentStatus::Available || local.truncated {
1629            gaps.push(format!(
1630                "local enrichment for repository `{}` is {:?}{}",
1631                local.repo_id.as_str(),
1632                local.status,
1633                if local.truncated {
1634                    " and truncated"
1635                } else {
1636                    ""
1637                }
1638            ));
1639            remediation.extend(local.degradations.iter().cloned());
1640        }
1641    }
1642    if truncation.is_some() {
1643        gaps.push("configured traversal bounds truncated impact analysis".to_owned());
1644        remediation.push("increase impact bounds or narrow the target scope".to_owned());
1645    }
1646    gaps = sorted_unique(gaps);
1647    remediation = sorted_unique(remediation);
1648    CoverageSummary {
1649        sufficient_for_score: context.graph_complete
1650            && stale.is_empty()
1651            && partial.is_empty()
1652            && unavailable.is_empty()
1653            && missing.is_empty()
1654            && possible_edges == 0
1655            && unknown_edges == 0
1656            && !compatibility_unknown
1657            && truncation.is_none()
1658            && context
1659                .local_enrichment
1660                .iter()
1661                .all(|local| local.status == LocalEnrichmentStatus::Available && !local.truncated)
1662            && context.coverage_gaps.is_empty(),
1663        relevant_repositories: relevant.into_iter().collect(),
1664        fresh_repositories: fresh,
1665        stale_repositories: stale,
1666        partial_repositories: partial,
1667        unavailable_repositories: unavailable,
1668        missing_repositories: missing,
1669        possible_edges,
1670        unknown_edges,
1671        gaps,
1672        remediation,
1673        total_items: items.len(),
1674    }
1675}
1676
1677#[expect(
1678    clippy::too_many_arguments,
1679    clippy::too_many_lines,
1680    reason = "Risk inputs stay explicit to make every scored dimension auditable"
1681)]
1682fn assess_risk(
1683    target: &Node,
1684    items: &[ImpactItem],
1685    repositories: &[RepositoryImpact],
1686    services: &[ServiceImpact],
1687    contracts: &[ContractImpact],
1688    communities: &[CommunityImpact],
1689    tests: &[TestRecommendation],
1690    context: &ImpactContext,
1691    coverage: &CoverageSummary,
1692    truncation: Option<&TruncationInfo>,
1693) -> (RiskLevel, Option<f32>, Vec<RiskFactor>) {
1694    let impacted_ids = items
1695        .iter()
1696        .map(|item| &item.node.id)
1697        .chain(std::iter::once(&target.id))
1698        .collect::<BTreeSet<_>>();
1699    let direct_count = items
1700        .iter()
1701        .filter(|item| item.classification == ImpactClassification::DirectlyDependent)
1702        .count();
1703    let transitive_count = items
1704        .iter()
1705        .filter(|item| item.classification == ImpactClassification::TransitivelyAffected)
1706        .count();
1707    let mut factors = Vec::new();
1708    if direct_count > 0 {
1709        push_factor(
1710            &mut factors,
1711            "direct_consumers",
1712            usize_to_f32(direct_count).mul_add(4.0, 0.0).min(24.0),
1713            format!("{direct_count} confirmed direct dependents"),
1714            direct_evidence(items),
1715        );
1716    }
1717    if transitive_count > 0 {
1718        push_factor(
1719            &mut factors,
1720            "transitive_fanout",
1721            usize_to_f32(transitive_count).mul_add(1.5, 0.0).min(15.0),
1722            format!("{transitive_count} confirmed transitive impacts"),
1723            Vec::new(),
1724        );
1725    }
1726    let mut repository_ids = repositories
1727        .iter()
1728        .map(|impact| impact.repo_id.clone())
1729        .collect::<BTreeSet<_>>();
1730    repository_ids.extend(target.repo_id.iter().cloned());
1731    if repository_ids.len() > 1 {
1732        push_factor(
1733            &mut factors,
1734            "cross_repository_count",
1735            usize_to_f32(repository_ids.len().saturating_sub(1))
1736                .mul_add(4.0, 0.0)
1737                .min(16.0),
1738            format!("impact spans {} repositories", repository_ids.len()),
1739            repository_ids
1740                .iter()
1741                .map(|repo_id| repo_id.as_str().to_owned())
1742                .collect(),
1743        );
1744    }
1745    if !services.is_empty() {
1746        push_factor(
1747            &mut factors,
1748            "service_impact",
1749            usize_to_f32(services.len()).mul_add(2.0, 0.0).min(10.0),
1750            format!("impact reaches {} services", services.len()),
1751            services
1752                .iter()
1753                .map(|impact| impact.service.stable_key.clone())
1754                .collect(),
1755        );
1756    }
1757    let public_contracts = contracts.iter().filter(|contract| contract.public).count()
1758        + usize::from(context.public_contracts.contains(&target.id));
1759    if public_contracts > 0 {
1760        push_factor(
1761            &mut factors,
1762            "public_contract",
1763            12.0,
1764            format!("{public_contracts} explicitly public contracts are involved"),
1765            contracts
1766                .iter()
1767                .filter(|contract| contract.public)
1768                .map(|contract| contract.contract.stable_key.clone())
1769                .collect(),
1770        );
1771    }
1772    add_compatibility_factors(&mut factors, &impacted_ids, context);
1773    if let Some(centrality) = context
1774        .centrality
1775        .get(&target.id)
1776        .filter(|value| **value >= 0.75)
1777    {
1778        push_factor(
1779            &mut factors,
1780            "centrality",
1781            *centrality * 12.0,
1782            format!("target centrality is {centrality:.3}"),
1783            vec![target.id.as_str().to_owned()],
1784        );
1785    }
1786    if !communities.is_empty() {
1787        let cross_edges = communities
1788            .iter()
1789            .filter(|community| community.coupling > 0.0)
1790            .count();
1791        if cross_edges > 0 {
1792            push_factor(
1793                &mut factors,
1794                "community_process_fanout",
1795                usize_to_f32(cross_edges).mul_add(3.0, 0.0).min(9.0),
1796                format!("{cross_edges} affected communities cross structural boundaries"),
1797                communities
1798                    .iter()
1799                    .map(|community| community.community_id.as_str().to_owned())
1800                    .collect(),
1801            );
1802        }
1803    }
1804    add_criticality_factors(&mut factors, &impacted_ids, context);
1805    if tests.is_empty() && !items.is_empty() {
1806        push_factor(
1807            &mut factors,
1808            "missing_tests",
1809            10.0,
1810            "no linked or locally supplied affected tests were found".to_owned(),
1811            Vec::new(),
1812        );
1813    }
1814    let owners = owner_count(&impacted_ids, context);
1815    if owners == 0 && !items.is_empty() {
1816        push_factor(
1817            &mut factors,
1818            "missing_owners",
1819            8.0,
1820            "no Owner node is linked by OwnedBy to an impacted node".to_owned(),
1821            Vec::new(),
1822        );
1823    }
1824    let environments = context
1825        .environments
1826        .iter()
1827        .filter(|assignment| impacted_ids.contains(&assignment.node_id))
1828        .map(|assignment| assignment.environment.as_str())
1829        .collect::<BTreeSet<_>>();
1830    if environments.len() > 1 {
1831        push_factor(
1832            &mut factors,
1833            "cross_environment",
1834            10.0,
1835            format!("impact spans {} explicit environments", environments.len()),
1836            environments.into_iter().map(str::to_owned).collect(),
1837        );
1838    }
1839    if !coverage.sufficient_for_score {
1840        push_factor(
1841            &mut factors,
1842            "coverage_unknown",
1843            0.0,
1844            "coverage is insufficient for a numeric risk conclusion".to_owned(),
1845            coverage.gaps.clone(),
1846        );
1847    }
1848    if let Some(info) = truncation {
1849        push_factor(
1850            &mut factors,
1851            "truncated",
1852            0.0,
1853            info.explanation.clone(),
1854            vec![format!("{}={}", info.bound, info.limit)],
1855        );
1856    }
1857    factors.sort_by(|left, right| {
1858        right
1859            .weight
1860            .partial_cmp(&left.weight)
1861            .unwrap_or(Ordering::Equal)
1862            .then_with(|| left.code.cmp(&right.code))
1863            .then_with(|| left.explanation.cmp(&right.explanation))
1864    });
1865    if !coverage.sufficient_for_score {
1866        return (RiskLevel::Unknown, None, factors);
1867    }
1868    let score = factors
1869        .iter()
1870        .map(|factor| factor.weight)
1871        .sum::<f32>()
1872        .clamp(1.0, 100.0);
1873    let explicit_critical = factors.iter().any(|factor| {
1874        matches!(
1875            factor.code.as_str(),
1876            "critical_tag" | "security_tag" | "payment_tag" | "data_boundary_tag"
1877        ) && !factor.evidence.is_empty()
1878    });
1879    let level = if score >= 85.0 && explicit_critical {
1880        RiskLevel::Critical
1881    } else if score >= 50.0 {
1882        RiskLevel::High
1883    } else if score >= 25.0 {
1884        RiskLevel::Medium
1885    } else {
1886        RiskLevel::Low
1887    };
1888    (level, Some(score), factors)
1889}
1890
1891fn add_compatibility_factors(
1892    factors: &mut Vec<RiskFactor>,
1893    impacted_ids: &BTreeSet<&NodeId>,
1894    context: &ImpactContext,
1895) {
1896    for input in &context.compatibility {
1897        if !impacted_ids.contains(&input.contract_node_id) {
1898            continue;
1899        }
1900        match input.status {
1901            ImpactCompatibilityStatus::Breaking => push_factor(
1902                factors,
1903                "breaking_compatibility",
1904                30.0,
1905                "a compatibility engine reported a breaking contract change".to_owned(),
1906                input.evidence.clone(),
1907            ),
1908            ImpactCompatibilityStatus::PotentiallyBreaking => push_factor(
1909                factors,
1910                "potentially_breaking_compatibility",
1911                18.0,
1912                "a compatibility engine reported a potentially breaking change".to_owned(),
1913                input.evidence.clone(),
1914            ),
1915            ImpactCompatibilityStatus::Compatible => {}
1916            ImpactCompatibilityStatus::Unknown => push_factor(
1917                factors,
1918                "compatibility_unknown",
1919                0.0,
1920                "compatibility coverage is unknown".to_owned(),
1921                input
1922                    .evidence
1923                    .iter()
1924                    .chain(input.recommended_validations.iter())
1925                    .cloned()
1926                    .collect(),
1927            ),
1928        }
1929    }
1930}
1931
1932fn add_criticality_factors(
1933    factors: &mut Vec<RiskFactor>,
1934    impacted_ids: &BTreeSet<&NodeId>,
1935    context: &ImpactContext,
1936) {
1937    for assignment in &context.criticality {
1938        if !impacted_ids.contains(&assignment.node_id) {
1939            continue;
1940        }
1941        let (code, weight) = match assignment.tag {
1942            CriticalityTag::Critical => ("critical_tag", 55.0),
1943            CriticalityTag::Authentication => ("authentication_tag", 35.0),
1944            CriticalityTag::Security => ("security_tag", 50.0),
1945            CriticalityTag::Payment => ("payment_tag", 50.0),
1946            CriticalityTag::DataBoundary => ("data_boundary_tag", 45.0),
1947        };
1948        push_factor(
1949            factors,
1950            code,
1951            weight,
1952            format!(
1953                "explicit {:?} tag applies to impacted node `{}`",
1954                assignment.tag,
1955                assignment.node_id.as_str()
1956            ),
1957            assignment.evidence.clone(),
1958        );
1959    }
1960}
1961
1962fn owner_count(impacted_ids: &BTreeSet<&NodeId>, context: &ImpactContext) -> usize {
1963    context
1964        .edges
1965        .iter()
1966        .filter(|edge| edge.kind == EdgeKind::OwnedBy && impacted_ids.contains(&edge.source))
1967        .map(|edge| &edge.target)
1968        .collect::<BTreeSet<_>>()
1969        .len()
1970}
1971
1972fn direct_evidence(items: &[ImpactItem]) -> Vec<String> {
1973    let mut evidence = items
1974        .iter()
1975        .filter(|item| item.classification == ImpactClassification::DirectlyDependent)
1976        .flat_map(|item| item.evidence.iter().map(|id| id.as_str().to_owned()))
1977        .collect::<Vec<_>>();
1978    evidence.sort();
1979    evidence.dedup();
1980    evidence
1981}
1982
1983fn push_factor(
1984    factors: &mut Vec<RiskFactor>,
1985    code: &str,
1986    weight: f32,
1987    explanation: String,
1988    evidence: Vec<String>,
1989) {
1990    factors.push(RiskFactor {
1991        code: code.to_owned(),
1992        weight,
1993        explanation,
1994        evidence: sorted_unique(evidence),
1995    });
1996}
1997
1998fn usize_to_f32(value: usize) -> f32 {
1999    u16::try_from(value).map_or(f32::from(u16::MAX), f32::from)
2000}
2001
2002fn split_classifications(
2003    items: Vec<ImpactItem>,
2004) -> (
2005    Vec<ImpactItem>,
2006    Vec<ImpactItem>,
2007    Vec<ImpactItem>,
2008    Vec<ImpactItem>,
2009) {
2010    let mut direct = Vec::new();
2011    let mut transitive = Vec::new();
2012    let mut possible = Vec::new();
2013    let mut unknown = Vec::new();
2014    for item in items {
2015        match item.classification {
2016            ImpactClassification::DirectlyDependent => direct.push(item),
2017            ImpactClassification::TransitivelyAffected => transitive.push(item),
2018            ImpactClassification::PossiblyAffected => possible.push(item),
2019            ImpactClassification::UnknownDueToCoverage => unknown.push(item),
2020        }
2021    }
2022    (direct, transitive, possible, unknown)
2023}
2024
2025fn sorted_unique(mut values: Vec<String>) -> Vec<String> {
2026    values.sort();
2027    values.dedup();
2028    values
2029}
2030
2031#[cfg(test)]
2032mod tests {
2033    use code_system_graph_model::{CheckoutId, Community, CommunityConfig, CommunityMetrics};
2034
2035    use super::*;
2036
2037    fn node(id: &str, kind: NodeKind, repo: &str) -> Node {
2038        Node {
2039            id: NodeId::new(id),
2040            kind,
2041            repo_id: Some(RepoId::new(repo)),
2042            stable_key: format!("{repo}:{id}"),
2043            label: id.to_owned(),
2044        }
2045    }
2046
2047    fn edge(id: &str, source: &str, target: &str) -> Edge {
2048        Edge {
2049            id: EdgeId::new(id),
2050            source: NodeId::new(source),
2051            target: NodeId::new(target),
2052            kind: EdgeKind::Consumes,
2053            confidence: 1.0,
2054            status: EpistemicStatus::Confirmed,
2055            evidence: vec![EvidenceId::new(format!("e-{id}"))],
2056        }
2057    }
2058
2059    fn freshness(repo: &str, state: RepoFreshnessState) -> RepoFreshness {
2060        RepoFreshness {
2061            repo_id: RepoId::new(repo),
2062            checkout_id: CheckoutId::new(format!("checkout-{repo}")),
2063            head_commit: Some("abc".to_owned()),
2064            manifest_hash: "manifest".to_owned(),
2065            state,
2066            reason: None,
2067        }
2068    }
2069
2070    fn context(nodes: Vec<Node>, edges: Vec<Edge>) -> ImpactContext {
2071        let repos = nodes
2072            .iter()
2073            .filter_map(|item| item.repo_id.clone())
2074            .collect::<BTreeSet<_>>();
2075        ImpactContext {
2076            nodes,
2077            edges,
2078            communities: None,
2079            freshness: repos
2080                .iter()
2081                .map(|repo| freshness(repo.as_str(), RepoFreshnessState::Fresh))
2082                .collect(),
2083            compatibility: Vec::new(),
2084            local_enrichment: Vec::new(),
2085            public_contracts: Vec::new(),
2086            criticality: Vec::new(),
2087            centrality: BTreeMap::new(),
2088            service_memberships: BTreeMap::new(),
2089            environments: Vec::new(),
2090            recommended_commands: Vec::new(),
2091            graph_complete: true,
2092            coverage_gaps: Vec::new(),
2093        }
2094    }
2095
2096    fn request(target: &str, direction: ImpactDirection) -> ImpactRequest {
2097        ImpactRequest {
2098            target: ImpactTarget::NodeId {
2099                node_id: NodeId::new(target),
2100            },
2101            direction,
2102            options: ImpactOptions::default(),
2103        }
2104    }
2105
2106    fn analyze(context: &ImpactContext, direction: ImpactDirection) -> ImpactReport {
2107        analyze_impact(&request("target", direction), context).expect("analysis should succeed")
2108    }
2109
2110    #[test]
2111    fn breaking_direct_impact_should_raise_high_risk() {
2112        let mut context = context(
2113            vec![
2114                node("consumer", NodeKind::Service, "a"),
2115                node("target", NodeKind::HttpOperation, "b"),
2116            ],
2117            vec![edge("direct", "consumer", "target")],
2118        );
2119        context.compatibility.push(CompatibilityInput {
2120            contract_node_id: NodeId::new("target"),
2121            status: ImpactCompatibilityStatus::Breaking,
2122            evidence: vec!["http.required_parameter_added".to_owned()],
2123            recommended_validations: Vec::new(),
2124        });
2125        context.public_contracts.push(NodeId::new("target"));
2126
2127        let report = analyze(&context, ImpactDirection::Upstream);
2128
2129        assert_eq!(report.risk, RiskLevel::High);
2130    }
2131
2132    #[test]
2133    fn breaking_transitive_path_should_remain_confirmed() {
2134        let context = context(
2135            vec![
2136                node("far", NodeKind::Service, "a"),
2137                node("near", NodeKind::Service, "b"),
2138                node("target", NodeKind::HttpOperation, "c"),
2139            ],
2140            vec![edge("one", "near", "target"), edge("two", "far", "near")],
2141        );
2142
2143        let report = analyze(&context, ImpactDirection::Upstream);
2144
2145        assert_eq!(report.transitive_consumers[0].node.id.as_str(), "far");
2146    }
2147
2148    #[test]
2149    fn stale_freshness_should_prevent_false_safe_score() {
2150        let mut context = context(
2151            vec![
2152                node("consumer", NodeKind::Service, "a"),
2153                node("target", NodeKind::HttpOperation, "b"),
2154            ],
2155            vec![edge("direct", "consumer", "target")],
2156        );
2157        context.freshness[0].state = RepoFreshnessState::WorkingTreeChanged;
2158
2159        let report = analyze(&context, ImpactDirection::Upstream);
2160
2161        assert_eq!((report.risk, report.risk_score), (RiskLevel::Unknown, None));
2162    }
2163
2164    #[test]
2165    fn low_confidence_should_be_unknown_risk_not_low_impact() {
2166        let mut candidate = edge("candidate", "consumer", "target");
2167        candidate.confidence = 0.2;
2168        let context = context(
2169            vec![
2170                node("consumer", NodeKind::Service, "a"),
2171                node("target", NodeKind::HttpOperation, "b"),
2172            ],
2173            vec![candidate],
2174        );
2175
2176        let report = analyze(&context, ImpactDirection::Upstream);
2177
2178        assert_eq!(
2179            (report.risk, report.possibly_affected[0].classification),
2180            (RiskLevel::Unknown, ImpactClassification::PossiblyAffected)
2181        );
2182    }
2183
2184    #[test]
2185    fn depth_truncation_should_force_unknown() {
2186        let context = context(
2187            vec![
2188                node("three", NodeKind::Service, "a"),
2189                node("two", NodeKind::Service, "b"),
2190                node("one", NodeKind::Service, "c"),
2191                node("target", NodeKind::HttpOperation, "d"),
2192            ],
2193            vec![
2194                edge("one", "one", "target"),
2195                edge("two", "two", "one"),
2196                edge("three", "three", "two"),
2197            ],
2198        );
2199        let mut request = request("target", ImpactDirection::Upstream);
2200        request.options.max_depth = 2;
2201
2202        let report = analyze_impact(&request, &context).expect("analysis should succeed");
2203
2204        assert_eq!(report.risk, RiskLevel::Unknown);
2205    }
2206
2207    #[test]
2208    fn direction_should_select_incoming_or_outgoing_edges() {
2209        let context = context(
2210            vec![
2211                node("upstream", NodeKind::Service, "a"),
2212                node("target", NodeKind::HttpOperation, "b"),
2213                node("downstream", NodeKind::Service, "c"),
2214            ],
2215            vec![
2216                edge("incoming", "upstream", "target"),
2217                edge("outgoing", "target", "downstream"),
2218            ],
2219        );
2220
2221        let report = analyze(&context, ImpactDirection::Downstream);
2222
2223        assert_eq!(report.direct_consumers[0].node.id.as_str(), "downstream");
2224    }
2225
2226    #[test]
2227    fn both_direction_should_include_both_sides() {
2228        let context = context(
2229            vec![
2230                node("upstream", NodeKind::Service, "a"),
2231                node("target", NodeKind::HttpOperation, "b"),
2232                node("downstream", NodeKind::Service, "c"),
2233            ],
2234            vec![
2235                edge("incoming", "upstream", "target"),
2236                edge("outgoing", "target", "downstream"),
2237            ],
2238        );
2239
2240        let report = analyze(&context, ImpactDirection::Both);
2241
2242        assert_eq!(report.coverage.total_items, 2);
2243    }
2244
2245    #[test]
2246    fn both_direction_should_not_treat_structural_siblings_as_impacted() {
2247        let mut contains_target = edge("contains-target", "artifact", "target");
2248        contains_target.kind = EdgeKind::Contains;
2249        let mut contains_sibling = edge("contains-sibling", "artifact", "sibling");
2250        contains_sibling.kind = EdgeKind::Contains;
2251        let mut reads_sibling = edge("reads-sibling", "reader", "sibling");
2252        reads_sibling.kind = EdgeKind::ReadsTable;
2253        let context = context(
2254            vec![
2255                node("target", NodeKind::DatabaseTable, "schema"),
2256                node("artifact", NodeKind::Artifact, "schema"),
2257                node("sibling", NodeKind::DatabaseTable, "schema"),
2258                node("reader", NodeKind::SymbolRef, "consumer"),
2259            ],
2260            vec![contains_target, contains_sibling, reads_sibling],
2261        );
2262
2263        let report = analyze(&context, ImpactDirection::Both);
2264        let impacted = report
2265            .direct_consumers
2266            .iter()
2267            .chain(&report.transitive_consumers)
2268            .map(|item| item.node.id.as_str())
2269            .collect::<BTreeSet<_>>();
2270
2271        assert_eq!(impacted, BTreeSet::from(["artifact"]));
2272    }
2273
2274    #[test]
2275    fn cycles_should_terminate_without_repeating_target() {
2276        let context = context(
2277            vec![
2278                node("a", NodeKind::Service, "a"),
2279                node("target", NodeKind::Service, "b"),
2280            ],
2281            vec![edge("one", "target", "a"), edge("two", "a", "target")],
2282        );
2283
2284        let report = analyze(&context, ImpactDirection::Downstream);
2285
2286        assert_eq!(report.coverage.total_items, 1);
2287    }
2288
2289    #[test]
2290    fn pagination_should_use_stable_combined_order() {
2291        let context = context(
2292            vec![
2293                node("a", NodeKind::Service, "a"),
2294                node("b", NodeKind::Service, "b"),
2295                node("target", NodeKind::Service, "t"),
2296            ],
2297            vec![edge("a", "a", "target"), edge("b", "b", "target")],
2298        );
2299        let mut request = request("target", ImpactDirection::Upstream);
2300        request.options.offset = 1;
2301        request.options.limit = 1;
2302
2303        let report = analyze_impact(&request, &context).expect("analysis should succeed");
2304
2305        assert_eq!(report.direct_consumers[0].node.id.as_str(), "b");
2306    }
2307
2308    #[test]
2309    fn summary_only_should_omit_items_and_retain_counts() {
2310        let context = context(
2311            vec![
2312                node("consumer", NodeKind::Service, "a"),
2313                node("target", NodeKind::Service, "b"),
2314            ],
2315            vec![edge("direct", "consumer", "target")],
2316        );
2317        let mut request = request("target", ImpactDirection::Upstream);
2318        request.options.summary_only = true;
2319
2320        let report = analyze_impact(&request, &context).expect("analysis should succeed");
2321
2322        assert_eq!(
2323            (report.direct_consumers.len(), report.coverage.total_items),
2324            (0, 1)
2325        );
2326    }
2327
2328    #[test]
2329    fn graph_tests_and_owners_should_be_ranked() {
2330        let mut validates = edge("validates", "test", "consumer");
2331        validates.kind = EdgeKind::Validates;
2332        let mut owned = edge("owned", "test", "owner");
2333        owned.kind = EdgeKind::OwnedBy;
2334        let context = context(
2335            vec![
2336                node("test", NodeKind::TestCase, "a"),
2337                node("owner", NodeKind::Owner, "a"),
2338                node("consumer", NodeKind::Service, "a"),
2339                node("target", NodeKind::HttpOperation, "b"),
2340            ],
2341            vec![edge("direct", "consumer", "target"), validates, owned],
2342        );
2343
2344        let report = analyze(&context, ImpactDirection::Upstream);
2345
2346        assert_eq!(
2347            report.test_recommendations[0].owners[0].id.as_str(),
2348            "owner"
2349        );
2350    }
2351
2352    #[test]
2353    fn explicit_commands_should_only_be_returned_not_executed() {
2354        let mut validates = edge("validates", "test", "consumer");
2355        validates.kind = EdgeKind::Validates;
2356        let mut context = context(
2357            vec![
2358                node("test", NodeKind::TestCase, "a"),
2359                node("consumer", NodeKind::Service, "a"),
2360                node("target", NodeKind::Service, "b"),
2361            ],
2362            vec![edge("direct", "consumer", "target"), validates],
2363        );
2364        context.recommended_commands.push(RecommendedCommand {
2365            repo_id: RepoId::new("a"),
2366            command: "cargo test -p consumer".to_owned(),
2367            description: "consumer tests".to_owned(),
2368        });
2369
2370        let report = analyze(&context, ImpactDirection::Upstream);
2371
2372        assert_eq!(
2373            report.test_recommendations[0].recommended_commands,
2374            vec!["cargo test -p consumer"]
2375        );
2376    }
2377
2378    #[test]
2379    fn affected_community_should_include_coupling() {
2380        let mut context = context(
2381            vec![
2382                node("consumer", NodeKind::Service, "a"),
2383                node("target", NodeKind::Service, "b"),
2384            ],
2385            vec![edge("direct", "consumer", "target")],
2386        );
2387        context.communities = Some(CommunitySnapshot {
2388            snapshot_id: "snapshot".to_owned(),
2389            engine_version: "1.0.0".to_owned(),
2390            config: CommunityConfig {
2391                algorithm: code_system_graph_model::CommunityAlgorithm::ConnectedComponents,
2392                scope: code_system_graph_model::CommunityScope::Federated,
2393                seed: 0,
2394                resolution: 1.0,
2395                minimum_confidence: 0.8,
2396                edge_weights: Vec::new(),
2397                max_iterations: 1,
2398            },
2399            communities: vec![Community {
2400                id: CommunityId::new("community"),
2401                label: "orders".to_owned(),
2402                members: vec![NodeId::new("consumer")],
2403                central_nodes: Vec::new(),
2404                repositories: vec![RepoId::new("a")],
2405                services: vec![NodeId::new("consumer")],
2406                inbound_contracts: Vec::new(),
2407                outbound_contracts: Vec::new(),
2408                metrics: CommunityMetrics {
2409                    size: 1,
2410                    density: 0.0,
2411                    cohesion: 0.0,
2412                    coupling: 2.0,
2413                    cross_community_edges: 1,
2414                },
2415                label_evidence: Vec::new(),
2416                limitations: Vec::new(),
2417            }],
2418        });
2419
2420        let report = analyze(&context, ImpactDirection::Upstream);
2421
2422        assert!((report.affected_communities[0].coupling - 2.0).abs() < f64::EPSILON);
2423    }
2424
2425    #[test]
2426    fn local_enrichment_degradation_should_be_visible_and_unknown() {
2427        let mut context = context(
2428            vec![
2429                node("consumer", NodeKind::Service, "a"),
2430                node("target", NodeKind::Service, "b"),
2431            ],
2432            vec![edge("direct", "consumer", "target")],
2433        );
2434        context.local_enrichment.push(LocalEnrichmentInput {
2435            repo_id: RepoId::new("a"),
2436            anchor: "consumer".to_owned(),
2437            status: LocalEnrichmentStatus::Stale,
2438            affected: Vec::new(),
2439            affected_tests: Vec::new(),
2440            truncated: false,
2441            degradations: vec!["reindex repository".to_owned()],
2442        });
2443
2444        let report = analyze(&context, ImpactDirection::Upstream);
2445
2446        assert_eq!(
2447            (report.risk, report.local_impact_summaries[0].status),
2448            (RiskLevel::Unknown, LocalEnrichmentStatus::Stale)
2449        );
2450    }
2451
2452    #[test]
2453    fn explicit_security_tag_with_evidence_can_produce_critical() {
2454        let mut context = context(
2455            vec![
2456                node("consumer", NodeKind::Service, "a"),
2457                node("target", NodeKind::HttpOperation, "b"),
2458            ],
2459            vec![edge("direct", "consumer", "target")],
2460        );
2461        context.criticality.push(CriticalityAssignment {
2462            node_id: NodeId::new("target"),
2463            tag: CriticalityTag::Security,
2464            evidence: vec!["policy:security-boundary".to_owned()],
2465        });
2466        context.public_contracts.push(NodeId::new("target"));
2467        context.compatibility.push(CompatibilityInput {
2468            contract_node_id: NodeId::new("target"),
2469            status: ImpactCompatibilityStatus::Breaking,
2470            evidence: vec!["breaking".to_owned()],
2471            recommended_validations: Vec::new(),
2472        });
2473
2474        let report = analyze(&context, ImpactDirection::Upstream);
2475
2476        assert_eq!(report.risk, RiskLevel::Critical);
2477    }
2478
2479    #[test]
2480    fn labels_should_not_infer_critical_tags() {
2481        let context = context(
2482            vec![
2483                node("payment-security", NodeKind::Service, "a"),
2484                node("target", NodeKind::Service, "b"),
2485            ],
2486            vec![edge("direct", "payment-security", "target")],
2487        );
2488
2489        let report = analyze(&context, ImpactDirection::Upstream);
2490
2491        assert!(
2492            !report
2493                .reasons
2494                .iter()
2495                .any(|factor| factor.code.ends_with("_tag"))
2496        );
2497    }
2498
2499    #[test]
2500    fn identical_inputs_should_produce_identical_reports() {
2501        let context = context(
2502            vec![
2503                node("b", NodeKind::Service, "b"),
2504                node("target", NodeKind::Service, "t"),
2505                node("a", NodeKind::Service, "a"),
2506            ],
2507            vec![edge("b", "b", "target"), edge("a", "a", "target")],
2508        );
2509
2510        let first = analyze(&context, ImpactDirection::Upstream);
2511        let second = analyze(&context, ImpactDirection::Upstream);
2512
2513        assert_eq!(first, second);
2514    }
2515
2516    #[test]
2517    fn invalid_bounds_should_be_rejected() {
2518        let context = context(vec![node("target", NodeKind::Service, "a")], Vec::new());
2519        let mut request = request("target", ImpactDirection::Both);
2520        request.options.max_depth = 0;
2521
2522        let error = analyze_impact(&request, &context).expect_err("zero depth must be rejected");
2523
2524        assert_eq!(error, ImpactError::InvalidBounds);
2525    }
2526
2527    #[test]
2528    fn invalid_edge_confidence_should_be_rejected() {
2529        let mut invalid = edge("invalid", "consumer", "target");
2530        invalid.confidence = f32::NAN;
2531        let context = context(
2532            vec![
2533                node("consumer", NodeKind::Service, "a"),
2534                node("target", NodeKind::Service, "b"),
2535            ],
2536            vec![invalid],
2537        );
2538
2539        let error = analyze_impact(&request("target", ImpactDirection::Upstream), &context)
2540            .expect_err("NaN confidence must be rejected");
2541
2542        assert_eq!(
2543            error,
2544            ImpactError::InvalidEdgeConfidence("invalid".to_owned())
2545        );
2546    }
2547
2548    #[test]
2549    fn fresh_complete_empty_impact_should_have_positive_low_score() {
2550        let context = context(vec![node("target", NodeKind::Service, "a")], Vec::new());
2551
2552        let report = analyze(&context, ImpactDirection::Both);
2553
2554        assert_eq!(
2555            (report.risk, report.risk_score),
2556            (RiskLevel::Low, Some(1.0))
2557        );
2558    }
2559}