callisto-graph 0.4.1

Callisto Release Engine — Dependency DAG solver and topological cascade release planner.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use callisto_model::{Ecosystem, ManifestFormat, ManifestRole, PackageId};

use crate::error::GraphError;

pub struct IdentityResolver {
    workspace_root: PathBuf,
}

impl IdentityResolver {
    pub fn new(workspace_root: &Path) -> Result<Self, GraphError> {
        Ok(IdentityResolver {
            workspace_root: workspace_root.to_path_buf(),
        })
    }

    pub fn resolve(&self, project_root: &Path, ecosystem: Ecosystem) -> Result<PackageId, GraphError> {
        let abs = self.workspace_root.join(project_root);
        let name = match ecosystem {
            Ecosystem::Cargo => {
                let cargo_toml = abs.join("Cargo.toml");
                let content =
                    std::fs::read_to_string(&cargo_toml).map_err(|e| callisto_model::ManifestError::Read {
                        path: project_root.join("Cargo.toml"),
                        message: e.to_string(),
                    })?;
                let doc: toml_edit::DocumentMut =
                    content
                        .parse()
                        .map_err(|e: toml_edit::TomlError| callisto_model::ManifestError::Parse {
                            path: project_root.join("Cargo.toml"),
                            format: ManifestFormat::CargoToml,
                            message: e.to_string(),
                        })?;
                callisto_manifests::cargo_package_name(&doc)
                    .ok_or_else(|| callisto_model::ManifestError::MissingField {
                        path: project_root.join("Cargo.toml"),
                        field: "package.name",
                    })?
                    .to_string()
            }
            Ecosystem::Npm => {
                let pkg_json = abs.join("package.json");
                let content = std::fs::read_to_string(&pkg_json).map_err(|e| callisto_model::ManifestError::Read {
                    path: project_root.join("package.json"),
                    message: e.to_string(),
                })?;
                let doc: serde_json::Map<String, serde_json::Value> =
                    serde_json::from_str(&content).map_err(|e| callisto_model::ManifestError::Parse {
                        path: project_root.join("package.json"),
                        format: ManifestFormat::PackageJson,
                        message: e.to_string(),
                    })?;
                callisto_manifests::npm_package_name(&doc)
                    .ok_or_else(|| callisto_model::ManifestError::MissingField {
                        path: project_root.join("package.json"),
                        field: "name",
                    })?
                    .to_string()
            }
            Ecosystem::Pypi => {
                let pyproject_toml = abs.join("pyproject.toml");
                let content =
                    std::fs::read_to_string(&pyproject_toml).map_err(|e| callisto_model::ManifestError::Read {
                        path: project_root.join("pyproject.toml"),
                        message: e.to_string(),
                    })?;
                let doc: toml_edit::DocumentMut =
                    content
                        .parse()
                        .map_err(|e: toml_edit::TomlError| callisto_model::ManifestError::Parse {
                            path: project_root.join("pyproject.toml"),
                            format: ManifestFormat::PyprojectToml,
                            message: e.to_string(),
                        })?;
                callisto_manifests::python_package_name(&doc)
                    .ok_or_else(|| callisto_model::ManifestError::MissingField {
                        path: project_root.join("pyproject.toml"),
                        field: "project.name / tool.poetry.name / tool.flit.metadata.module",
                    })?
                    .to_string()
            }
            _ => {
                return Err(GraphError::AmbiguousName {
                    name: "unsupported ecosystem".to_string(),
                    candidates: Vec::new(),
                });
            }
        };

        PackageId::parse(&name).map_err(|_err| GraphError::AmbiguousName {
            name: name.clone(),
            candidates: Vec::new(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resolves_cargo_package_name() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"my-crate\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        let resolver = IdentityResolver::new(dir.path()).unwrap();
        let id = resolver.resolve(std::path::Path::new("."), Ecosystem::Cargo).unwrap();
        assert_eq!(id.name(), "my-crate");
    }

    /// A `Cargo.toml` using `version.workspace = true` (real-world common
    /// case) must still resolve by name alone -- a package's *name* is
    /// never workspace-inherited in Cargo, so this must succeed without
    /// any `WorkspaceInheritance` context, which `IdentityResolver` (used
    /// from `callisto-moon`'s WASM PDK entry points, which have no such
    /// context available) deliberately never builds.
    #[test]
    fn resolves_cargo_package_name_with_workspace_inherited_version() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"inheriting-crate\"\nversion.workspace = true\nedition.workspace = true\n",
        )
        .unwrap();
        let resolver = IdentityResolver::new(dir.path()).unwrap();
        let id = resolver.resolve(std::path::Path::new("."), Ecosystem::Cargo).unwrap();
        assert_eq!(id.name(), "inheriting-crate");
    }

    #[test]
    fn resolves_npm_package_name() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"name":"my-pkg","version":"1.0.0"}"#,
        )
        .unwrap();
        let resolver = IdentityResolver::new(dir.path()).unwrap();
        let id = resolver.resolve(std::path::Path::new("."), Ecosystem::Npm).unwrap();
        assert_eq!(id.name(), "my-pkg");
    }

    #[test]
    fn resolves_pypi_package_name_pep621() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("pyproject.toml"),
            "[project]\nname = \"my-lib\"\nversion = \"1.0.0\"\n",
        )
        .unwrap();
        let resolver = IdentityResolver::new(dir.path()).unwrap();
        let id = resolver.resolve(std::path::Path::new("."), Ecosystem::Pypi).unwrap();
        assert_eq!(id.name(), "my-lib");
    }

    #[test]
    fn resolves_pypi_package_name_poetry_fallback() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("pyproject.toml"),
            "[tool.poetry]\nname = \"my-poetry-lib\"\nversion = \"1.0.0\"\n",
        )
        .unwrap();
        let resolver = IdentityResolver::new(dir.path()).unwrap();
        let id = resolver.resolve(std::path::Path::new("."), Ecosystem::Pypi).unwrap();
        assert_eq!(id.name(), "my-poetry-lib");
    }

    /// Before the shared-extractor refactor, IdentityResolver's Pypi branch
    /// only checked PEP 621 then Poetry -- unlike
    /// `PyprojectToml::package_name()`, which also falls back to Flit's
    /// `[tool.flit.metadata].module`. A Flit-based Python package could be
    /// resolved via the Manifest trait but not via IdentityResolver. The
    /// shared `python_package_name` extractor closes this gap as a
    /// side effect of removing the duplication.
    #[test]
    fn resolves_pypi_package_name_flit_fallback() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("pyproject.toml"),
            "[tool.flit.metadata]\nmodule = \"my_flit_lib\"\n",
        )
        .unwrap();
        let resolver = IdentityResolver::new(dir.path()).unwrap();
        let id = resolver.resolve(std::path::Path::new("."), Ecosystem::Pypi).unwrap();
        assert_eq!(id.name(), "my_flit_lib");
    }

    #[test]
    fn resolve_errors_when_manifest_file_missing() {
        let dir = tempfile::tempdir().unwrap();
        let resolver = IdentityResolver::new(dir.path()).unwrap();
        let result = resolver.resolve(std::path::Path::new("."), Ecosystem::Cargo);
        assert!(result.is_err());
    }

    #[test]
    fn resolve_errors_when_name_field_missing() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("Cargo.toml"), "[workspace]\nmembers = []\n").unwrap();
        let resolver = IdentityResolver::new(dir.path()).unwrap();
        let result = resolver.resolve(std::path::Path::new("."), Ecosystem::Cargo);
        assert!(result.is_err());
    }

    #[test]
    fn resolve_human_finds_prefixed_entry_for_unpromoted_package() {
        let mut index = IdentityIndex::default();
        let id = PackageId::Bare("foo".to_string());
        index.bare.insert("foo".to_string(), id.clone());
        index.native.insert((Ecosystem::Cargo, "foo".to_string()), id.clone());
        index.prefixed.insert((Ecosystem::Cargo, "foo".to_string()), id.clone());
        let resolved = index
            .resolve_human("cargo:foo", &[])
            .expect("cargo:foo must resolve via prefixed map");
        assert_eq!(resolved, id);
    }

    #[test]
    fn resolve_human_unknown_ecosystem_prefix_falls_through_to_unknown() {
        let mut index = IdentityIndex::default();
        let id = PackageId::Bare("foo".to_string());
        index.bare.insert("foo".to_string(), id.clone());
        index.native.insert((Ecosystem::Cargo, "foo".to_string()), id.clone());
        index.prefixed.insert((Ecosystem::Cargo, "foo".to_string()), id);
        let err = index.resolve_human("npm:foo", &[]).unwrap_err();
        assert!(
            matches!(err, GraphError::UnknownPackage { .. }),
            "expected UnknownPackage, got {err:?}"
        );
    }

    #[test]
    fn resolve_native_with_fallback_returns_none_on_single_cross_ecosystem_candidate() {
        let mut index = IdentityIndex::default();
        let cargo_serde = PackageId::Bare("serde".to_string());
        index
            .native
            .insert((Ecosystem::Cargo, "serde".to_string()), cargo_serde);
        let mut diagnostics = Vec::new();
        let result = index.resolve_native_with_fallback(Ecosystem::Npm, "serde", &mut diagnostics);
        assert!(
            result.is_none(),
            "a same-ecosystem miss must never silently fall back to a cross-ecosystem match"
        );
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, callisto_model::DiagnosticCode::UnknownPackage);
        assert_eq!(diagnostics[0].severity, callisto_model::DiagnosticSeverity::Warning);
    }

    #[test]
    fn resolve_native_with_fallback_returns_none_and_one_diagnostic_for_two_candidates() {
        let mut index = IdentityIndex::default();
        index.native.insert(
            (Ecosystem::Cargo, "ambiguous-lib".to_string()),
            PackageId::Bare("ambiguous-lib".to_string()),
        );
        index.native.insert(
            (Ecosystem::Pypi, "ambiguous-lib".to_string()),
            PackageId::Prefixed {
                ecosystem: Ecosystem::Pypi,
                name: "ambiguous-lib".to_string(),
            },
        );
        let mut diagnostics = Vec::new();
        let result = index.resolve_native_with_fallback(Ecosystem::Npm, "ambiguous-lib", &mut diagnostics);
        assert!(result.is_none());
        assert_eq!(diagnostics.len(), 1, "exactly one diagnostic, not zero and not two");
        assert!(
            diagnostics[0].message.contains("cargo:ambiguous-lib")
                && diagnostics[0].message.contains("pypi:ambiguous-lib")
        );
    }

    #[test]
    fn resolve_native_unchanged_still_returns_cross_ecosystem_match() {
        let mut index = IdentityIndex::default();
        let cargo_serde = PackageId::Bare("serde".to_string());
        index
            .native
            .insert((Ecosystem::Cargo, "serde".to_string()), cargo_serde.clone());
        let result = index.resolve_native(Ecosystem::Npm, "serde");
        assert_eq!(
            result,
            Some(&cargo_serde),
            "resolve_native's own permissive contract is unchanged by this spec"
        );
    }
}

