caixa_core/version.rs
1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6/// A caixa's pinned version — a thin typed wrapper over a String that parses
7/// as [`semver::Version`] on demand.
8///
9/// Stored as a String at rest so authoring a `caixa.lisp` stays a single
10/// quoted literal. The typed form is reached through [`Self::parse`].
11#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
12#[serde(transparent)]
13pub struct CaixaVersion(pub String);
14
15impl CaixaVersion {
16 /// Parse and validate the wrapped string as semver.
17 pub fn parse(&self) -> Result<semver::Version, VersionError> {
18 semver::Version::parse(&self.0)
19 .map_err(|e| VersionError::semver(self.0.clone(), e.to_string()))
20 }
21
22 /// Borrow the string form.
23 #[must_use]
24 pub const fn as_str(&self) -> &str {
25 self.0.as_str()
26 }
27}
28
29impl fmt::Display for CaixaVersion {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 f.write_str(&self.0)
32 }
33}
34
35impl From<String> for CaixaVersion {
36 fn from(s: String) -> Self {
37 Self(s)
38 }
39}
40
41impl From<&str> for CaixaVersion {
42 fn from(s: &str) -> Self {
43 Self(s.to_string())
44 }
45}
46
47/// Substrate-canonical [`AsRef<str>`] projection on the [`CaixaVersion`]
48/// typed newtype — routes through the same [`CaixaVersion::as_str`]
49/// `pub const fn` scalar accessor the sibling [`fmt::Display`] impl
50/// and every downstream `&str`-shaped consumer already keys off, so
51/// any future consumer that binds a [`CaixaVersion`] through the
52/// standard-library `impl AsRef<str>` bound (a `Path`-shaped file-
53/// system reader on the operator side that accepts the version body
54/// as one segment of a per-caixa `versao/<v>/...` on-disk cache path,
55/// a builder-shaped API on the future `feira publish` writer verb
56/// that composes `<prefix><versao>` through a git-tag builder crate's
57/// `impl AsRef<str>` join step, a `HashMap<CaixaVersion, _>` lookup
58/// through the `map.get::<str>(v.as_ref())` shape a future
59/// version-keyed dispatch table lands on) reaches the wrapped
60/// [`String`] through one substrate-primitive dispatch rather than
61/// through the pre-lift `.as_str()` open-coded projection at every
62/// wire-up.
63///
64/// Peer of the sibling [`fmt::Display`] impl on the same primitive —
65/// both delegate to the shared [`CaixaVersion::as_str`] `pub const
66/// fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
67/// `<CaixaVersion as AsRef<str>>::as_ref(&v)` resolve to the same
68/// byte-string per instance by construction. A future rebrand of the
69/// wrapped storage (a hypothetical widening to a typed [`semver::Version`]
70/// slot the roadmap acknowledges once eager parse-on-construct
71/// discipline lands, an internal normalization step that trims
72/// leading zeroes off pre-release identifiers, a per-cluster overlay
73/// the operator pins through a future `:versao-overrides` slot) that
74/// changes what [`CaixaVersion::as_str`] returns migrates every
75/// consumer of every one of the three paths in lockstep.
76///
77/// Same "route the trait impl through the substrate-primitive
78/// accessor" discipline the sibling [`fmt::Display`] impl on this
79/// type already carries — extends it onto the standard-library
80/// [`AsRef<str>`] projection axis every third-party API that takes
81/// `impl AsRef<str>` (the [`std::path::Path::new`] / [`std::fs`]
82/// interop surface, [`std::process::Command::arg`], the peer
83/// `tracing::field::Value` recorder's `Str`-arm, every `clap`-side
84/// `value_parser!` fold that accepts an owned newtype through
85/// `impl AsRef<str>`) already binds through. Rust-side newtype
86/// convention pairs `AsRef<str>` and [`fmt::Display`] on the same
87/// primitive so a caller who has one has both; before this lift,
88/// [`CaixaVersion`] carried [`fmt::Display`] but not the paired
89/// [`AsRef<str>`] impl the convention names.
90///
91/// The first standard-library trait added to [`CaixaVersion`] beyond
92/// the pre-existing [`serde::Serialize`] / [`serde::Deserialize`] /
93/// [`Debug`] / [`Clone`] / [`PartialEq`] / [`Eq`] / [`Hash`] derives
94/// and the paired [`fmt::Display`] / [`From<String>`] / [`From<&str>`]
95/// hand-written impls. Pinned load-bearing by
96/// [`tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
97/// (byte-parity pin against [`CaixaVersion::as_str`]) — any future
98/// silent detour that routes the impl through a divergent projection
99/// (a `Cow<'_, str>` intermediate, a stray `.to_lowercase()`
100/// normalization, a swap onto a per-arm inline `&self.0.as_str()`
101/// re-inlining) trips at caixa-core test time under `assert_eq!`
102/// rather than at a downstream `impl AsRef<str>`-bound consumer's
103/// silent split.
104impl AsRef<str> for CaixaVersion {
105 fn as_ref(&self) -> &str {
106 self.as_str()
107 }
108}
109
110/// Trait-idiomatic *owned-`String`* reverse projection on the
111/// [`CaixaVersion`] newtype primitive — the owned-heap-string inverse
112/// of the pre-existing [`From<String> for CaixaVersion`] /
113/// [`From<&str> for CaixaVersion`] forward-projection pair on this
114/// primitive. Returns the wrapped [`String`] verbatim ([`Self::0`],
115/// a move of the pre-existing heap allocation — no re-copy of the
116/// per-instance version body's bytes), so every consumer that binds a
117/// [`CaixaVersion`] through the standard-library `.into()` /
118/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis
119/// reaches the wrapped byte-string through one substrate-primitive
120/// dispatch rather than through a `.as_str().to_owned()` /
121/// `.to_string()` allocating detour whose bounds have no compile-time
122/// link back to the newtype's storage.
123///
124/// A future consumer that wants to unwrap a [`CaixaVersion`] into an
125/// owned [`String`] — a `serde_json::Value::String(versao.into())`
126/// structured-payload composer where the `Value::String` arm typing
127/// demands an owned [`String`] and the sibling
128/// [`AsRef<str>`]-borrowed axis forces an explicit `.to_owned()`
129/// restatement at every call site, a future
130/// `HashMap::<String, _>::from_iter([(versao.into(), _)])` per-versao
131/// lookup where the map's key type is owned [`String`] rather than
132/// [`&str`] borrowed from a stashed [`CaixaVersion`], a future
133/// `Cow::<'static, str>::Owned(versao.into())` composer where the
134/// owned arm typing rules out the borrowed [`AsRef<str>`] return —
135/// reaches the wrapped [`String`] through this one dispatch, avoiding
136/// the pre-lift double-allocation (`.as_str().to_owned()` on the owned
137/// path would allocate a fresh [`String`] rather than reuse the
138/// wrapper's own heap allocation).
139///
140/// Opens the trait-idiomatic *owned-`String`* reverse-projection axis
141/// on the substrate's core String-wrapper newtype primitive
142/// [`CaixaVersion`], mirroring the paired owned-`String` forward-
143/// projection family the sibling closed-set fieldless typed enums
144/// ([`crate::supervisor::RestartStrategy`] (7baa18a, first-mover),
145/// [`crate::supervisor::RestartPolicy`] (7851725),
146/// [`crate::CaixaKind`] (per its own doc block, third peer), plus the
147/// remaining twelve closed-set enums) already carry — Rust's standard
148/// library does not derive `From<Self> for String` from `From<String>
149/// for Self`, so every newtype that carries a forward `From<String>`
150/// constructor but not the paired reverse-unwrap axis forces every
151/// call site through a `.to_string()` / `.as_str().to_owned()` detour
152/// that allocates fresh bytes rather than moving the wrapper's own
153/// heap allocation.
154///
155/// Preserves the two-path split on the wrapped byte-string: the paired
156/// [`AsRef<str>`] and [`fmt::Display`] impls stay reachable for the
157/// borrowed `&str` and formatter-output paths, this impl closes the
158/// owned-`String` reverse axis. Same "one dispatch on the substrate
159/// primitive" discipline the peer forward `From<String> for
160/// CaixaVersion` / `From<&str> for CaixaVersion` constructors carry,
161/// now extended onto the owned-heap-string reverse projection.
162///
163/// Pinned load-bearing by
164/// [`tests::caixa_version_from_into_owned_string_returns_wrapped_body`]
165/// (byte-parity pin against [`CaixaVersion::as_str`] on the same
166/// instance) and
167/// [`tests::caixa_version_from_into_owned_string_and_as_str_agree_on_every_shape`]
168/// (cross-axis partition pin against the paired borrowed
169/// [`AsRef<str>`] impl and the sibling [`fmt::Display`]-routed
170/// [`ToString::to_string`] surface, plus a round-trip witness through
171/// the paired forward [`From<String> for CaixaVersion`] constructor
172/// closing the two-way `Self → String → Self` cycle by construction).
173impl From<CaixaVersion> for String {
174 fn from(v: CaixaVersion) -> String {
175 v.0
176 }
177}
178
179/// Trait-idiomatic *borrowed-input, owned-`String` output* reverse
180/// projection on the [`CaixaVersion`] newtype primitive — the
181/// borrowed-input companion to the paired owned-input
182/// [`From<CaixaVersion> for String`] impl immediately above. Routes
183/// byte-for-byte through the substrate-primitive
184/// [`CaixaVersion::as_str`] `pub const fn` accessor (via
185/// [`str::to_owned`]) so every consumer that holds a
186/// borrowed [`&CaixaVersion`] and needs an owned [`String`] — a
187/// `[…].iter().map(String::from).collect::<Vec<_>>()` per-instance
188/// materializer over `&[CaixaVersion]` (whose iterator yields
189/// `&CaixaVersion`, not `CaixaVersion`, so the owned-input
190/// [`From<CaixaVersion> for String`] axis alone forces every call site
191/// through an explicit `.clone()` / dereference restatement), a future
192/// `HashMap::<String, _>::from_iter` that keys off a borrowed-
193/// iteration axis where cloning the wrapper would allocate one
194/// [`String`] beyond the map entry's own, a future
195/// `serde_json::Value::String(String::from(&caixa.versao))`
196/// structured-payload composer that owns the emit-path without moving
197/// out of a borrowed field — reaches the wrapped byte-string through
198/// this one dispatch on the substrate primitive.
199///
200/// Second corner on the `{Self, &Self} → String` reverse-projection
201/// family opened on the paired owned-input
202/// [`From<CaixaVersion> for String`] impl immediately above. Rust's
203/// `From` trait does not derive the `From<&Self>` sibling from a
204/// `From<Self>` impl (the blanket
205/// `impl<T, U> From<&T> for U where T: Clone, U: From<T>` does not
206/// exist in `core`), so every newtype that carries the owned-input
207/// reverse axis but not the borrowed-input axis forces every borrowed
208/// call site through a `.clone()` / `<String>::from(v.clone())` detour
209/// whose type bounds have no compile-time link back to the newtype.
210///
211/// Pinned load-bearing by
212/// [`tests::caixa_version_from_borrowed_into_owned_string_routes_through_as_str_accessor`]
213/// (byte-parity pin against [`CaixaVersion::as_str`] via a borrowed
214/// input) and
215/// [`tests::caixa_version_from_owned_and_borrowed_into_string_agree_on_every_shape`]
216/// (cross-axis partition pin against the paired owned-input
217/// [`From<CaixaVersion> for String`] impl on the same instance,
218/// closing the "owned-input move vs. borrowed-input clone" bifurcation
219/// on the same wrapped body).
220impl From<&CaixaVersion> for String {
221 fn from(v: &CaixaVersion) -> String {
222 v.as_str().to_owned()
223 }
224}
225
226/// Canonical Zig-style git-tag prefix every `feira publish` run writes
227/// and every downstream consumer of a published caixa reads. A caixa
228/// published at `:versao "0.1.0"` lands as a git tag `v0.1.0` on the
229/// source repo's `origin` remote — the [`crate::CaixaVersion`] value
230/// gates the version body, this constant gates the prefix the body
231/// composes under.
232///
233/// Two production-code consumers carry this prefix on the same git
234/// remote axis:
235///
236/// 1. [`caixa-feira`]'s `feira publish` verb (caixa-feira/src/cmd/publish.rs)
237/// — the writer. Its `--prefix` clap flag defaults to this string
238/// and the verb computes the tag as `format!("{prefix}{versao}")`
239/// before `git tag -a <tag>` + `git push origin <tag>`.
240/// 2. [`caixa-flux`]'s [`caixa-flux::cluster_bundle`] renderer
241/// (caixa-flux/src/lib.rs) — the reader. Its
242/// `ClusterBundleOpts::for_caixa` constructor defaults
243/// `git_ref: GitRefSpec::Tag(...)` to `<prefix><versao>` so the
244/// rendered `gitrepository.yaml` carries `ref: { tag: v<versao> }`
245/// pointing `FluxCD`'s `GitRepository` reconciler at the exact tag
246/// the publisher just wrote.
247///
248/// Until this lift landed both consumers carried the bare `"v"` byte
249/// inline — `caixa-feira/src/cmd/publish.rs:22`'s clap
250/// `default_value = "v"` and `caixa-flux/src/lib.rs:335`'s
251/// `format!("v{}", caixa.versao)` literal. A future Zig-style-tag
252/// convention rebrand (the substrate moving to plain `<versao>` tags
253/// once the GitHub releases UI normalizes around the bare form, to
254/// `release/<versao>` once a sibling forge convention adopts the
255/// `<type>/<value>` slash-namespaced shape, or to a per-edition
256/// override the operator pins through a future `:placement
257/// :tag-prefix` slot) without a coordinated edit on both sides would
258/// silently emit a `feira publish`-side tag at one shape (e.g.
259/// `release/0.1.0`) and a `cluster_bundle`-side `ref: { tag: v0.1.0 }`
260/// pointing at the prior shape — Flux's `GitRepository` reconciler
261/// would loop forever looking for an upstream `v0.1.0` ref the publish
262/// remote no longer carries, the dependent `HelmRelease`'s `chart:
263/// sourceRef` would never resolve, every per-Servico apply would
264/// silently come up with the prior reconciled state, and the failure
265/// would surface at `kubectl describe gitrepository` time (the
266/// `Status: Stalled` / `Reason: Failed` arm) far from the rebrand
267/// commit's source.
268///
269/// Lifting the literal to one `&'static str` constant closes the drift
270/// footgun structurally — both consumers read from the same memory,
271/// so any future rebrand reaches both sites by construction and a CI
272/// build that re-introduces a sibling inline `"v"` literal trips the
273/// peer pinning tests
274/// ([`caixa-feira`]'s `publish_prefix_default_pins_lifted_caixa_core_constant`,
275/// [`caixa-flux`]'s `cluster_bundle_default_git_tag_uses_lifted_caixa_core_prefix`)
276/// at the build-time fail-before-deploy posture every prior
277/// load-bearing-string lift on this surface
278/// ([`crate::DEFAULT_NAMESPACE`] a085b26,
279/// [`crate::DEFAULT_LIBRARY_NAME`] 41438dc,
280/// [`crate::DEFAULT_SERVICO_PORT`] 1e22add) establishes.
281///
282/// Authoring-side `:versao` gates already refuse the `"v"`-prefixed
283/// publish tag shape leaking back into a version body — every typed
284/// `:versao` surface (top-level `:versao`, `:upgrade-from :from`,
285/// `:deps :versao`, `:deps-dev :versao`, `:membros :versao`,
286/// `:children :versao`) routes through `semver::Version::parse` /
287/// [`parse_requirement`], both of which reject the `v`-prefix as
288/// invalid `SemVer`. The split — bare `SemVer` at the `:versao` slot,
289/// `v<versao>` at the published git-tag axis — is the convention this
290/// constant pins.
291pub const DEFAULT_PUBLISH_TAG_PREFIX: &str = "v";
292
293/// Canonical git remote name every `feira` writer-side verb pushes to —
294/// the destination handle the operator-out-of-the-loop publish + deploy
295/// chain (`feira publish`, `feira deploy --apply`, `feira app deploy
296/// --apply`) names when it invokes `git push <remote> <ref>` against
297/// the local clone of the source / k8s GitOps repo.
298///
299/// Three production-code consumers carry this remote name on the same
300/// `git push` axis:
301///
302/// 1. [`caixa-feira`]'s `feira publish` verb (caixa-feira/src/cmd/publish.rs)
303/// — the writer-side publish path. Its `--remote` clap flag defaults
304/// to this string and the verb runs `git push <remote> <tag>` to push
305/// the freshly written `v<versao>` tag upstream.
306/// 2. [`caixa-feira`]'s `feira deploy --apply` verb
307/// (caixa-feira/src/cmd/deploy.rs) — the writer-side Servico cluster-
308/// deploy path. Its `push_origin` helper runs `git push origin HEAD`
309/// against the k8s GitOps repo's working tree after upserting the
310/// Servico's entry into the cluster's lareira-fleet-programs
311/// HelmRelease values.
312/// 3. [`caixa-feira`]'s `feira app deploy --apply` verb
313/// (caixa-feira/src/cmd/app.rs) — the writer-side Aplicacao
314/// cluster-deploy path. Its `push_origin` helper runs the same
315/// `git push origin HEAD` against the k8s GitOps repo after writing
316/// the rendered multi-doc YAML (programs.yaml entries + Cilium
317/// NetworkPolicies + Gateway/HTTPRoute) to the cluster's tree.
318///
319/// Until this lift landed all three consumers carried the bare
320/// `"origin"` byte inline — `publish.rs`'s clap `default_value = "origin"`,
321/// `deploy.rs`'s `git(repo, ["push", "origin", "HEAD"])`, and
322/// `app.rs`'s `git(repo, ["push", "origin", "HEAD"])`. A future
323/// remote-naming-convention rebrand on any one side (the substrate
324/// moving to `upstream` for forge-mirror clusters, to a per-tenant
325/// remote naming convention once the operator-flux pipeline grows the
326/// `:placement :remote` slot, or to the canonical multi-remote
327/// `release` + `mirror` split every Erlang/OTP `release_handler` /
328/// `relup` shop converges on once their git surface grows past one
329/// upstream) without a coordinated edit on the other two would have
330/// silently emitted a `git push` against a remote that doesn't exist
331/// on the operator's clone (`fatal: '<remote>' does not appear to be
332/// a git repository`) on one writer verb while the other two still
333/// pushed to the old remote — operator-observed symptom: the publish
334/// landed but the deploy didn't, or vice-versa, with the failure
335/// surfacing as a partial-state rollout far from the rebrand commit's
336/// source.
337///
338/// Lifting the literal to one `&'static str` constant closes the drift
339/// footgun structurally — all three consumers read from the same
340/// memory, so any future remote-naming rebrand reaches every writer
341/// verb by construction and a CI build that re-introduces a sibling
342/// inline `"origin"` literal trips the peer pinning tests
343/// ([`caixa-feira`]'s `publish_remote_default_pins_lifted_caixa_core_constant`
344/// on the clap-default axis, the sibling structural pins on the two
345/// `push_origin` helpers) at the build-time fail-before-deploy
346/// posture every prior load-bearing-string lift on this surface
347/// ([`crate::DEFAULT_NAMESPACE`] a085b26, [`crate::DEFAULT_LIBRARY_NAME`]
348/// 41438dc, [`crate::DEFAULT_SERVICO_PORT`] 1e22add,
349/// [`crate::DEFAULT_PUBLISH_TAG_PREFIX`] 0a6a602,
350/// [`crate::DEFAULT_FLUX_SYSTEM_NAMESPACE`] 7197d38) establishes.
351///
352/// Pairs with [`DEFAULT_PUBLISH_TAG_PREFIX`] on the same git remote
353/// axis — `feira publish` runs `git push <DEFAULT_GIT_REMOTE>
354/// <DEFAULT_PUBLISH_TAG_PREFIX><versao>` to push the typed `:versao`
355/// body composed under the canonical prefix to the canonical remote.
356/// Both halves of the publish-side convention now live in one place.
357pub const DEFAULT_GIT_REMOTE: &str = "origin";
358
359/// Canonical GitHub org name the pleme-io substrate defaults every un-
360/// pinned caixa's source repo to — the org handle the two substrate-side
361/// "no `:repositorio` / no `:fonte` declared, fall back to the canonical
362/// org" paths compose their `github:<org>/<nome>` shorthand + full
363/// `https://github.com/<org>/<nome>` URL under.
364///
365/// Two production-code consumers carry this org name on the same
366/// canonical-substrate-default-git-org axis:
367///
368/// 1. [`caixa-feira`]'s `feira lock` verb's `resolve_stub` (caixa-feira/src/cmd/lock.rs)
369/// — the resolver-side default. When a declared dep has no
370/// `:fonte` block the stub resolver composes
371/// `caixa_core::DepSource::default_github(<org>, &dep.nome)` to fill
372/// the shorthand `github:<org>/<nome>` fallback the phase 1.B
373/// `feira resolve` walker will resolve against upstream.
374/// 2. [`caixa-flux`]'s [`caixa-flux::cluster_bundle`] renderer
375/// (caixa-flux/src/lib.rs) — the renderer-side default. Its
376/// `ClusterBundleOpts::for_caixa` constructor defaults
377/// `git_url` to `format!("https://github.com/{org}/{}", caixa.nome)`
378/// when the caixa carries no `:repositorio`, so the rendered
379/// `gitrepository.yaml` points `FluxCD`'s `GitRepository`
380/// reconciler at the substrate's canonical git host for un-pinned
381/// caixas.
382///
383/// Until this lift landed both consumers carried the bare `"pleme-io"`
384/// byte inline — `caixa-feira/src/cmd/lock.rs:61`'s
385/// `default_github("pleme-io", …)` call and `caixa-flux/src/lib.rs`'s
386/// `format!("https://github.com/pleme-io/{}", …)` literal. A future
387/// substrate-side git-org migration (the pleme-io org renaming to a
388/// short form, forking to a per-tenant `<org>-<tenant>` shape once the
389/// operator-flux pipeline grows a `:placement :org` slot, or moving to
390/// a self-hosted forge under a wholly-owned org name once the
391/// substrate's forge-gen roadmap graduates past GitHub) without a
392/// coordinated edit on both sides would silently emit a `feira lock`-
393/// side `github:<old-org>/<nome>` fallback shorthand while the
394/// `cluster_bundle`-side `gitrepository.yaml` pointed at the new org's
395/// `<nome>` — the phase 1.B `feira resolve` walker would probe the
396/// prior org's git host for a repo that migrated with the org, or vice-
397/// versa: Flux's `GitRepository` reconciler would loop forever looking
398/// for an upstream repo the old org handle no longer maps to, the
399/// dependent `HelmRelease`'s `chart: sourceRef` would never resolve,
400/// every per-Servico apply would silently come up with the prior
401/// reconciled state, and the failure would surface at `kubectl describe
402/// gitrepository` time (the `Status: Stalled` / `Reason: Failed` arm)
403/// far from the org-migration commit's source.
404///
405/// Lifting the literal to one `&'static str` constant closes the drift
406/// footgun structurally — both consumers read from the same memory, so
407/// any future org migration reaches both sites by construction and a CI
408/// build that re-introduces a sibling inline `"pleme-io"` literal trips
409/// the peer pinning tests at the build-time fail-before-deploy posture
410/// every prior load-bearing-string lift on this surface
411/// ([`crate::DEFAULT_NAMESPACE`] a085b26,
412/// [`crate::DEFAULT_LIBRARY_NAME`] 41438dc,
413/// [`crate::DEFAULT_SERVICO_PORT`] 1e22add,
414/// [`DEFAULT_PUBLISH_TAG_PREFIX`] 0a6a602,
415/// [`DEFAULT_GIT_REMOTE`],
416/// [`crate::DEFAULT_FLUX_SYSTEM_NAMESPACE`] 7197d38) establishes.
417///
418/// Distinct from the [`crate::PLEME_LABEL_PREFIX`] canonical pleme-io
419/// label-namespace prefix (`"pleme.pleme.io"`, the K8s label-namespace
420/// axis every substrate-emitted cluster object's `LABEL_APLICACAO` /
421/// `LABEL_PROGRAM` / `LABEL_CONTRATO` axis shares) — these constants
422/// sit on separate schema-contract surfaces (the git-host org handle
423/// vs. the K8s label-namespace prefix) governed by independent rebrand
424/// cycles, so a git-org rename must not couple the K8s label-namespace
425/// axis to the git-host axis (or vice-versa). Splitting the two lets
426/// each schema's future rebrand land independently at its canonical
427/// const definition without silently coupling the surfaces — same
428/// "byte-distinct, semantically distinct" discipline the
429/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LABEL_APLICACAO`] /
430/// [`crate::LABEL_PROGRAM`] / [`crate::LABEL_CONTRATO`] set establishes
431/// on the peer per-K8s-label-namespace canonical-string surface.
432pub const DEFAULT_PLEME_GIT_ORG: &str = "pleme-io";
433
434/// Parse a dep's `:versao` string as a [`semver::VersionReq`].
435///
436/// Treats the literal `"*"` as "any version" (semver's wildcard).
437pub fn parse_requirement(s: &str) -> Result<semver::VersionReq, VersionError> {
438 if s == "*" {
439 return Ok(semver::VersionReq::STAR);
440 }
441 semver::VersionReq::parse(s).map_err(|e| VersionError::requirement(s, e.to_string()))
442}
443
444#[derive(Debug, Error, PartialEq, Eq)]
445pub enum VersionError {
446 #[error("invalid version '{0}': {1}")]
447 Semver(String, String),
448 #[error("invalid version requirement '{0}': {1}")]
449 Requirement(String, String),
450}
451
452// Fold the sole `VersionError::Semver(<into-String-expr>, <into-String-expr>)`
453// wire-up site on [`CaixaVersion::parse`]'s [`semver::Version::parse`]
454// `map_err` arm onto one substrate primitive — the paired
455// `(String, String)` two-slot tuple-newtype [`VersionError::Semver`] on
456// the [`CaixaVersion`] parser surface, the first of the two variants on
457// the [`VersionError`] envelope's paired `(String, String)` tuple-newtype
458// codec-magnitude family (its peer is [`VersionError::Requirement`] on
459// the sibling [`parse_requirement`] surface). Same discipline the peer
460// per-variant lifts on [`AplicacaoError`] / [`SupervisorError`] /
461// [`UpgradeError`] / [`LayoutError`] / [`DepError`] / [`ManifestError`]
462// / [`LimitsError`] / [`BehaviorError`] / [`DialetoError`] have
463// converged through the "one substrate primitive per emit-site variant"
464// ratchet: the sole wire-up site opens the identical
465// `VersionError::Semver(<into-String-expr>, <into-String-expr>)` block
466// against the parser-scoped `String` binding (`self.0.clone()`) and the
467// derived `String` binding (`e.to_string()`) on the failing
468// [`semver::Version::parse`] arm, so the fold routes the site through
469// one dispatch on a uniform pair of `impl Into<String>` params,
470// byte-equal to the pre-lift tuple-newtype construction on the same
471// arguments. The `impl Into<String>` bound covers both the pre-lift
472// `String` bindings and any future `&str` binding a downstream consumer
473// might carry without forcing the caller to spell the `.into()`
474// conversion at the wire-up site — the same shape the peer
475// [`LimitsError::empty_byte_size`] / [`LimitsError::empty_duration`] /
476// [`DialetoError::leitura`] folds carry on the single-slot `(String)`
477// tuple-newtype cousins of the same tuple-newtype error-envelope family
478// on the sibling parser surfaces. `#[must_use]` fires a compile warning
479// at any wire-up that mistakenly discards the constructed error. The
480// added [`PartialEq`] / [`Eq`] derives on the envelope (peer with the
481// sibling [`LimitsError`] / [`DialetoError`] / [`DepError`] envelopes
482// on the same axis) let the fail-before-pass-after byte-equality pins
483// below trip a de-lift regression at caixa-core test time under
484// `PartialEq` rather than at a downstream diagnostic shape drift.
485//
486// Every future consumer that wants to construct this variant outside
487// [`CaixaVersion::parse`] (a deferred `feira lint --canonical-versao`
488// per-caixa admission verb probing each authored top-level `:versao`
489// value against the same [`semver::Version::parse`] gate, an M4 typed
490// `mesh.pleme.io/v1alpha1/Servico` CR materializer's per-manifest
491// admission validator re-checking one edited `:versao` slot against
492// the [`CaixaVersion::parse`] semver floor, a per-`caixa.lisp` value-
493// shape pre-emitter probing each declared `:versao` magnitude ahead of
494// the operator's admit-cycle) now reaches the variant through one call
495// rather than re-inlining the two-slot tuple-newtype block in lockstep.
496impl VersionError {
497 /// Construct a [`VersionError::Semver`] carrying the offending
498 /// authoring string `value` and the underlying [`semver::Version::parse`]
499 /// `reason` verbatim in the variant's two-slot tuple-newtype payload.
500 /// Folds the uniform `Self::Semver(value.into(), reason.into())`
501 /// tuple-newtype construction onto one substrate primitive so every
502 /// wire-up on the variant reads through one dispatch rather than the
503 /// pre-lift open-coded
504 /// `VersionError::Semver(<into-String-expr>, <into-String-expr>)`
505 /// block. The paired `impl Into<String>` bounds cover the pre-lift
506 /// `String` wire-up shape on [`CaixaVersion::parse`]
507 /// (`self.0.clone()` on the parser-scoped `String` field, `e.to_string()`
508 /// on the derived `String` from the failing
509 /// [`semver::Version::parse`] arm) without forcing the caller to
510 /// spell the conversion at the wire-up site. Peer to the sibling
511 /// [`VersionError::Requirement`] variant on the [`parse_requirement`]
512 /// surface — the same `(String, String)` two-slot tuple-newtype axis
513 /// of the paired [`VersionError`] envelope, but on the `SemVer`
514 /// version-body parser surface rather than the version-requirement
515 /// parser surface.
516 #[must_use]
517 pub fn semver(value: impl Into<String>, reason: impl Into<String>) -> Self {
518 Self::Semver(value.into(), reason.into())
519 }
520
521 /// Construct a [`VersionError::Requirement`] carrying the offending
522 /// authoring string `value` and the underlying
523 /// [`semver::VersionReq::parse`] `reason` verbatim in the variant's
524 /// two-slot tuple-newtype payload. Folds the uniform
525 /// `Self::Requirement(value.into(), reason.into())` tuple-newtype
526 /// construction onto one substrate primitive so every wire-up on the
527 /// variant reads through one dispatch rather than the pre-lift open-
528 /// coded `VersionError::Requirement(<into-String-expr>,
529 /// <into-String-expr>)` block. Peer to the sibling
530 /// [`VersionError::semver`] ctor on the [`CaixaVersion::parse`]
531 /// surface — the same `(String, String)` two-slot tuple-newtype axis
532 /// of the paired [`VersionError`] envelope, but on the version-
533 /// requirement parser surface rather than the semver-version-body
534 /// parser surface. Closes the last un-lifted variant on the
535 /// [`VersionError`] envelope: every arm now reaches its emit site
536 /// through one substrate-primitive dispatch, matching the "one
537 /// substrate primitive per emit-site variant" ratchet the peer per-
538 /// variant lifts on [`crate::AplicacaoError`] /
539 /// [`crate::SupervisorError`] / [`crate::UpgradeError`] /
540 /// [`crate::LayoutError`] / [`crate::DepError`] /
541 /// [`crate::ManifestError`] / [`crate::LimitsError`] /
542 /// [`crate::BehaviorError`] / [`crate::DialetoError`] have converged
543 /// onto.
544 #[must_use]
545 pub fn requirement(value: impl Into<String>, reason: impl Into<String>) -> Self {
546 Self::Requirement(value.into(), reason.into())
547 }
548}
549
550#[cfg(test)]
551mod tests {
552 use super::*;
553
554 #[test]
555 fn version_round_trip() {
556 let v: CaixaVersion = "1.2.3".into();
557 assert_eq!(v.as_str(), "1.2.3");
558 assert_eq!(v.parse().unwrap().to_string(), "1.2.3");
559 }
560
561 #[test]
562 fn caixa_version_as_str_accessor_is_const_fn() {
563 // Fail-before-pass-after pin on [`CaixaVersion::as_str`]'s
564 // `const`-eval-surface posture. The accessor projects the typed
565 // newtype's inner [`String`] through the `pub const fn`
566 // [`String::as_str`] (const-stable since Rust 1.87, well within
567 // the workspace MSRV) — any future accidental downgrade to
568 // non-`const` fails `as_str_via_const_fn` at caixa-core build
569 // time with E0015 (`cannot call non-const method`), strictly
570 // stronger than a runtime `assert!`. Sibling of the peer
571 // per-M2/M3/universal-axis `String → &str` scalar-accessor
572 // family pins on the sibling `const`-eval-surface passes
573 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
574 // top-level manifest, [`crate::aplicacao::Membro::nome`] /
575 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
576 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
577 // [`crate::aplicacao::Entrada::destination`] at the M3 ingress
578 // axis, [`crate::supervisor::ChildSpec::nome`] /
579 // [`crate::supervisor::ChildSpec::versao_requirement`] at the
580 // M2 supervisor-tree axis,
581 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the M2
582 // upgrade axis, [`crate::dep::Dep::nome`] /
583 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
584 // axis, and the peer per-`:contratos` [`crate::aplicacao::WitContract::source`] /
585 // [`crate::aplicacao::WitContract::destination`] /
586 // [`crate::aplicacao::WitContract::world_ref`] trio the
587 // sibling pin at 279823b already anchors).
588 const fn as_str_via_const_fn(v: &CaixaVersion) -> &str {
589 v.as_str()
590 }
591 for versao in ["0.1.0", "1.2.3-alpha.1", "0.0.0", ""] {
592 let v: CaixaVersion = versao.into();
593 assert_eq!(as_str_via_const_fn(&v), v.as_str());
594 assert_eq!(v.as_str(), versao);
595 }
596 }
597
598 #[test]
599 fn star_is_any() {
600 let r = parse_requirement("*").unwrap();
601 assert!(r.matches(&"0.1.0".parse().unwrap()));
602 assert!(r.matches(&"99.0.0".parse().unwrap()));
603 }
604
605 #[test]
606 fn caret_matches_minor_range() {
607 let r = parse_requirement("^0.1").unwrap();
608 assert!(r.matches(&"0.1.0".parse().unwrap()));
609 assert!(r.matches(&"0.1.99".parse().unwrap()));
610 assert!(!r.matches(&"0.2.0".parse().unwrap()));
611 }
612
613 #[test]
614 fn invalid_version_errors() {
615 let v: CaixaVersion = "not-a-version".into();
616 assert!(v.parse().is_err());
617 }
618
619 #[test]
620 fn semver_ctor_matches_tuple_literal_wrap_on_str_binding() {
621 // Fail-before-pass-after byte-equality pin: the lifted
622 // [`VersionError::semver`] inherent ctor projects a `&str`
623 // binding pair through the paired `impl Into<String>` bounds
624 // byte-equal to the pre-lift open-coded
625 // `VersionError::Semver(<into-String-expr>, <into-String-expr>)`
626 // tuple-literal on the same fixture, so any future silent
627 // regression that swaps `.into()` for a divergent conversion
628 // (a stray `String::from(str::trim(v))` normalization, a
629 // parity-lossy `.to_lowercase()` fold, a `Cow<'_, str>` detour)
630 // trips at caixa-core test time under `PartialEq` rather than
631 // at a downstream diagnostic-shape drift on a consumer surface.
632 // Same shape the peer
633 // [`crate::LimitsError::empty_byte_size_ctor_matches_tuple_literal_wrap_on_str_binding`]
634 // / [`crate::DialetoError::leitura_ctor_matches_tuple_literal_wrap_on_str_binding`]
635 // pins carry on the sibling single-slot `(String)` tuple-newtype
636 // cousins of the same tuple-newtype error-envelope family on the
637 // sibling parser surfaces.
638 let value: &str = "not-a-version";
639 let reason: &str = "unexpected character 'n' while parsing major version number";
640 assert_eq!(
641 VersionError::semver(value, reason),
642 VersionError::Semver(value.to_string(), reason.to_string()),
643 "generated semver ctor over `&str` bindings must match \
644 the pre-lift tuple-literal wrap on the same fixture",
645 );
646 }
647
648 #[test]
649 fn semver_ctor_matches_tuple_literal_wrap_on_string_binding() {
650 // Fail-before-pass-after byte-equality pin on the paired owned-
651 // `String` shape — the actual wire-up shape on
652 // [`CaixaVersion::parse`] (`self.0.clone()` +
653 // `e.to_string()`). Peer to the `&str` variant above; refuses
654 // any future de-lift that inlines a divergent construction on
655 // the owned-`String` path (a stray `.trim().to_string()`
656 // normalization on either slot, a swap that routes the ctor
657 // through the sibling [`VersionError::Requirement`] variant on
658 // the paired parser surface).
659 let value: String = String::from("1.2");
660 let reason: String =
661 String::from("unexpected end of input while parsing minor version number");
662 assert_eq!(
663 VersionError::semver(value.clone(), reason.clone()),
664 VersionError::Semver(value, reason),
665 "generated semver ctor over owned-`String` bindings must \
666 match the pre-lift tuple-literal wrap on the same fixture",
667 );
668 }
669
670 #[test]
671 fn parse_semver_error_routes_through_semver_ctor() {
672 // Fail-before-pass-after routes-through pin: refuses any future
673 // de-lift of [`CaixaVersion::parse`]'s
674 // [`semver::Version::parse`] `map_err` arm off the substrate
675 // primitive. Sweeps three malformed authoring shapes (a bare
676 // non-numeric, a partial `major.minor` shape, a stray leading
677 // `v`-prefix that the [`DEFAULT_PUBLISH_TAG_PREFIX`] git-tag
678 // convention rejects at the version-body slot) through the
679 // parser and asserts the emitted [`VersionError`] equals the
680 // ctor-built error verbatim under `PartialEq`, so any future
681 // swap of the wire-up (an inline `Self::Semver(...)`
682 // re-inlining, a routing detour through the sibling
683 // [`VersionError::Requirement`] variant on the paired parser
684 // surface, a swap of the ordering on the paired arguments)
685 // trips at caixa-core test time rather than at a downstream
686 // diagnostic drift on a `feira lint` / operator admission
687 // callsite.
688 for bad in ["not-a-version", "1.2", "v0.1.0"] {
689 let v: CaixaVersion = bad.into();
690 let err = v
691 .parse()
692 .expect_err("malformed versao fixture must fail semver parsing");
693 let semver_reason = match semver::Version::parse(bad) {
694 Err(e) => e.to_string(),
695 Ok(_) => unreachable!(
696 "fixture `{bad}` is documented as a `SemVer` \
697 rejection but parsed cleanly — the pin's oracle \
698 drifted from `semver`'s current shape",
699 ),
700 };
701 assert_eq!(
702 err,
703 VersionError::semver(bad, semver_reason),
704 "CaixaVersion::parse must route its semver `map_err` \
705 arm through the lifted VersionError::semver ctor on \
706 the same offending value and semver reason",
707 );
708 }
709 }
710
711 #[test]
712 fn default_git_remote_pins_canonical_origin_byte() {
713 // Bridge-arm pin: [`DEFAULT_GIT_REMOTE`] resolves to the
714 // canonical `"origin"` byte today, the same remote-handle every
715 // `git clone <url>` invocation populates by default and every
716 // peer `feira` writer-side verb (`feira publish`, `feira deploy
717 // --apply`, `feira app deploy --apply`) names when it invokes
718 // `git push <remote> <ref>` against the local clone. Pin the
719 // literal here (peer with the
720 // [`DEFAULT_PUBLISH_TAG_PREFIX`] / [`crate::DEFAULT_SERVICO_PORT`]
721 // / [`crate::DEFAULT_NAMESPACE`] / [`crate::DEFAULT_LIBRARY_NAME`]
722 // / [`crate::DEFAULT_FLUX_SYSTEM_NAMESPACE`] canonical-literal
723 // pins on the sibling lifted-constant surfaces) so a future
724 // remote-naming rebrand surfaces here as a coordinated edit-
725 // point: the sibling [`caixa-feira`]
726 // `publish_remote_default_pins_lifted_caixa_core_constant`
727 // pinning test already pins the equality at the clap-default
728 // axis; this pin closes the second coordinate of the
729 // triangle by anchoring the lifted constant's current byte
730 // to the canonical git-default-remote convention's documented
731 // shape.
732 assert_eq!(DEFAULT_GIT_REMOTE, "origin");
733 }
734
735 #[test]
736 fn default_pleme_git_org_pins_canonical_pleme_io_byte() {
737 // Bridge-arm pin: [`DEFAULT_PLEME_GIT_ORG`] resolves to the
738 // canonical `"pleme-io"` GitHub-org-handle today, the same org
739 // name every peer substrate-side default-git-source consumer
740 // ([`caixa-feira`]'s `feira lock` `resolve_stub` for the
741 // per-dep `:fonte`-elided `github:<org>/<nome>` fallback,
742 // [`caixa-flux`]'s `ClusterBundleOpts::for_caixa` constructor
743 // for the per-caixa `:repositorio`-elided
744 // `https://github.com/<org>/<nome>` fallback) fills into its
745 // per-consumer render/resolve compose site. Pin the literal
746 // here (peer with the [`DEFAULT_PUBLISH_TAG_PREFIX`] /
747 // [`DEFAULT_GIT_REMOTE`] canonical-literal pins on the sibling
748 // lifted-constant surfaces) so a future substrate-side git-org
749 // migration surfaces here as a coordinated edit-point: both
750 // sibling consumer sites already thread through the same
751 // `&'static str`, this pin anchors the lifted constant's
752 // current byte to the canonical substrate-git-org convention's
753 // documented shape.
754 assert_eq!(DEFAULT_PLEME_GIT_ORG, "pleme-io");
755 }
756
757 #[test]
758 fn requirement_ctor_matches_tuple_literal_wrap_on_str_binding() {
759 // Fail-before-pass-after byte-equality pin: the lifted
760 // [`VersionError::requirement`] inherent ctor projects a `&str`
761 // binding pair through the paired `impl Into<String>` bounds
762 // byte-equal to the pre-lift open-coded
763 // `VersionError::Requirement(<into-String-expr>, <into-String-expr>)`
764 // tuple-literal on the same fixture. Same shape the peer
765 // [`VersionError::semver_ctor_matches_tuple_literal_wrap_on_str_binding`]
766 // pin carries on the sibling [`VersionError::Semver`] variant of
767 // the same `(String, String)` two-slot tuple-newtype envelope.
768 let value: &str = "not-a-req";
769 let reason: &str = "unexpected character 'n' while parsing major version number";
770 assert_eq!(
771 VersionError::requirement(value, reason),
772 VersionError::Requirement(value.to_string(), reason.to_string()),
773 "generated requirement ctor over `&str` bindings must match \
774 the pre-lift tuple-literal wrap on the same fixture",
775 );
776 }
777
778 #[test]
779 fn requirement_ctor_matches_tuple_literal_wrap_on_string_binding() {
780 // Fail-before-pass-after byte-equality pin on the paired owned-
781 // `String` shape. Peer to the `&str` variant above; refuses any
782 // future de-lift that inlines a divergent construction on the
783 // owned-`String` path (a stray `.trim().to_string()` normalization
784 // on either slot, a swap that routes the ctor through the sibling
785 // [`VersionError::Semver`] variant on the paired parser surface,
786 // an argument-ordering swap on the paired slots).
787 let value: String = String::from("^bogus");
788 let reason: String = String::from("unexpected character while parsing requirement");
789 assert_eq!(
790 VersionError::requirement(value.clone(), reason.clone()),
791 VersionError::Requirement(value, reason),
792 "generated requirement ctor over owned-`String` bindings must \
793 match the pre-lift tuple-literal wrap on the same fixture",
794 );
795 }
796
797 #[test]
798 fn parse_requirement_error_routes_through_requirement_ctor() {
799 // Fail-before-pass-after routes-through pin: refuses any future
800 // de-lift of [`parse_requirement`]'s
801 // [`semver::VersionReq::parse`] `map_err` arm off the substrate
802 // primitive. Sweeps three malformed authoring shapes (a bare
803 // non-numeric, a stray operator with no version body, a
804 // caret-prefixed non-numeric that the [`semver::VersionReq`]
805 // grammar rejects at the operator-body slot) through the parser
806 // and asserts the emitted [`VersionError`] equals the ctor-built
807 // error verbatim under `PartialEq`, so any future swap of the
808 // wire-up (an inline `Self::Requirement(...)` re-inlining, a
809 // routing detour through the sibling [`VersionError::Semver`]
810 // variant on the paired parser surface, an argument-ordering
811 // swap on the paired slots) trips at caixa-core test time rather
812 // than at a downstream diagnostic drift on a `feira lock` /
813 // resolver admission callsite. The `"*"` wildcard short-circuit
814 // is deliberately excluded from the sweep — it returns
815 // [`semver::VersionReq::STAR`] before reaching the parser arm.
816 for bad in ["not-a-req", "^", "^bogus"] {
817 let err = parse_requirement(bad)
818 .expect_err("malformed requirement fixture must fail parsing");
819 let semver_reason = match semver::VersionReq::parse(bad) {
820 Err(e) => e.to_string(),
821 Ok(_) => unreachable!(
822 "fixture `{bad}` is documented as a `VersionReq` \
823 rejection but parsed cleanly — the pin's oracle \
824 drifted from `semver`'s current shape",
825 ),
826 };
827 assert_eq!(
828 err,
829 VersionError::requirement(bad, semver_reason),
830 "parse_requirement must route its `map_err` arm through \
831 the lifted VersionError::requirement ctor on the same \
832 offending value and semver reason",
833 );
834 }
835 }
836
837 #[test]
838 fn default_publish_tag_prefix_pins_canonical_v_byte() {
839 // Bridge-arm pin: [`DEFAULT_PUBLISH_TAG_PREFIX`] resolves to the
840 // canonical Zig-style `"v"` byte today, the same prefix every
841 // peer doc-comment on the typed `:versao` surfaces (the
842 // top-level `:versao` `validate_versao` cascade at
843 // caixa-core/src/manifest.rs:646, the four sibling per-axis
844 // `:versao` requirement gates that name the publish-side
845 // `v<versao>` tag inline in their bodies) cites as the
846 // canonical convention. Pin the literal here (peer with the
847 // [`crate::DEFAULT_SERVICO_PORT`] / [`crate::DEFAULT_NAMESPACE`]
848 // / [`crate::DEFAULT_LIBRARY_NAME`] canonical-literal pins on
849 // the sibling lifted-constant surfaces) so a future rebrand of
850 // the constant surfaces here as a coordinated edit-point: both
851 // sibling pinning tests on the two consumer crates
852 // ([`caixa-feira`] `publish_prefix_default_pins_lifted_caixa_core_constant`,
853 // [`caixa-flux`] `cluster_bundle_default_git_tag_uses_lifted_caixa_core_prefix`)
854 // already pin the equality at the consumer-default axis; this
855 // pin closes the third coordinate of the triangle by anchoring
856 // the lifted constant's current byte to the canonical Zig-style
857 // convention's documented shape.
858 assert_eq!(DEFAULT_PUBLISH_TAG_PREFIX, "v");
859 }
860
861 #[test]
862 fn caixa_version_as_ref_str_routes_through_as_str_accessor() {
863 // Fail-before-pass-after byte-parity pin on the lifted
864 // `impl AsRef<str> for CaixaVersion` — asserts the standard-
865 // library trait impl and the substrate-primitive
866 // [`CaixaVersion::as_str`] `pub const fn` accessor resolve to
867 // the same `&str` per instance, so any future silent detour
868 // that routes the impl through a divergent projection (a
869 // `Cow<'_, str>` intermediate, a stray `.to_lowercase()`
870 // normalization, a swap onto a per-arm inline `&self.0.as_str()`
871 // re-inlining, a swap onto a divergent [`String::trim`]
872 // fold) trips at caixa-core test time under `PartialEq`
873 // rather than at a downstream `impl AsRef<str>`-bound
874 // consumer's silent split. Sweeps four authoring shapes (a
875 // canonical release version, a pre-release build-metadata
876 // version, the zero-version canonical unset baseline, and
877 // the empty-string byte the caller-side default-construct
878 // path composes) so every non-degenerate arm of the wrapped
879 // `String` storage is covered. Peer of the sibling
880 // [`caixa_version_as_str_accessor_is_const_fn`] const-eval
881 // pin on the same [`CaixaVersion::as_str`] primitive — the
882 // two pins together cover the const-eval axis (the pin above)
883 // and the trait-projection axis (this pin) of the same
884 // substrate-primitive scalar accessor.
885 for versao in ["0.1.0", "1.2.3-alpha.1", "0.0.0", ""] {
886 let v: CaixaVersion = versao.into();
887 assert_eq!(
888 <CaixaVersion as AsRef<str>>::as_ref(&v),
889 v.as_str(),
890 "AsRef<str> impl must byte-equal CaixaVersion::as_str \
891 on the same instance — divergence signals a silent \
892 detour off the substrate-primitive accessor",
893 );
894 assert_eq!(
895 <CaixaVersion as AsRef<str>>::as_ref(&v),
896 versao,
897 "AsRef<str> impl must byte-equal the pre-lift wrapped \
898 String storage on round-trip through the From<&str> \
899 constructor — divergence signals a normalization \
900 detour on either the constructor or the accessor",
901 );
902 }
903 }
904
905 #[test]
906 fn caixa_version_as_ref_str_routes_through_display_via_shared_accessor() {
907 // Fail-before-pass-after byte-parity pin on the three-path
908 // convergence discipline the substrate primitive now carries
909 // on the `&str`-projection axis: `<CaixaVersion as
910 // AsRef<str>>::as_ref(&v)` (the newly lifted impl),
911 // `format!("{v}")` (the pre-existing [`fmt::Display`] impl),
912 // and `v.as_str()` (the substrate-primitive `pub const fn`
913 // accessor both trait impls delegate through) must resolve to
914 // the same byte-string on every instance. Refuses any future
915 // divergence between the two trait impls (a stray
916 // [`fmt::Display::fmt`] rewrite that inlines
917 // `f.write_str(&self.0)` on the wrapped `String` directly,
918 // bypassing the shared accessor; a hypothetical `AsRef<str>`
919 // rewrite that inlines the same `&self.0` field-access) that
920 // would silently split the two projection paths of the same
921 // typed newtype. Mirrors the sibling three-path-convergence
922 // discipline the peer [`RestartStrategy`] typed enum carries
923 // on its `Display` / `as_str` / `Serialize` triple (aplicacao.rs
924 // pin `restart_strategy_display_matches_serialized_wire_byte_string`).
925 for versao in ["0.1.0", "1.2.3-alpha.1", ""] {
926 let v: CaixaVersion = versao.into();
927 let via_as_ref: &str = <CaixaVersion as AsRef<str>>::as_ref(&v);
928 let via_display: String = format!("{v}");
929 let via_accessor: &str = v.as_str();
930 assert_eq!(via_as_ref, via_accessor);
931 assert_eq!(via_display, via_accessor);
932 assert_eq!(via_as_ref, via_display.as_str());
933 }
934 }
935
936 #[test]
937 fn caixa_version_from_into_owned_string_returns_wrapped_body() {
938 // Fail-before-pass-after byte-parity pin on the lifted
939 // `impl From<CaixaVersion> for String` — asserts the owned-input
940 // reverse-projection routes the wrapper's own heap allocation
941 // through verbatim (no re-copy, no normalization detour) so
942 // `String::from(v)` returns the same bytes `v.as_str()`
943 // borrows. Refuses any future silent detour that would swap
944 // the move on `v.0` for an allocating `.as_str().to_owned()` /
945 // `.to_string()` cascade (the pre-lift compose shape), a stray
946 // `.trim().to_owned()` normalization, or a routing through the
947 // sibling [`fmt::Display`] emitter that would introduce a
948 // formatter round-trip.
949 for versao in ["0.1.0", "1.2.3-alpha.1", "0.0.0", ""] {
950 let v: CaixaVersion = versao.into();
951 let expected = v.as_str().to_owned();
952 let owned: String = String::from(v);
953 assert_eq!(
954 owned, expected,
955 "String::from(v) must return the wrapper's own bytes verbatim",
956 );
957 assert_eq!(
958 owned, versao,
959 "String::from(v) must round-trip byte-equal through the From<&str> constructor",
960 );
961 }
962 }
963
964 #[test]
965 fn caixa_version_from_into_owned_string_and_as_str_agree_on_every_shape() {
966 // Fail-before-pass-after cross-axis partition pin: the owned-
967 // input [`From<CaixaVersion> for String`] reverse projection
968 // and the borrowed [`AsRef<str>`] projection resolve to the
969 // same bytes on every instance, and the paired forward
970 // [`From<String> for CaixaVersion`] constructor closes the
971 // `Self → String → Self` round-trip by construction. Refuses
972 // any future silent split between the owned-move reverse axis
973 // and the borrowed-clone AsRef axis (a stray normalization on
974 // one path only) that would let `String::from(v)` and
975 // `v.as_ref::<str>()` diverge on the same instance.
976 for versao in ["0.1.0", "1.2.3-alpha.1", "0.0.0", ""] {
977 let v: CaixaVersion = versao.into();
978 let via_as_ref: String = <CaixaVersion as AsRef<str>>::as_ref(&v).to_owned();
979 let via_to_string: String = v.to_string();
980 let via_from: String = String::from(v.clone());
981 assert_eq!(via_from, via_as_ref);
982 assert_eq!(via_from, via_to_string);
983 let round_trip: CaixaVersion = via_from.clone().into();
984 assert_eq!(round_trip, v);
985 }
986 }
987
988 #[test]
989 fn caixa_version_from_borrowed_into_owned_string_routes_through_as_str_accessor() {
990 // Fail-before-pass-after byte-parity pin on the lifted
991 // `impl From<&CaixaVersion> for String` — asserts the
992 // borrowed-input reverse projection allocates a fresh
993 // [`String`] whose bytes byte-equal the substrate-primitive
994 // [`CaixaVersion::as_str`] accessor on the same instance,
995 // preserving the source [`CaixaVersion`] intact (no move-out).
996 // Refuses any future silent detour that would route the impl
997 // through a divergent projection (a stray normalization step,
998 // a swap onto the sibling [`fmt::Display`]-routed
999 // [`ToString::to_string`] surface, a re-inlining that
1000 // dereferences `&self.0` outside the shared accessor).
1001 for versao in ["0.1.0", "1.2.3-alpha.1", "0.0.0", ""] {
1002 let v: CaixaVersion = versao.into();
1003 let via_borrowed: String = String::from(&v);
1004 assert_eq!(
1005 via_borrowed,
1006 v.as_str(),
1007 "String::from(&v) must byte-equal CaixaVersion::as_str",
1008 );
1009 // The borrowed-input impl must not move out of the source.
1010 assert_eq!(
1011 v.as_str(),
1012 versao,
1013 "source CaixaVersion must survive borrowed-input projection"
1014 );
1015 }
1016 }
1017
1018 #[test]
1019 fn caixa_version_from_owned_and_borrowed_into_string_agree_on_every_shape() {
1020 // Fail-before-pass-after cross-axis partition pin: the paired
1021 // owned-input [`From<CaixaVersion> for String`] and
1022 // borrowed-input [`From<&CaixaVersion> for String`] impls
1023 // resolve to the same bytes on every instance, closing the
1024 // "owned-input move vs. borrowed-input clone" bifurcation on
1025 // the same wrapped body. Refuses any future silent split
1026 // between the two corners (a normalization on one path only, a
1027 // divergent routing that would let `String::from(v.clone())`
1028 // and `String::from(&v)` disagree on the same body).
1029 for versao in ["0.1.0", "1.2.3-alpha.1", "0.0.0", ""] {
1030 let v: CaixaVersion = versao.into();
1031 let via_borrowed: String = String::from(&v);
1032 let via_owned: String = String::from(v.clone());
1033 assert_eq!(via_owned, via_borrowed);
1034 assert_eq!(via_borrowed, versao);
1035 }
1036 }
1037}