Skip to main content

fallow_api/
dependency_deltas.rs

1//! Dependency deltas for the decision surface: what a changed `package.json`
2//! adds or moves across a major version, read from the base and head manifest
3//! text, projected onto [`DependencyAnchor`]s. Pure over its inputs; the CLI
4//! reads base text through git and the typed runtime through the base
5//! worktree, and both hand the pairs to [`dependency_anchors_from_manifests`]
6//! so the two routes cannot drift.
7//!
8//! Firing precision mirrors the public-API rule R1: a manifest yields at most
9//! one "added" candidate set and one "major bump" candidate set, never one
10//! decision per package. Minor and patch bumps are not candidates; a range
11//! that does not start with a numeric version (a workspace, catalog, file,
12//! git, or tag specifier) is skipped rather than guessed at.
13
14use fallow_engine::module_graph::PackageImporters;
15use fallow_output::ReviewDeltas;
16use fallow_types::discover::FileId;
17use rustc_hash::{FxHashMap, FxHashSet};
18use serde_json::Value;
19
20use crate::decision_surface::{
21    DependencyAnchor, DependencyChangeKind, DependencyEntry, dependency_delta_key,
22};
23
24/// The `package.json` sections a dependency entry can live in, in the
25/// precedence order a duplicate name resolves to.
26const DEPENDENCY_SECTIONS: [&str; 4] = [
27    "dependencies",
28    "devDependencies",
29    "optionalDependencies",
30    "peerDependencies",
31];
32
33/// One dependency entry that changed between base and head.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct DependencyChange {
36    /// The package name.
37    pub name: String,
38    /// The manifest section the entry lives in at head.
39    pub section: String,
40    /// The base range, `None` when the entry is new.
41    pub from: Option<String>,
42    /// The head range.
43    pub to: String,
44    /// 1-based line of the entry in the head manifest, `0` when not found.
45    pub line: u32,
46}
47
48/// The dependency changes in one manifest, split by candidate kind.
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct ManifestDependencyDeltas {
51    /// Entries absent at base.
52    pub added: Vec<DependencyChange>,
53    /// Entries whose range moved across a major version (or a `0.x` minor).
54    pub major_bumped: Vec<DependencyChange>,
55}
56
57/// A changed manifest with its base and head text.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct ManifestPair {
60    /// Root-relative, forward-slashed path of the manifest.
61    pub manifest: String,
62    /// The base text; `None` when the manifest did not exist at base.
63    pub base: Option<String>,
64    /// The head text.
65    pub head: String,
66}
67
68/// Whether `rel_path` is a `package.json` manifest fallow should diff.
69#[must_use]
70pub fn is_manifest_path(rel_path: &str) -> bool {
71    let name = rel_path.rsplit('/').next().unwrap_or(rel_path);
72    name == "package.json" && !rel_path.contains("node_modules/")
73}
74
75/// Diff the dependency sections of a manifest between `base` and `head` text.
76/// Malformed JSON on either side reads as empty: an unreadable base makes every
77/// head entry new, an unreadable head yields nothing.
78#[must_use]
79pub fn manifest_dependency_deltas(base: &str, head: &str) -> ManifestDependencyDeltas {
80    let base_entries = dependency_entries(base);
81    let head_entries = dependency_entries(head);
82    if head_entries.is_empty() {
83        return ManifestDependencyDeltas::default();
84    }
85
86    let mut deltas = ManifestDependencyDeltas::default();
87    let mut names: Vec<&String> = head_entries.keys().collect();
88    names.sort();
89    for name in names {
90        let (section, to) = &head_entries[name];
91        let line = entry_line(head, section, name);
92        let change = |from: Option<String>| DependencyChange {
93            name: name.clone(),
94            section: section.clone(),
95            from,
96            to: to.clone(),
97            line,
98        };
99        match base_entries.get(name) {
100            None => deltas.added.push(change(None)),
101            Some((_, from)) if is_major_bump(from, to) => {
102                deltas.major_bumped.push(change(Some(from.clone())));
103            }
104            Some(_) => {}
105        }
106    }
107    deltas
108}
109
110/// Whether moving a range from `from` to `to` crosses a major version. Both
111/// sides must start with a numeric version once the range operator is
112/// stripped; anything else (workspace, catalog, file, git, tag, wildcard) is
113/// not a bump fallow can classify. A `0.x` line treats a minor move as major,
114/// the semver convention for pre-1.0 packages.
115#[must_use]
116pub fn is_major_bump(from: &str, to: &str) -> bool {
117    let (Some((from_major, from_minor)), Some((to_major, to_minor))) =
118        (leading_version(from), leading_version(to))
119    else {
120        return false;
121    };
122    if from_major != to_major {
123        return true;
124    }
125    from_major == 0 && from_minor != to_minor
126}
127
128/// Project manifest pairs onto dependency anchors, one per manifest per kind,
129/// in manifest order. Importer counts come from the graph's package usage; a
130/// package the graph never saw counts zero.
131#[must_use]
132#[expect(
133    clippy::implicit_hasher,
134    reason = "fallow standardizes on FxHashMap; the importer map is always built by the engine with the fallow hasher"
135)]
136pub fn dependency_anchors_from_manifests(
137    manifests: &[ManifestPair],
138    package_importers: Option<&FxHashMap<String, PackageImporters>>,
139) -> Vec<DependencyAnchor> {
140    let mut anchors = Vec::new();
141    for pair in manifests {
142        let deltas = manifest_dependency_deltas(pair.base.as_deref().unwrap_or(""), &pair.head);
143        if !deltas.added.is_empty() {
144            anchors.push(to_anchor(
145                &pair.manifest,
146                DependencyChangeKind::Added,
147                &deltas.added,
148                package_importers,
149            ));
150        }
151        if !deltas.major_bumped.is_empty() {
152            anchors.push(to_anchor(
153                &pair.manifest,
154                DependencyChangeKind::MajorBump,
155                &deltas.major_bumped,
156                package_importers,
157            ));
158        }
159    }
160    anchors
161}
162
163/// Mirror the dependency anchors onto the brief's `deltas` as stable keys so
164/// the JSON envelope names what changed even when the cap collapses the
165/// decision.
166pub fn fill_dependency_delta_keys(deltas: &mut ReviewDeltas, anchors: &[DependencyAnchor]) {
167    for anchor in anchors {
168        for entry in &anchor.entries {
169            let key = dependency_delta_key(&anchor.manifest, anchor.kind, entry);
170            match anchor.kind {
171                DependencyChangeKind::MajorBump => deltas.dependency_major_bumped.push(key),
172                DependencyChangeKind::Added => deltas.dependency_added.push(key),
173            }
174        }
175    }
176    deltas.dependency_added.sort();
177    deltas.dependency_major_bumped.sort();
178}
179
180fn to_anchor(
181    manifest: &str,
182    kind: DependencyChangeKind,
183    entries: &[DependencyChange],
184    package_importers: Option<&FxHashMap<String, PackageImporters>>,
185) -> DependencyAnchor {
186    // Union, not sum: a module importing two packages of the same batch is one
187    // importer, and the count is both displayed and used for ranking.
188    let mut importer_ids: FxHashSet<FileId> = FxHashSet::default();
189    let mut out_of_diff_ids: FxHashSet<FileId> = FxHashSet::default();
190    for entry in entries {
191        if let Some(counts) = package_importers.and_then(|map| map.get(&entry.name)) {
192            importer_ids.extend(counts.importers.iter().copied());
193            out_of_diff_ids.extend(counts.out_of_diff.iter().copied());
194        }
195    }
196    let importers = importer_ids.len() as u64;
197    let out_of_diff_importers = out_of_diff_ids.len() as u64;
198    DependencyAnchor {
199        manifest: manifest.to_string(),
200        kind,
201        entries: entries
202            .iter()
203            .map(|entry| DependencyEntry {
204                name: entry.name.clone(),
205                section: entry.section.clone(),
206                from: entry.from.clone(),
207                to: entry.to.clone(),
208            })
209            .collect(),
210        importers,
211        out_of_diff_importers,
212        line: entries
213            .iter()
214            .map(|entry| entry.line)
215            .find(|line| *line > 0)
216            .unwrap_or(0),
217    }
218}
219
220/// The `(major, minor)` pair a range starts with, after stripping a leading
221/// range operator. An `npm:<name>@<range>` alias is read at its range, since
222/// that is how a package ships two majors of one peer side by side. `None`
223/// when the range does not start with digits.
224fn leading_version(range: &str) -> Option<(u64, u64)> {
225    let range = range
226        .trim()
227        .strip_prefix("npm:")
228        .and_then(|alias| alias.rsplit_once('@').map(|(_, range)| range))
229        .unwrap_or(range);
230    let trimmed = range
231        .trim()
232        .trim_start_matches(['^', '~', '=', 'v', '>', '<', ' ']);
233    let core = trimmed.split([' ', '|']).next().unwrap_or(trimmed);
234    let mut parts = core.split('.');
235    let major = parts.next()?.parse::<u64>().ok()?;
236    let minor = parts
237        .next()
238        .and_then(|m| m.parse::<u64>().ok())
239        .unwrap_or(0);
240    Some((major, minor))
241}
242
243/// Every `name -> (section, range)` pair across the dependency sections. A
244/// later section never overrides an earlier one, so a package listed as both
245/// a peer and a runtime dependency keeps its `dependencies` range.
246fn dependency_entries(text: &str) -> FxHashMap<String, (String, String)> {
247    let mut entries: FxHashMap<String, (String, String)> = FxHashMap::default();
248    let Ok(Value::Object(manifest)) = serde_json::from_str::<Value>(text) else {
249        return entries;
250    };
251    for section in DEPENDENCY_SECTIONS {
252        let Some(Value::Object(deps)) = manifest.get(section) else {
253            continue;
254        };
255        for (name, range) in deps {
256            if let Value::String(range) = range {
257                entries
258                    .entry(name.clone())
259                    .or_insert_with(|| (section.to_string(), range.clone()));
260            }
261        }
262    }
263    entries
264}
265
266/// 1-based line of the `"<name>":` key inside the `"<section>":` block of
267/// `text`, `0` when absent. The scan starts at the section header so a
268/// package listed in two sections anchors on the section that won.
269fn entry_line(text: &str, section: &str, name: &str) -> u32 {
270    let is_key = |line: &str, key: &str| {
271        line.trim_start()
272            .strip_prefix(&format!("\"{key}\""))
273            .is_some_and(|rest| rest.trim_start().starts_with(':'))
274    };
275    let lines: Vec<&str> = text.lines().collect();
276    let start = lines
277        .iter()
278        .position(|line| is_key(line, section))
279        .unwrap_or(0);
280    lines[start..]
281        .iter()
282        .position(|line| is_key(line, name))
283        .map_or(0, |offset| {
284            u32::try_from(start + offset + 1).unwrap_or(u32::MAX)
285        })
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    fn change(
293        name: &str,
294        section: &str,
295        from: Option<&str>,
296        to: &str,
297        line: u32,
298    ) -> DependencyChange {
299        DependencyChange {
300            name: name.to_string(),
301            section: section.to_string(),
302            from: from.map(str::to_string),
303            to: to.to_string(),
304            line,
305        }
306    }
307
308    #[test]
309    fn added_and_major_bumped_entries_are_split_and_sorted() {
310        let base = r#"{ "dependencies": { "react": "^18.2.0", "zod": "^3.0.0" } }"#;
311        let head = "{\n  \"dependencies\": {\n    \"react\": \"^19.0.0\",\n    \"zod\": \"^3.4.0\",\n    \"dayjs\": \"^1.11.0\"\n  }\n}\n";
312        let deltas = manifest_dependency_deltas(base, head);
313        assert_eq!(
314            deltas.added,
315            vec![change("dayjs", "dependencies", None, "^1.11.0", 5)]
316        );
317        assert_eq!(
318            deltas.major_bumped,
319            vec![change(
320                "react",
321                "dependencies",
322                Some("^18.2.0"),
323                "^19.0.0",
324                3
325            )]
326        );
327    }
328
329    #[test]
330    fn non_numeric_ranges_and_minor_bumps_are_not_candidates() {
331        assert!(!is_major_bump("^1.2.0", "^1.9.0"));
332        assert!(!is_major_bump("workspace:*", "workspace:^"));
333        assert!(!is_major_bump("catalog:", "catalog:react19"));
334        assert!(!is_major_bump("^2.0.0", "file:../local"));
335        assert!(!is_major_bump("latest", "^3.0.0"));
336        assert!(is_major_bump("npm:foo@1.0.0", "npm:foo@2.0.0"));
337        assert!(is_major_bump(
338            "npm:@scope/pkg@^1.4.0",
339            "npm:@scope/pkg@^2.0.0"
340        ));
341        assert!(!is_major_bump("npm:foo@^1.0.0", "npm:foo@^1.9.0"));
342        assert!(!is_major_bump("1.0.0-beta.2", "1.0.0"));
343        assert!(is_major_bump("~1.4.0", "2.0.0"));
344        assert!(is_major_bump(">=1.0.0 <2.0.0", "^3.0.0"));
345        assert!(is_major_bump("1.x || 2.x", "3.0.0"));
346    }
347
348    #[test]
349    fn zero_x_minor_move_counts_as_major() {
350        assert!(is_major_bump("^0.3.1", "^0.4.0"));
351        assert!(!is_major_bump("^0.3.1", "^0.3.9"));
352    }
353
354    #[test]
355    fn dev_and_peer_sections_participate_without_overriding_runtime_ranges() {
356        let base = r#"{ "devDependencies": { "vitest": "^1.0.0" } }"#;
357        let head = r#"{ "dependencies": { "zod": "^3.0.0" }, "devDependencies": { "vitest": "^2.0.0", "zod": "^9.0.0" } }"#;
358        let deltas = manifest_dependency_deltas(base, head);
359        assert_eq!(deltas.major_bumped.len(), 1);
360        assert_eq!(deltas.major_bumped[0].name, "vitest");
361        assert_eq!(deltas.major_bumped[0].section, "devDependencies");
362        assert_eq!(deltas.added.len(), 1);
363        assert_eq!(deltas.added[0].to, "^3.0.0", "the runtime range wins");
364        assert_eq!(deltas.added[0].section, "dependencies");
365    }
366
367    #[test]
368    fn malformed_manifest_yields_nothing_or_all_new() {
369        let all_new = manifest_dependency_deltas("{", r#"{ "dependencies": { "a": "^1.0.0" } }"#);
370        assert_eq!(
371            all_new.added,
372            vec![change("a", "dependencies", None, "^1.0.0", 0)]
373        );
374        assert!(all_new.major_bumped.is_empty());
375        assert_eq!(
376            manifest_dependency_deltas(r#"{ "dependencies": { "a": "^1.0.0" } }"#, "{"),
377            ManifestDependencyDeltas::default()
378        );
379    }
380
381    #[test]
382    fn batched_importers_are_a_union_not_a_sum() {
383        let pairs = vec![ManifestPair {
384            manifest: "package.json".to_string(),
385            base: Some(
386                r#"{ "dependencies": { "react": "^18.0.0", "react-dom": "^18.0.0" } }"#.to_string(),
387            ),
388            head: r#"{ "dependencies": { "react": "^19.0.0", "react-dom": "^19.0.0" } }"#
389                .to_string(),
390        }];
391        let mut importers = FxHashMap::default();
392        for name in ["react", "react-dom"] {
393            importers.insert(
394                name.to_string(),
395                PackageImporters {
396                    importers: vec![FileId(1), FileId(2)],
397                    out_of_diff: vec![FileId(2)],
398                },
399            );
400        }
401        let anchors = dependency_anchors_from_manifests(&pairs, Some(&importers));
402        assert_eq!(anchors.len(), 1);
403        assert_eq!(anchors[0].entries.len(), 2);
404        assert_eq!(anchors[0].importers, 2, "two modules import both packages");
405        assert_eq!(anchors[0].out_of_diff_importers, 1);
406    }
407
408    #[test]
409    fn entry_line_follows_the_winning_section() {
410        let head = "{\n  \"devDependencies\": {\n    \"zod\": \"^9.0.0\"\n  },\n  \"dependencies\": {\n    \"zod\": \"^3.0.0\"\n  }\n}\n";
411        let deltas = manifest_dependency_deltas("{}", head);
412        assert_eq!(deltas.added.len(), 1);
413        assert_eq!(deltas.added[0].section, "dependencies");
414        assert_eq!(
415            deltas.added[0].line, 6,
416            "the runtime entry, not the dev one above it"
417        );
418    }
419
420    #[test]
421    fn manifest_paths_exclude_node_modules() {
422        assert!(is_manifest_path("package.json"));
423        assert!(is_manifest_path("packages/web/package.json"));
424        assert!(!is_manifest_path("node_modules/react/package.json"));
425        assert!(!is_manifest_path("packages/web/tsconfig.json"));
426    }
427
428    #[test]
429    fn anchors_and_delta_keys_agree_with_the_candidate_key() {
430        let pairs = vec![ManifestPair {
431            manifest: "packages/web/package.json".to_string(),
432            base: Some(r#"{ "dependencies": { "react": "^18.0.0" } }"#.to_string()),
433            head: r#"{ "dependencies": { "react": "^19.0.0", "dayjs": "^1.0.0" } }"#.to_string(),
434        }];
435        let ids = |range: std::ops::Range<u32>| range.map(FileId).collect::<Vec<_>>();
436        let mut importers = FxHashMap::default();
437        importers.insert(
438            "react".to_string(),
439            PackageImporters {
440                importers: ids(0..40),
441                out_of_diff: ids(2..40),
442            },
443        );
444        let anchors = dependency_anchors_from_manifests(&pairs, Some(&importers));
445        assert_eq!(anchors.len(), 2);
446        assert_eq!(anchors[0].kind, DependencyChangeKind::Added);
447        assert_eq!(anchors[0].importers, 0);
448        assert_eq!(anchors[1].kind, DependencyChangeKind::MajorBump);
449        assert_eq!(anchors[1].importers, 40);
450        assert_eq!(anchors[1].out_of_diff_importers, 38);
451
452        let mut deltas = ReviewDeltas::default();
453        fill_dependency_delta_keys(&mut deltas, &anchors);
454        assert_eq!(
455            deltas.dependency_added,
456            vec!["packages/web/package.json::dayjs"]
457        );
458        assert_eq!(
459            deltas.dependency_major_bumped,
460            vec!["packages/web/package.json::react@^18.0.0->^19.0.0"]
461        );
462        let surface = crate::decision_surface::extract_decision_surface(
463            &crate::decision_surface::DecisionInputs {
464                deltas: &deltas,
465                boundary_anchors: &[],
466                coordination: &[],
467                dependency_anchors: &anchors,
468                public_api_anchor_line: 0,
469                affected_not_shown: 0,
470                routing: &fallow_output::RoutingFacts::default(),
471                head_source: &|_: &str| None,
472                rename_old_path: &|_: &str| None,
473                internal_consumers: &|_: &str| 0,
474                cap: 4,
475            },
476        );
477        let keys: Vec<&str> = surface
478            .decisions
479            .iter()
480            .map(|d| d.signal_key.as_str())
481            .collect();
482        assert!(keys.contains(&"packages/web/package.json::react@^18.0.0->^19.0.0"));
483        assert!(keys.contains(&"packages/web/package.json::dayjs"));
484    }
485}