#[derive(Clone, Debug, Default)]
pub struct IdentityIndex {
    pub bare: BTreeMap<String, PackageId>,
    pub prefixed: BTreeMap<(Ecosystem, String), PackageId>,
    pub native: BTreeMap<(Ecosystem, String), PackageId>,
    /// Keyed by a platform npm manifest's own package name (e.g.
    /// `"@myorg/my-crate-linux-x64-gnu"`) -- distinct from `owner`'s name
    /// when the owning package's primary identity comes from a
    /// higher-priority ecosystem sharing the same directory (a Cargo+npm
    /// Case D project, §M.6.1 M7: platform manifests belong to the owning
    /// `Package`, they are never independently-registered `Package`s of
    /// their own). The `ManifestRole::Platform` is carried alongside so
    /// `GroupTable::resolve` doesn't need a second disk read to recover it.
    pub platform: BTreeMap<String, (PackageId, PathBuf, ManifestRole)>,
}

impl IdentityIndex {
    pub fn resolve_human(&self, name: &str, siblings: &[PackageId]) -> Result<PackageId, GraphError> {
        if let Ok(PackageId::Prefixed { ecosystem, name: n }) = PackageId::parse(name) {
            if let Some(id) = self.prefixed.get(&(ecosystem, n)) {
                return Ok(id.clone());
            }
        }

        if let Some(id) = self.bare.get(name) {
            return Ok(id.clone());
        }

        let mut candidates = Vec::new();
        for ((_eco, n), id) in &self.prefixed {
            if n == name {
                candidates.push(id.clone());
            }
        }

        if candidates.len() == 1 {
            return Ok(candidates[0].clone());
        }

        if candidates.len() > 1 && !siblings.is_empty() {
            for sib in siblings {
                for cand in &candidates {
                    if cand.ecosystem() == sib.ecosystem() {
                        return Ok(cand.clone());
                    }
                }
            }
        }

        if candidates.is_empty() {
            Err(GraphError::UnknownPackage {
                id: PackageId::parse(name).unwrap_or_else(|_| PackageId::Bare(name.to_string())),
            })
        } else {
            Err(GraphError::AmbiguousName {
                name: name.to_string(),
                candidates,
            })
        }
    }

