Skip to main content

ossctl_core/contract/
schema.rs

1//! The ONE canonical serde model for `OSS-RELEASE.md` (ADR-0003 §1).
2//!
3//! These types are the single normalization model that `contract show`,
4//! `contract validate`, `audit`, the facts consumers, and release planning all
5//! use — no second parser anywhere. Their serialized form is the canonical
6//! JSON contract every `/oss-*` member reads (SCHEMA.md §4, preserved
7//! byte-for-shape by the migration rule). Public wire access goes through
8//! [`crate::protocol::contract`], which re-exports these types and owns the
9//! wire-version declaration so internals and wire can diverge under the
10//! migration rule (ADR-0001 §2).
11//!
12//! Hot file (ADR-0001): a change here ripples to every family member. Every
13//! enum's [`as_str`](Status::as_str) form is the wire string; a change to one is
14//! a `schema_version` bump, never silent.
15
16use serde::Serialize;
17
18/// The contract `schema_version` this build knows how to read.
19///
20/// A config declaring a higher version is refused rather than guessed
21/// (SCHEMA.md §2 floor 5) — skills upgrade independently of the repos they act
22/// on. Distinct from the wire-envelope [`crate::SCHEMA_VERSION`], which versions
23/// the JSON envelope, not the contract document. Mirrors the Python
24/// `KNOWN_SCHEMA_VERSION`.
25///
26/// **Bumped `1` → `2`** for the monorepo-distribution change: the single
27/// top-level [`Distribution`] key `distribution` (an object-or-`null`) became the
28/// collection [`Contract::distributions`] (`distributions`, always a JSON array),
29/// and every distribution gained an association key [`Distribution::package`].
30/// Renaming the canonical key and re-shaping the value is a **breaking** change,
31/// not a pure addition, so it bumps deliberately (never silently). This tool
32/// still *reads* a v1 document — a bare `distribution:` mapping deserializes as a
33/// one-element `distributions` list — but *emits* the v2 canonical shape.
34///
35/// A purely additive field (a new optional top-level key defaulting to
36/// absent/`null`) does NOT bump: an older reader preserves the unknown key under
37/// [`Contract::extra_fields`] and warns rather than failing. The migration rule
38/// bumps only on a **breaking** change — renaming/removing a field or re-meaning
39/// an existing one — never on a pure addition, which the forward-compat mechanism
40/// absorbs.
41pub const KNOWN_SCHEMA_VERSION: u32 = 2;
42
43/// The changelog fragment directory materialized when the config omits it.
44pub const DEFAULT_FRAGMENT_DIR: &str = "changelog/fragments";
45
46/// The cross-platform default [`Distribution::platforms`] set materialized when a
47/// distribution block omits `platforms`: macOS (`aarch64` + `x86_64`) and Linux
48/// (`aarch64` + `x86_64`). This is the KEYSTONE of the cross-platform install
49/// requirement — a distribution that OMITS `platforms` covers Linux **by
50/// default**, so a repo that never thinks about it still ships Linux binaries. (A
51/// repo that sets `platforms` explicitly owns its own coverage; the cross-platform
52/// `audit` — not this default — flags a Linux-less explicit set.) musl over gnu for
53/// Linux: for a pure-Rust CLI a musl target links statically and sidesteps the
54/// glibc-version cliff — though choosing a musl *target* does not by itself
55/// guarantee a static build, and a repo with C/native dependencies (`openssl-sys`,
56/// `libgit2`, …) may need to override to gnu. Windows is a deliberate omission (a
57/// bonus a repo opts into by listing it explicitly, never the default). The set
58/// always contains at least one Linux triple.
59pub const DEFAULT_CROSS_PLATFORM_TARGETS: [&str; 4] = [
60    "aarch64-apple-darwin",
61    "x86_64-apple-darwin",
62    "aarch64-unknown-linux-musl",
63    "x86_64-unknown-linux-musl",
64];
65
66/// Define a closed enum whose variants each map to a fixed wire string.
67///
68/// Generates the enum (with the standard derives), [`as_str`] (variant → wire),
69/// [`parse`] (wire → variant), the `VALID` slice of wire strings for error
70/// messages, and a `Serialize` impl that emits the wire string. `Deserialize`
71/// is intentionally not generated: the normalizer reads strings out of the
72/// parsed YAML and validates each with [`parse`] so it can collect *all* errors
73/// and substitute a default (mirroring the Python normalizer), rather than
74/// fail-fast on the first bad enum.
75macro_rules! wire_enum {
76    (
77        $(#[$emeta:meta])*
78        $name:ident { $($variant:ident => $wire:literal),+ $(,)? }
79    ) => {
80        $(#[$emeta])*
81        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82        pub enum $name {
83            $(
84                #[doc = concat!("Wire value `", $wire, "`.")]
85                $variant,
86            )+
87        }
88
89        impl $name {
90            /// The wire string for this variant (matches SCHEMA.md §4).
91            #[must_use]
92            pub fn as_str(self) -> &'static str {
93                match self { $(Self::$variant => $wire),+ }
94            }
95
96            /// Parse a wire string into the variant, or `None` if unrecognized.
97            #[must_use]
98            pub fn parse(s: &str) -> Option<Self> {
99                match s { $($wire => Some(Self::$variant),)+ _ => None }
100            }
101
102            /// Every valid wire string, for "must be one of …" messages.
103            pub const VALID: &'static [&'static str] = &[$($wire),+];
104        }
105
106        impl serde::Serialize for $name {
107            fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
108                ser.serialize_str(self.as_str())
109            }
110        }
111    };
112}
113
114wire_enum! {
115    /// Machine-readable approval gate (SCHEMA.md §1). `/oss-init` writes `draft`
116    /// and stops; a human flips it to `approved`. Mutating members refuse a
117    /// draft (they pass `--require-approved`).
118    Status { Draft => "draft", Approved => "approved" }
119}
120
121wire_enum! {
122    /// Master maturity dial that gates every member's output (SCHEMA.md §1).
123    /// Required — inference is `/oss-init`'s job, not the normalizer's.
124    Maturity { Spike => "spike", Mvp => "mvp", Production => "production" }
125}
126
127wire_enum! {
128    /// A packaging ecosystem. `homebrew` is a distribution *target*, never an
129    /// ecosystem. Listed in the canonical order used for stable de-dup/expansion.
130    Ecosystem {
131        Rust => "rust", Node => "node", Python => "python", Go => "go", Binary => "binary"
132    }
133}
134
135wire_enum! {
136    /// Base versioning scheme (SCHEMA.md §1). A `calver:<pattern>` config splits
137    /// into `Calver` + a separate [`Contract::versioning_pattern`]; the wire form
138    /// never carries the `calver:` prefix.
139    VersioningBase { Semver => "semver", Calver => "calver", Zerover => "zerover" }
140}
141
142wire_enum! {
143    /// How the changelog is produced (SCHEMA.md §1).
144    ChangelogMode { Curated => "curated", Automated => "automated", Fragment => "fragment" }
145}
146
147wire_enum! {
148    /// The changelog's structured input (SCHEMA.md §1).
149    ChangelogSource {
150        IssuectlTrailers => "issuectl-trailers",
151        ConventionalCommits => "conventional-commits",
152        Manual => "manual"
153    }
154}
155
156wire_enum! {
157    /// Release trigger model (SCHEMA.md §1). `auto` installs an on-merge
158    /// workflow; it never publishes from a chat turn.
159    ReleaseModel { Gated => "gated", Auto => "auto" }
160}
161
162wire_enum! {
163    /// Repository release layout (SCHEMA.md §1). `monorepo` drives per-package
164    /// versions/tags and flips the node adapter default to `changesets`.
165    ReleaseLayout { Single => "single", Monorepo => "monorepo" }
166}
167
168wire_enum! {
169    /// Contributor sign-off requirement, read by `/oss-contributing`.
170    ContributionProvenance { Dco => "dco", Cla => "cla", None => "none" }
171}
172
173wire_enum! {
174    /// Build-provenance level (SCHEMA.md §1). `slsa-l3` is production-only (floor).
175    ProvenanceLevel { None => "none", Keyless => "keyless", SlsaL3 => "slsa-l3" }
176}
177
178wire_enum! {
179    /// Which dependency-update bot `/oss-ci` emits.
180    DependencyBot { Dependabot => "dependabot", Renovate => "renovate", None => "none" }
181}
182
183wire_enum! {
184    /// A README health badge (SCHEMA.md §1). Every badge needs its producer
185    /// enabled (floor 4).
186    HealthBadge {
187        Ci => "ci", Registry => "registry", License => "license",
188        Coverage => "coverage", Scorecard => "scorecard", Discord => "discord"
189    }
190}
191
192wire_enum! {
193    /// Optional documentation-site generator (SCHEMA.md §1); production-tier.
194    DocsSite {
195        None => "none", Mkdocs => "mkdocs", Vitepress => "vitepress",
196        Docusaurus => "docusaurus", Sphinx => "sphinx", Mintlify => "mintlify"
197    }
198}
199
200wire_enum! {
201    /// A publish destination for a [`Target`] (SCHEMA.md §1).
202    Registry {
203        CratesIo => "crates.io", Npm => "npm", Pypi => "pypi", TestPypi => "testpypi",
204        GhReleases => "gh-releases", ProxyGolangOrg => "proxy.golang.org",
205        Homebrew => "homebrew"
206    }
207}
208
209wire_enum! {
210    /// The release tool pinned for a [`Target`] so it is not re-inferred each cut.
211    Adapter {
212        CargoPublish => "cargo-publish", CargoDist => "cargo-dist",
213        ReleasePlease => "release-please", Changesets => "changesets",
214        GhActionPypiPublish => "gh-action-pypi-publish", Twine => "twine",
215        Goreleaser => "goreleaser", HomebrewTap => "homebrew-tap",
216        HomebrewCore => "homebrew-core", NpmPublish => "npm-publish", Manual => "manual"
217    }
218}
219
220wire_enum! {
221    /// The binary-distribution engine that produces multi-platform GitHub-Release
222    /// artifacts plus a generated installer set (distinct from a registry
223    /// [`Adapter`]). Owned by a tag-triggered `release.yml` the family must NOT
224    /// regenerate — hence first-class in the contract.
225    DistributionAdapter {
226        CargoDist => "cargo-dist", Goreleaser => "goreleaser", Manual => "manual"
227    }
228}
229
230wire_enum! {
231    /// An installer flavor a [`Distribution`] emits. `homebrew` requires a
232    /// [`Distribution::homebrew_tap`] (floor).
233    Installer {
234        Shell => "shell", Powershell => "powershell", Homebrew => "homebrew",
235        Msi => "msi", Npm => "npm"
236    }
237}
238
239impl Ecosystem {
240    /// The default registry for this ecosystem when `targets` is expanded
241    /// (SCHEMA.md §1 default-expansion table).
242    #[must_use]
243    pub fn default_registry(self) -> Registry {
244        match self {
245            Self::Rust => Registry::CratesIo,
246            Self::Node => Registry::Npm,
247            Self::Python => Registry::Pypi,
248            Self::Go => Registry::ProxyGolangOrg,
249            Self::Binary => Registry::GhReleases,
250        }
251    }
252
253    /// The default adapter for this ecosystem/layout when `targets` is expanded
254    /// (SCHEMA.md §1). Node's default is layout-sensitive: `single` →
255    /// `release-please`, `monorepo` → `changesets`.
256    #[must_use]
257    pub fn default_adapter(self, layout: ReleaseLayout) -> Adapter {
258        match self {
259            Self::Rust => Adapter::CargoPublish,
260            Self::Node => match layout {
261                ReleaseLayout::Monorepo => Adapter::Changesets,
262                ReleaseLayout::Single => Adapter::ReleasePlease,
263            },
264            Self::Python => Adapter::GhActionPypiPublish,
265            Self::Go => Adapter::Goreleaser,
266            Self::Binary => Adapter::Manual,
267        }
268    }
269}
270
271/// One concrete `ecosystem → package → registry` publish destination.
272///
273/// Always concrete in the canonical output: expanded from `ecosystems` when the
274/// source omitted `targets`. `package` may be `null` (the executor infers it
275/// from the manifest); every other field is present.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
277pub struct Target {
278    /// The ecosystem this target publishes for.
279    pub ecosystem: Ecosystem,
280    /// The package/crate name, or `null` when inferred from the manifest.
281    pub package: Option<String>,
282    /// The publish destination.
283    pub registry: Registry,
284    /// The release tool pinned for this target.
285    pub adapter: Adapter,
286}
287
288/// The binary-distribution block: multi-platform GitHub-Release binaries, a
289/// generated installer set, and an optional Homebrew tap — produced by a
290/// tag-triggered release workflow (cargo-dist / goreleaser).
291///
292/// SEPARATE from [`Target`] (registry publishes): a cargo-dist repo attaches
293/// per-platform binaries to its GitHub Release, ships a shell/Homebrew installer,
294/// **and** independently publishes its crate to crates.io — the crates.io publish
295/// is a [`Target`]; everything binary-distribution is this block. The two coexist,
296/// which is exactly the "registry publish alongside a cargo-dist release" the
297/// contract could not express before. First-class (not prose) so downstream
298/// members SEE the tap + installer and neither under-describe the release nor
299/// regenerate the existing `release.yml`.
300///
301/// One element of [`Contract::distributions`]: a registry-only repo has an empty
302/// list, a single-binary repo one entry, a **monorepo** one entry per
303/// independently-distributed binary (each with its own installers / tap /
304/// platforms), tagged by [`Self::package`].
305///
306/// Keeps `Eq` even after gaining [`Self::extra_fields`]: `serde_json::Value`
307/// (and `serde_json::Map`) implement `Eq` — JSON numbers exclude non-finite
308/// floats — so the added field does not weaken the derive (unlike the sibling
309/// [`Contract`], which is `PartialEq`-only for unrelated historical reasons).
310#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
311pub struct Distribution {
312    /// The package/target this distribution belongs to (matches a
313    /// [`Target::package`] or a manifest package name), or `null` for the sole /
314    /// unassociated distribution.
315    ///
316    /// The monorepo association key: a repo shipping multiple independently
317    /// distributed binaries gives each its own [`Distribution`] tagged with the
318    /// package it builds. `null` is the single-distribution back-compat case (a
319    /// bare `distribution:` mapping carries no package). The normalizer requires a
320    /// non-null, **unique** `package` on every entry once there are two or more
321    /// distributions — otherwise a monorepo's entries would be indistinguishable.
322    pub package: Option<String>,
323    /// The binary-distribution engine that owns the tag-triggered release
324    /// workflow.
325    pub adapter: DistributionAdapter,
326    /// Whether multi-platform binaries are attached to the GitHub Release.
327    pub gh_releases: bool,
328    /// Installer flavors this release produces (may be empty), canonically
329    /// ordered and de-duplicated.
330    pub installers: Vec<Installer>,
331    /// The Homebrew tap repo (`owner/repo`) the generated formula is pushed to,
332    /// or `null` when no tap is used. Required when `installers` includes
333    /// `homebrew` (floor).
334    pub homebrew_tap: Option<String>,
335    /// The platform target set — the target-triples this binary distribution builds
336    /// and ships, in Rust target-triple form (the vocabulary the `cargo-dist`
337    /// adapter consumes; a `goreleaser`/`manual` remodel into an adapter-neutral
338    /// shape is deliberately left to a follow-up). Always non-empty in the canonical
339    /// output: defaulted to the cross-platform [`DEFAULT_CROSS_PLATFORM_TARGETS`] set
340    /// (macOS + Linux) when the source OMITS it (an explicit empty list is rejected,
341    /// not defaulted), so a distribution that doesn't specify platforms still covers
342    /// Linux (the cross-platform install requirement). An explicit set is validated
343    /// per triple and de-duplicated, preserving the author's order. Validation is
344    /// STRUCTURAL, not semantic — a well-formed triple whose OS component stays
345    /// inspectable, so the cross-platform `audit` can flag a Linux-less explicit set;
346    /// the normalizer guarantees only that the field is present and every triple
347    /// well-formed, never that the set covers any particular OS or that the toolchain
348    /// will build it.
349    pub platforms: Vec<String>,
350    /// Preserved unknown keys inside the `distribution` block under a known
351    /// `schema_version` (forward-compat), so an older reader round-trips a newer
352    /// contract's distribution sub-keys rather than dropping them. Mirrors
353    /// [`Contract::extra_fields`] at the nested level; empty for a contract with
354    /// no unknown distribution keys.
355    ///
356    /// An EMPTY map is OMITTED from canonical JSON (`skip_serializing_if`), so a
357    /// distribution with no unknown keys carries no `extra_fields` key at all — the
358    /// "additive = absent-by-default" migration rule holds literally, and a
359    /// populated map serializes exactly as before. Kept symmetric with
360    /// [`Contract::extra_fields`] (both omit-when-empty).
361    #[serde(skip_serializing_if = "serde_json::Map::is_empty")]
362    pub extra_fields: serde_json::Map<String, serde_json::Value>,
363}
364
365/// The changelog block of the contract (SCHEMA.md §1). `fragment_dir` is always
366/// present, even for non-`fragment` modes.
367#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
368pub struct Changelog {
369    /// How the changelog is produced.
370    pub mode: ChangelogMode,
371    /// The changelog's structured input.
372    pub source: ChangelogSource,
373    /// Where changelog fragments live (relative path inside the repo).
374    pub fragment_dir: String,
375}
376
377/// The release block of the contract (SCHEMA.md §1).
378#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
379pub struct Release {
380    /// Release trigger model.
381    pub model: ReleaseModel,
382    /// Repository release layout.
383    pub layout: ReleaseLayout,
384}
385
386/// The canonical, fully-defaulted, `targets`-expanded `OSS-RELEASE.md` contract.
387///
388/// This is the exact shape of SCHEMA.md §4 (the stable machine contract). Every
389/// field is present and defaulted; `versioning` is the base enum with the
390/// calver pattern split into [`Self::versioning_pattern`]; `extra_fields` holds
391/// preserved unknown frontmatter keys (forward-compat); `warnings` holds the
392/// non-fatal notes. Field order matches SCHEMA.md §4 for readable output; JSON
393/// consumers key-access, so order is not part of the contract.
394#[derive(Debug, Clone, PartialEq, Serialize)]
395pub struct Contract {
396    /// Contract schema version (bounded by [`KNOWN_SCHEMA_VERSION`]).
397    pub schema_version: u32,
398    /// Approval gate.
399    pub status: Status,
400    /// Maturity dial.
401    pub maturity: Maturity,
402    /// Packaging ecosystems, de-duplicated to canonical order.
403    pub ecosystems: Vec<Ecosystem>,
404    /// Concrete registry publish targets. Expanded from `ecosystems` when the
405    /// `targets` key is OMITTED (or written as a bare `targets:` / `targets: null`,
406    /// which read as absent); an explicit empty `targets: []` — the literal empty
407    /// sequence — is the author's authoritative "never publish anywhere" and is
408    /// honored as an empty set (not re-expanded), the machine-readable way to
409    /// declare a version-tracked but unpublished repo. An empty set is a valid,
410    /// honored state, not a misconfiguration. This re-meaning of the specific `[]`
411    /// value did NOT bump [`KNOWN_SCHEMA_VERSION`] deliberately: the serialized
412    /// shape is a JSON array either way (an empty array is already producible today
413    /// by a contract with no ecosystems), so every consumer that reads `targets`
414    /// already handles `[]` — no reader breaks.
415    pub targets: Vec<Target>,
416    /// The binary-distribution blocks (cargo-dist / goreleaser binaries +
417    /// installers + Homebrew tap). Empty for a registry-only repo, one entry for
418    /// a single-binary repo, one per independently-distributed binary for a
419    /// **monorepo** (each tagged by [`Distribution::package`]). Always a JSON
420    /// array in canonical output. Coexists with `targets` — a cargo-dist repo has
421    /// both. A bare `distribution:` mapping in the source deserializes as a
422    /// one-element list (v1 back-compat); a `distributions:` sequence carries many.
423    pub distributions: Vec<Distribution>,
424    /// Base versioning scheme.
425    pub versioning: VersioningBase,
426    /// The calver pattern string, or `null` for non-calver schemes.
427    pub versioning_pattern: Option<String>,
428    /// Changelog configuration.
429    pub changelog: Changelog,
430    /// Whether `/oss-release-cut` may derive the bump from commit types.
431    pub conventional_commits: bool,
432    /// Release model + layout.
433    pub release: Release,
434    /// Contributor sign-off requirement.
435    pub contribution_provenance: ContributionProvenance,
436    /// Build-provenance level.
437    pub provenance_level: ProvenanceLevel,
438    /// Dependency-update bot.
439    pub dependency_bot: DependencyBot,
440    /// README health badges.
441    pub health_badges: Vec<HealthBadge>,
442    /// SPDX license id/expression.
443    pub license: String,
444    /// Optional documentation-site generator.
445    pub docs_site: DocsSite,
446    /// Preserved unknown frontmatter keys under a known `schema_version`
447    /// (forward-compat); never dropped.
448    ///
449    /// An EMPTY map is OMITTED from canonical JSON (`skip_serializing_if`), so a
450    /// contract with no unknown keys carries no `extra_fields` key at all — the
451    /// "additive = absent-by-default" migration rule holds literally, and a
452    /// populated map serializes exactly as before. Kept symmetric with
453    /// [`Distribution::extra_fields`] (both omit-when-empty).
454    #[serde(skip_serializing_if = "serde_json::Map::is_empty")]
455    pub extra_fields: serde_json::Map<String, serde_json::Value>,
456    /// Non-fatal notes (aspirational draft producers, the unknown-field report).
457    pub warnings: Vec<String>,
458}