Skip to main content

pmcp_package/
reference.rs

1//! Typed component references.
2//!
3//! A [`ComponentRef`] encodes the range-vs-pin distinction that makes the
4//! "converge on exact digests" property computable:
5//!
6//! - [`ComponentRef::Range`] — a capture-time semver range (e.g.
7//!   `london-tube@^1.2`), used while authoring/discovering components.
8//! - [`ComponentRef::Pinned`] — a finalized exact reference, wrapping a
9//!   [`PinnedRef`] whose `version` and `digest` fields are both non-`Option`.
10//!   A pin can never exist without a digest — this is a STRUCTURAL
11//!   guarantee (no field is missing at the type level), not a runtime check
12//!   that could be forgotten at some call site.
13//!
14//!   [`PinnedRef::resolved_from`] (D-10) is the struct's FIRST `Option`, and
15//!   it does NOT weaken that guarantee — `version` and `digest` remain
16//!   mandatory, so the "a pin can never exist without a digest" claim above
17//!   still holds exactly as stated. `resolved_from` is legitimately optional
18//!   for a different reason: it records the semver range a pin was resolved
19//!   FROM, and a direct pin genuinely had no declared range. A non-`Option`
20//!   field would force every direct pin to invent one, which would turn an
21//!   honestly-absent fact into a fabricated one.
22//!
23//! `PinnedRef` is a dedicated struct (not an inline enum-variant struct) so
24//! downstream helpers (e.g. `pinned_components() -> Result<Vec<&PinnedRef>>`)
25//! can name the pin body directly.
26//!
27//! ## Component identity (D-D)
28//!
29//! [`ComponentType`] is a SEPARATE axis from the `kind` discriminator above:
30//! `kind` says whether a reference is a range or a pin (a wire-shape
31//! concern); `component_type` says WHAT the referenced thing is — a server,
32//! an agent, or a team. A workflow graph can legitimately contain a server
33//! and an agent that share the same `name` (e.g. an agent named "x" that
34//! calls a server also named "x") — without `component_type`, those two
35//! pins would be indistinguishable by name alone. Both `ComponentRef`
36//! variants (`Range` and `Pinned`) carry a required `component_type` field
37//! so identity is unambiguous regardless of range-vs-pin state.
38
39use crate::digest::ManifestDigest;
40use serde::{Deserialize, Serialize};
41
42/// What kind of component a [`ComponentRef`] identifies. Ordering
43/// (`server < agent < team`, derived from declaration order via `Ord`) is
44/// the canonical type-then-name sort key `WorkflowManifest::new` uses (D-D).
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
46#[serde(rename_all = "snake_case")]
47pub enum ComponentType {
48    Server,
49    Agent,
50    Team,
51}
52
53/// An exact, digest-verified component pin. `version` and `digest` are both
54/// mandatory (non-`Option`) — a pin always carries both.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct PinnedRef {
57    pub name: String,
58    pub component_type: ComponentType,
59    pub version: semver::Version,
60    pub digest: ManifestDigest,
61    /// The semver range this pin was RESOLVED FROM, when it was resolved from
62    /// one. Same type as [`ComponentRef::Range`]'s `range` field, because a
63    /// resolution records the same kind of thing the range declared.
64    ///
65    /// # Why a pin keeps the range it resolved (D-10)
66    ///
67    /// Cargo's model, adopted deliberately because that logic is proven and
68    /// will pass the same security reviews. Cargo keeps TWO artifacts:
69    /// `Cargo.toml` holds the range (author intent — what enables reuse and
70    /// upgrade), `Cargo.lock` holds the resolution (the exact version plus its
71    /// checksum). Pinning never destroys the range.
72    ///
73    /// Before this field, [`ComponentRef`] was strictly either/or, so pinning
74    /// DISCARDED the declared range — losing the one fact the dev-to-prod case
75    /// turns on. A target environment could not distinguish *"dev declared
76    /// `^1.2` and resolved 1.3.0"* from *"dev declared `=1.2.0`"*. In the first
77    /// case prod's already-deployed 1.2.0 still satisfies `^1.2`, so it is
78    /// silently kept — the wrong reference, with nothing in the package able to
79    /// say so.
80    ///
81    /// # What `None` means — decided, not left implicit (D-10)
82    ///
83    /// `None` means "no declared range is recorded on this pin". It is NOT
84    /// distinguishable from "this package was packed before this field
85    /// existed": the additive serde attributes below make an old pin
86    /// deserialize to exactly the value a direct pin produces. The crate
87    /// ACCEPTS that ambiguity rather than carrying a schema-version
88    /// discriminator — `pmcp-package` is 0.x, and the standing position for the
89    /// package tree is to break freely rather than ship compatibility shims.
90    ///
91    /// Two obligations follow, and both are load-bearing:
92    ///
93    /// - **Consumer side.** Anything building skew reporting on this field —
94    ///   Phase 123's dev-to-prod import check is the named one — MUST treat
95    ///   `None` as "cannot report" and NEVER as "no skew". Reading an absent
96    ///   fact as a positive claim is precisely the failure this field exists to
97    ///   prevent.
98    /// - **Producer side.** A producer that resolved a range MUST record it. A
99    ///   `None` written by a range-resolving producer is indistinguishable from
100    ///   an old package, and destroys the signal for every consumer downstream.
101    ///
102    /// # Compatibility — both halves, because only stating one under-scopes the next change
103    ///
104    /// - **Serde/wire: ADDITIVE.** `#[serde(default)]` means pin JSON written
105    ///   before this field existed still deserializes (yielding `None`), and
106    ///   `skip_serializing_if` means nothing new is emitted for a `None`. No
107    ///   checked-in fixture byte and no pinned digest constant moves — measured,
108    ///   not assumed: all four `tests/golden_fixtures/canonical/*.json` files
109    ///   and all five pinned constants in `tests/digest_stability.rs` are
110    ///   byte-identical across this addition, and their tests pass unedited.
111    ///   `skip_serializing_if` is load-bearing here, not cosmetic: without it
112    ///   every pin would emit `"resolved_from": null`, and both
113    ///   `workflow.canonical.json` and `EXPECTED_WORKFLOW_DIGEST` would move.
114    ///
115    ///   A `Some(range)` DOES change the canonical bytes and therefore the
116    ///   manifest digest — see
117    ///   `recording_the_range_a_pin_resolved_changes_the_manifest_digest` in
118    ///   `tests/digest_stability.rs`. The field participates in package
119    ///   identity; it is not cosmetic metadata that could be stripped or forged
120    ///   without changing what the package IS.
121    /// - **Rust source: BREAKING.** `PinnedRef` had four public fields before
122    ///   this, all non-`Option`, all set by struct literal — a fifth field
123    ///   breaks every literal in the language, everywhere. The MEASURED
124    ///   inventory is EIGHT construction sites (`grep -rn 'PinnedRef {'
125    ///   --include="*.rs" crates cargo-pmcp` returns nine hits; the ninth is
126    ///   this struct's own `pub struct PinnedRef {` definition, which is not a
127    ///   construction site):
128    ///
129    ///   - `crates/pmcp-package/src/reference.rs` — 4 (all inside
130    ///     `#[cfg(test)] mod tests`)
131    ///   - `crates/pmcp-package/src/oci/unpack.rs` — 2 (both in a
132    ///     `#[cfg(test)]` fixture helper)
133    ///   - `crates/pmcp-package/src/package/workflow.rs` — 1 (`#[cfg(test)]`
134    ///     helper)
135    ///   - `crates/pmcp-team-servers/src/team/identity.rs` — 1 (`#[cfg(test)]`
136    ///     helper)
137    ///
138    ///   A reader who takes "additive" at face value will under-scope the next
139    ///   field addition exactly as this one would have been.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub resolved_from: Option<semver::VersionReq>,
142}
143
144/// A reference to a component: either a capture-time semver range or a
145/// finalized exact pin. The `kind` discriminator (`"range"` | `"pinned"`) is
146/// the wire-format contract other consumers key off of. `component_type` is
147/// a separate, required axis on BOTH variants (D-D) — see module docs.
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(tag = "kind", rename_all = "snake_case")]
150pub enum ComponentRef {
151    Range {
152        name: String,
153        range: semver::VersionReq,
154        component_type: ComponentType,
155    },
156    Pinned(PinnedRef),
157}
158
159impl ComponentRef {
160    /// The component name, regardless of variant.
161    pub fn name(&self) -> &str {
162        match self {
163            ComponentRef::Range { name, .. } => name,
164            ComponentRef::Pinned(pinned) => &pinned.name,
165        }
166    }
167
168    /// The component type, regardless of variant (D-D identity axis).
169    pub fn component_type(&self) -> ComponentType {
170        match self {
171            ComponentRef::Range { component_type, .. } => *component_type,
172            ComponentRef::Pinned(pinned) => pinned.component_type,
173        }
174    }
175
176    /// `true` if this reference is a finalized exact pin.
177    pub fn is_pinned(&self) -> bool {
178        matches!(self, ComponentRef::Pinned(_))
179    }
180
181    /// Borrow the pin body, if this reference is pinned.
182    pub fn as_pinned(&self) -> Option<&PinnedRef> {
183        match self {
184            ComponentRef::Pinned(pinned) => Some(pinned),
185            ComponentRef::Range { .. } => None,
186        }
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    fn sample_digest() -> ManifestDigest {
195        ManifestDigest::from_bytes(b"fixture-bytes")
196    }
197
198    #[test]
199    fn range_round_trips_with_kind_discriminator() {
200        let r = ComponentRef::Range {
201            name: "london-tube".to_string(),
202            range: semver::VersionReq::parse("^1.2").unwrap(),
203            component_type: ComponentType::Server,
204        };
205        let json = serde_json::to_value(&r).unwrap();
206        assert_eq!(json.get("kind").and_then(|v| v.as_str()), Some("range"));
207        assert_eq!(
208            json.get("name").and_then(|v| v.as_str()),
209            Some("london-tube")
210        );
211        assert_eq!(
212            json.get("component_type").and_then(|v| v.as_str()),
213            Some("server")
214        );
215        let back: ComponentRef = serde_json::from_value(json).unwrap();
216        assert_eq!(back, r);
217    }
218
219    #[test]
220    fn pinned_round_trips_flat_with_kind_discriminator() {
221        let pinned = PinnedRef {
222            name: "london-tube".to_string(),
223            component_type: ComponentType::Server,
224            version: semver::Version::parse("1.2.3").unwrap(),
225            digest: sample_digest(),
226            resolved_from: None,
227        };
228        let r = ComponentRef::Pinned(pinned.clone());
229        let json = serde_json::to_value(&r).unwrap();
230
231        // FLAT shape: {"kind":"pinned","name":...,"version":...,"digest":...}
232        // — NOT nested under a "Pinned" key.
233        let obj = json.as_object().expect("must serialize as a flat object");
234        let mut keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();
235        keys.sort_unstable();
236        assert_eq!(
237            keys,
238            vec!["component_type", "digest", "kind", "name", "version"]
239        );
240        assert_eq!(obj.get("kind").and_then(|v| v.as_str()), Some("pinned"));
241        assert_eq!(
242            obj.get("name").and_then(|v| v.as_str()),
243            Some("london-tube")
244        );
245        assert_eq!(obj.get("version").and_then(|v| v.as_str()), Some("1.2.3"));
246        assert_eq!(
247            obj.get("component_type").and_then(|v| v.as_str()),
248            Some("server")
249        );
250        assert!(obj
251            .get("digest")
252            .and_then(|v| v.as_str())
253            .unwrap()
254            .starts_with("sha256:"));
255
256        let back: ComponentRef = serde_json::from_value(json).unwrap();
257        assert_eq!(back, r);
258    }
259
260    #[test]
261    fn pinned_ref_always_carries_version_and_digest() {
262        // Structural test: PinnedRef's fields are non-Option — this compiles
263        // only because both fields are mandatory at construction.
264        let pinned = PinnedRef {
265            name: "x".to_string(),
266            component_type: ComponentType::Server,
267            version: semver::Version::parse("0.1.0").unwrap(),
268            digest: sample_digest(),
269            resolved_from: None,
270        };
271        assert_eq!(pinned.version.to_string(), "0.1.0");
272        assert!(pinned.digest.as_str().starts_with("sha256:"));
273    }
274
275    #[test]
276    fn name_accessor_works_for_both_variants() {
277        let range = ComponentRef::Range {
278            name: "a".to_string(),
279            range: semver::VersionReq::parse("^1").unwrap(),
280            component_type: ComponentType::Server,
281        };
282        assert_eq!(range.name(), "a");
283        assert!(!range.is_pinned());
284        assert!(range.as_pinned().is_none());
285
286        let pinned = ComponentRef::Pinned(PinnedRef {
287            name: "b".to_string(),
288            component_type: ComponentType::Agent,
289            version: semver::Version::parse("2.0.0").unwrap(),
290            digest: sample_digest(),
291            resolved_from: None,
292        });
293        assert_eq!(pinned.name(), "b");
294        assert!(pinned.is_pinned());
295        assert!(pinned.as_pinned().is_some());
296    }
297
298    #[test]
299    fn component_type_orders_server_before_agent_before_team() {
300        assert!(ComponentType::Server < ComponentType::Agent);
301        assert!(ComponentType::Agent < ComponentType::Team);
302        assert!(ComponentType::Server < ComponentType::Team);
303    }
304
305    /// A pin that records no declared range must emit NO key for it, so every
306    /// package written before the field existed stays byte-identical.
307    #[test]
308    fn a_pin_with_no_resolved_range_emits_exactly_the_original_five_keys() {
309        let r = ComponentRef::Pinned(PinnedRef {
310            name: "london-tube".to_string(),
311            component_type: ComponentType::Server,
312            version: semver::Version::parse("1.2.3").unwrap(),
313            digest: sample_digest(),
314            resolved_from: None,
315        });
316        let json = serde_json::to_value(&r).unwrap();
317        let obj = json.as_object().expect("must serialize as a flat object");
318
319        let mut keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();
320        keys.sort_unstable();
321        assert_eq!(
322            keys,
323            vec!["component_type", "digest", "kind", "name", "version"],
324            "a `None` resolved_from must emit no key at all — `skip_serializing_if` is what \
325             keeps every checked-in fixture and every pinned digest constant unmoved"
326        );
327        assert!(
328            !obj.contains_key("resolved_from"),
329            "not even a null: a null would move the canonical bytes"
330        );
331
332        let back: ComponentRef = serde_json::from_value(json).unwrap();
333        assert_eq!(back, r);
334    }
335
336    /// The Cargo half (D-10): a pin resolved FROM a range carries that range,
337    /// so a target environment can tell `^1.2 -> 1.3.0` from `=1.2.0`.
338    #[test]
339    fn a_pin_carrying_the_range_it_resolved_emits_it_and_round_trips() {
340        let declared = semver::VersionReq::parse("^1.2").unwrap();
341        let r = ComponentRef::Pinned(PinnedRef {
342            name: "london-tube".to_string(),
343            component_type: ComponentType::Server,
344            version: semver::Version::parse("1.3.0").unwrap(),
345            digest: sample_digest(),
346            resolved_from: Some(declared.clone()),
347        });
348        let json = serde_json::to_value(&r).unwrap();
349        let obj = json.as_object().expect("must serialize as a flat object");
350
351        let mut keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();
352        keys.sort_unstable();
353        assert_eq!(
354            keys,
355            vec![
356                "component_type",
357                "digest",
358                "kind",
359                "name",
360                "resolved_from",
361                "version"
362            ]
363        );
364        assert_eq!(
365            obj.get("resolved_from").and_then(|v| v.as_str()),
366            Some("^1.2"),
367            "the declared range is recorded verbatim, not collapsed into the resolution"
368        );
369        // Both facts survive together: what was asked for AND what was chosen.
370        assert_eq!(obj.get("version").and_then(|v| v.as_str()), Some("1.3.0"));
371
372        let back: ComponentRef = serde_json::from_value(json).unwrap();
373        assert_eq!(back, r);
374        assert_eq!(back.as_pinned().unwrap().resolved_from, Some(declared));
375    }
376
377    /// Backward compatibility, asserted against a hand-written JSON literal
378    /// rather than a re-serialized value — the literal IS what a package
379    /// written before this field existed contains on disk.
380    #[test]
381    fn pin_json_written_before_resolved_from_existed_deserializes_to_none() {
382        let legacy = serde_json::json!({
383            "kind": "pinned",
384            "name": "london-tube",
385            "component_type": "server",
386            "version": "1.2.3",
387            "digest": sample_digest().as_str(),
388        });
389
390        let back: ComponentRef =
391            serde_json::from_value(legacy).expect("five-key pin JSON must still deserialize");
392        let pin = back.as_pinned().expect("must deserialize as a pin");
393        assert_eq!(
394            pin.resolved_from, None,
395            "an absent key must degrade to a defined value, never a decode failure"
396        );
397        assert_eq!(pin.version.to_string(), "1.2.3");
398    }
399
400    #[test]
401    fn component_type_accessor_works_for_both_variants() {
402        let range = ComponentRef::Range {
403            name: "x".to_string(),
404            range: semver::VersionReq::parse("^1").unwrap(),
405            component_type: ComponentType::Team,
406        };
407        assert_eq!(range.component_type(), ComponentType::Team);
408
409        let pinned = ComponentRef::Pinned(PinnedRef {
410            name: "x".to_string(),
411            component_type: ComponentType::Agent,
412            version: semver::Version::parse("1.0.0").unwrap(),
413            digest: sample_digest(),
414            resolved_from: None,
415        });
416        assert_eq!(pinned.component_type(), ComponentType::Agent);
417    }
418}