    /// Look up a package by its native (manifest-declared) name.
    ///
    /// First tries the exact `(eco, name)` key. If that misses -- a
    /// package in one ecosystem depending on a different ecosystem's
    /// package by bare name (e.g. an npm package listing a cargo crate)
    /// -- falls back to scanning all ecosystems for `name`.
    ///
    /// Fallback finds exactly one match: returns it. Finds more than one
    /// (two ecosystems both have `name`): returns `None` to prevent
    /// silent misresolution -- callers holding a `&mut Vec<Diagnostic>`
    /// should use [`Self::resolve_native_with_fallback`] instead, to get
    /// a diagnostic.
    pub fn resolve_native(&self, eco: Ecosystem, name: &str) -> Option<&PackageId> {
        // Fast path: exact ecosystem match.
        if let Some(id) = self.native.get(&(eco, name.to_string())) {
            return Some(id);
        }

        // Cross-ecosystem fallback.
        let mut candidates: Vec<&PackageId> = self
            .native
            .iter()
            .filter(|((e, n), _)| *e != eco && n == name)
            .map(|(_, id)| id)
            .collect();

        // Deduplicate by pointer identity (multiple entries for the same ID
        // across different ecosystems, e.g. a package that is both cargo and
        // npm, should not be treated as ambiguous).
        candidates.dedup_by(|a, b| a == b);

        match candidates.len() {
            1 => Some(candidates[0]),
            // 0 = not found; >1 = true ambiguity → caller should diagnose.
            _ => None,
        }
    }

    /// Like [`Self::resolve_native`] but pushes a [`callisto_model::Diagnostic`] when
    /// cross-ecosystem ambiguity is detected (two packages with the same bare
    /// name in different ecosystems).
    pub fn resolve_native_with_fallback<'a>(
        &'a self,
        eco: Ecosystem,
        name: &str,
        diagnostics: &mut Vec<callisto_model::Diagnostic>,
    ) -> Option<&'a PackageId> {
        // Fast path: exact ecosystem match.
        if let Some(id) = self.native.get(&(eco, name.to_string())) {
            return Some(id);
        }

        // Cross-ecosystem fallback: collect unique IDs from other ecosystems.
        let mut candidates: Vec<(Ecosystem, &PackageId)> = self
            .native
            .iter()
            .filter(|((e, n), _)| *e != eco && n == name)
            .map(|((e, _), id)| (*e, id))
            .collect();
        candidates.dedup_by(|a, b| a.1 == b.1);

        match candidates.len() {
            0 => None,
            _ => {
                let candidate_names: Vec<String> = candidates
                    .iter()
                    .map(|(e, id)| format!("{}:{}", e.prefix(), id.name()))
                    .collect();
                diagnostics.push(callisto_model::Diagnostic {
                    code: callisto_model::DiagnosticCode::UnknownPackage,
                    severity: callisto_model::DiagnosticSeverity::Warning,
                    message: format!(
                        "dependency name `{}` is ambiguous across ecosystems: {}; \
                         add an ecosystem prefix (e.g. `cargo:{}`) to disambiguate",
                        name,
                        candidate_names.join(", "),
                        name,
                    ),
                    package: None,
                    path: None,
                    escalated_by: None,
                    governed_by: None,
                });
                None
            }
        }
    }

    pub fn native_name(&self, id: &PackageId, eco: Ecosystem) -> Option<&str> {
        for ((e, name), registered_id) in &self.native {
            if e == &eco && registered_id == id {
                return Some(name.as_str());
            }
        }
        None
    }

    pub fn native_names(&self, id: &PackageId) -> impl Iterator<Item = (Ecosystem, &str)> {
        let mut results = Vec::new();
        for ((e, name), registered_id) in &self.native {
            if registered_id == id {
                results.push((*e, name.as_str()));
            }
        }
        results.into_iter()
    }

    pub fn display_form(&self, id: &PackageId) -> String {
        id.display_name()
    }

    pub fn platforms_of(&self, owner: &PackageId) -> impl Iterator<Item = (&str, &Path)> {
        let mut results = Vec::new();
        for (name, (plat_owner, path, _role)) in &self.platform {
            if plat_owner == owner {
                results.push((name.as_str(), path.as_path()));
            }
        }
        results.into_iter()
    }
}