Skip to main content

tatara_process/
json_object.rs

1//! Substrate primitive over `serde_json::Value` — the ONE substrate
2//! owner of the `.as_object_mut().ok_or_else(|| anyhow::anyhow!(
3//! "<slot> is not an object"))` guard-shape every JSON-mutating helper
4//! restates by hand at the "walk this `Value` slot into its
5//! `serde_json::Map` interior or fail loud" boundary.
6//!
7//! Peer of the trait family that already lives in this crate on the
8//! wrap-shape axis:
9//!
10//! * [`crate::kube_error::KubeResultExt`] — the `kube::Error → anyhow`
11//!   display-prefix wrap.
12//! * [`crate::hostname::HostnameResultExt`] — the `HostnameError →
13//!   anyhow` display-prefix wrap.
14//! * [`crate::anyhow_flatten::FlattenCtxExt`] — the `anyhow::Error →
15//!   anyhow` display-prefix flatten.
16//! * This module — the `Option<&mut Map> → anyhow::Result<&mut Map>`
17//!   type-guard, partitioned from the three above by SOURCE (`None`
18//!   from the slot-typecheck, not a lifted error type) but sharing the
19//!   `.map_err(|_| anyhow!("<slug>: …"))?` display-prefix wire format.
20//!   The module also owns the READ-side [`ValueGetExt`] projector
21//!   (`.get_i64(<key>) -> Option<i64>`) — sibling of the three
22//!   MUTATION-side traits below on the (read, mutate) axis, closing
23//!   the READ half of the `serde_json::Value` substrate the four
24//!   traits jointly own.
25//!
26//! Pre-lift the shape was hand-authored at THREE adjacent private
27//! helpers in `tatara-reconciler::ssapply` past the ★★ PRIME-DIRECTIVE
28//! ≥ 2 duplication threshold:
29//!
30//! * `metadata_object_mut(resource)` — the root-guard step
31//!   (`resource.as_object_mut().ok_or_else(|| anyhow!("resource is not
32//!   an object"))?`) that opens the SSA-time
33//!   `resource → &mut metadata` walk shared by `inject_owner_reference`
34//!   + `inject_annotations`.
35//! * `metadata_object_mut(resource)` — the metadata-slot type-check
36//!   step (`metadata.as_object_mut().ok_or_else(|| anyhow!("metadata
37//!   is not an object"))?`) that closes the same walk — a resource
38//!   whose author mistyped the `metadata` slot as an array / string
39//!   surfaces as an error rather than as a silent
40//!   `.as_object_mut() → None → skip` no-op.
41//! * `inject_annotations(resource, process)` — the annotations-slot
42//!   type-check step (`annot.as_object_mut().ok_or_else(|| anyhow!(
43//!   "annotations is not an object"))?`) that opens the SSA-time
44//!   `metadata → &mut annotations` walk before the ownership tag +
45//!   observed-* primitive family drops its keys into the map.
46//!
47//! All three restated the SAME 2-line shape verbatim: `.as_object_mut()`
48//! on a `serde_json::Value` handle already known to be non-null, then
49//! `.ok_or_else(|| anyhow!("<slot-name> is not an object"))` wrap
50//! whose slot name matched the walk step's semantic role (`"resource"`
51//! / `"metadata"` / `"annotations"`). THREE byte-for-byte identical
52//! guard blocks past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold,
53//! differing only in the `&'static str` slot name each callsite
54//! stamped.
55//!
56//! Post-lift each callsite reads
57//! `<value>.as_object_mut_or("<slot>")?` and the guard-shape lives at
58//! ONE substrate owner here. The composed `anyhow::Error`'s `Display`
59//! is byte-identical to the pre-lift chain (`"<slot> is not an
60//! object"`), so operator-facing log output and any error-chain greps
61//! still match bytewise. A regression that drifts the message (a
62//! `"<slot> is not a JSON object"` synonym, a swapped `<slot>` slot,
63//! a promotion to a chain-form `source` that only surfaces via the
64//! alternate `{e:#}` formatter) surfaces at the tests below rather
65//! than as silent operator-facing drift across the three pre-lift
66//! consumers.
67//!
68//! ### Naming — `as_object_mut_or`, not `as_object_mut`
69//!
70//! Same discipline as the three sibling traits above — the trait
71//! method deliberately does NOT share a name with the inherent
72//! `serde_json::Value::as_object_mut` method (which returns
73//! `Option<&mut Map>`), because a name collision would let a caller
74//! who has `ValueObjectExt` in scope resolve to the inherent method
75//! by accident (inherent methods win over trait methods in method
76//! resolution) and silently drop the type-guard wrap altogether. The
77//! `_or` suffix names the intent: guard the `Option → Result` step
78//! at the same call, matching the pre-lift `.as_object_mut().
79//! ok_or_else(...)` chain.
80//!
81//! ### `#[must_use]`
82//!
83//! Every consumer threads the `?` short-circuit onto its handler's
84//! `Result<_, anyhow::Error>` return — dropping the guard swallows
85//! the underlying type-mismatch entirely, which is never the intended
86//! semantic at any of the three pre-lift consumers (each downstream
87//! `md.entry(...).or_insert_with(...)` / `annot.insert(...)` mutation
88//! depends on the returned `&mut Map` reference).
89//!
90//! Theory anchor: THEORY.md §VI.1 (generation over composition — the
91//! `.as_object_mut().ok_or_else(|| anyhow!("<slot> is not an
92//! object"))` guard-shape recurred at three hand-authored sites past
93//! the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to
94//! ONE substrate owner here). THEORY.md §II.1 invariant 5 (composition
95//! preserves proofs — a regression that drifts the guard message
96//! wording at ONE site surfaces here at the substrate pin rather than
97//! as silent operator-facing skew across every SSA-time
98//! `metadata_object_mut` + `inject_annotations` mutation).
99
100use serde_json::{Map, Value};
101
102/// Substrate extension trait over `serde_json::Value` — the ONE
103/// substrate owner of the `.as_object_mut().ok_or_else(|| anyhow!(
104/// "<slot> is not an object"))` guard-shape. See the module docs for
105/// the full callsite audit + the naming rationale (why
106/// `as_object_mut_or` and not `as_object_mut`).
107pub trait ValueObjectExt {
108    /// Borrow the [`Value`] as a mutable JSON object [`Map`], or fail
109    /// loud with an [`anyhow::Error`] whose `Display` reads exactly
110    /// `"<slot> is not an object"` — the pre-lift wire format every
111    /// consumer's `tracing::error!(error = %e, ...)` log line already
112    /// encoded.
113    #[must_use = "an object-guard that isn't threaded via `?` swallows the underlying type mismatch"]
114    fn as_object_mut_or(&mut self, slot: &'static str) -> anyhow::Result<&mut Map<String, Value>>;
115}
116
117impl ValueObjectExt for Value {
118    #[inline]
119    fn as_object_mut_or(&mut self, slot: &'static str) -> anyhow::Result<&mut Map<String, Value>> {
120        self.as_object_mut()
121            .ok_or_else(|| anyhow::anyhow!("{slot} is not an object"))
122    }
123}
124
125/// Substrate extension trait over `serde_json::Map<String, Value>` —
126/// the ONE substrate owner of the `map.insert(<key>.into(),
127/// Value::String(<val>.into()))` string-slot insertion shape every
128/// JSON-mutating helper in the workspace hand-authored at each callsite.
129///
130/// Peer of [`ValueObjectExt`] above on the JSON-mutation axis, split
131/// by SHAPE: [`ValueObjectExt::as_object_mut_or`] owns the "walk into
132/// this `Value`'s object-shape interior or fail loud" guard;
133/// [`JsonMapStrExt::insert_str`] owns the "stamp a `Value::String` at
134/// a string-typed key" write shape that every consumer downstream of
135/// the guard uses to populate the returned `&mut Map`.
136///
137/// Pre-lift the shape was hand-authored at SEVENTEEN production emit
138/// sites across `tatara-reconciler` past the ★★ PRIME-DIRECTIVE ≥ 2
139/// duplication threshold:
140///
141/// * `ssapply::inject_annotations` × 4 — the SSA-time observed-*
142///   annotation stamp family (`PID`, `CONTENT_HASH`, `GENERATION`,
143///   `ATTESTATION_ROOT`) each restated the 2-line `annot.insert(
144///   <annotation-const>.to_string(), Value::String(<val>.<coerce>))`
145///   shape verbatim.
146/// * `render::render_flux` × 3 — the Flux `Kustomization.spec` seeds
147///   (`interval`, `path`, `targetNamespace`), each restating the same
148///   `spec.insert("<key>".into(), Value::String(<val>))` shape.
149/// * `render::render_aplicacao` × 3 — the Flux `HelmRelease.spec`
150///   seeds (`releaseName`, `targetNamespace`) plus the values-overlay
151///   `profile` slot, each restating the same insert shape.
152/// * `render::render_export_job` × 2 — the export-Job outer label map
153///   (`ROLE`, `EXPORT_INDEX`) each restating the same insert shape.
154/// * `edges::IngressEdge::render` × 1 — the cert-manager
155///   `cluster-issuer` annotation, restating the same insert shape.
156/// * `edges::routing_edge_labels` × 2 — the routing-edge `metadata.
157///   labels` map's non-ownership slots (`APP`, `ROUTING_FORM`), each
158///   restating the same `labels.insert(<annotation-const>.to_string(),
159///   Value::String(<val>.into()))` shape past the ★★ PRIME-DIRECTIVE
160///   ≥ 2 duplication threshold — one of TWO adjacent bypass sites the
161///   substrate owner reaches through this lift.
162/// * `render::mark_resources_as_adopting` × 2 — the `encapsulation-
163///   mode` + `adopted-release` annotation stamps on adoption-mode
164///   render, each restating the same `anns_obj.insert("<key>".into(),
165///   Value::String(<val>.into()))` shape past the ★★ PRIME-DIRECTIVE
166///   ≥ 2 duplication threshold. The adopted-release value slot also
167///   routes its `<ns>/<release>` join through the sibling
168///   [`crate::qualified_process_ref`] substrate composer, closing a
169///   bare `format!("{ns}/{name}")` bypass on the `<ns>/<name>` join
170///   axis at this same callsite.
171///
172/// All SEVENTEEN pre-lift sites restated the SAME 2-line shape verbatim,
173/// differing only in the `&'static str` / `String` key + the `&str` /
174/// `String` value at each callsite. A copy-paste that dropped the
175/// `Value::String(...)` wrap (a caller who reached for
176/// `.insert(k, v)` after refactoring from a `Value` slot to a plain
177/// `String` value slot) would type-check silently at every callsite —
178/// `Map<String, Value>::insert` expects a `Value`, and `String:
179/// Into<Value>` is provided by `serde_json` via the `Value::String`
180/// arm's `From` impl, so the naive `.insert(k, v.to_string())` compiles
181/// AND writes the byte-identical JSON. Post-lift each callsite reads
182/// `<map>.insert_str(<key>, <val>)` and the string-slot write shape
183/// lives at ONE substrate owner here.
184///
185/// ### Composability
186///
187/// * Key slot accepts any `impl Into<String>`: `&str` (via
188///   `String::from`), `String` (identity), `Cow<'_, str>`, so a
189///   callsite with a static `annotations::PID` (`&'static str`) reads
190///   `insert_str(annotations::PID, …)` with no `.to_string()` per site.
191/// * Value slot accepts any `impl Into<String>`: `&str`, `String`,
192///   `Cow<'_, str>`. Numeric or non-string values still need an
193///   explicit `.to_string()` at the callsite — same as pre-lift, so
194///   the wrapping shape stays visible in the caller's grep footprint.
195/// * Returns `Option<Value>` matching the inherent
196///   `Map<String, Value>::insert` return semantics: `None` on new-key,
197///   `Some(prev)` on overwrite of an existing slot.
198///
199/// ### Naming — `insert_str`, not `insert`
200///
201/// Same discipline as [`ValueObjectExt::as_object_mut_or`] above — the
202/// trait method deliberately does NOT collide with the inherent
203/// `Map::insert` (which takes `(String, Value)` positionally). A name
204/// collision would let a caller who has `JsonMapStrExt` in scope
205/// resolve to the inherent method by accident (inherent methods win
206/// over trait methods in method resolution) and silently drop the
207/// `Value::String` wrap, stamping the value bytes straight into the
208/// map under a different `Value` variant. The `_str` suffix names the
209/// intent: the value slot IS the `Value::String` arm at this write.
210///
211/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
212/// `.insert(<k>.into(), Value::String(<v>.into()))` shape recurred at
213/// SEVENTEEN hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
214/// duplication trigger, and is lifted to ONE substrate owner here).
215/// THEORY.md §II.1 invariant 5 (composition preserves proofs — a
216/// regression that drifts the string-slot write shape at ONE consumer
217/// surfaces at the substrate pin rather than as silent per-emit skew
218/// across every ssapply / render / edges JSON emit site).
219pub trait JsonMapStrExt {
220    /// Insert a `Value::String(<val>.into())` at `<key>.into()` into
221    /// this JSON object map. Returns `Option<Value>` matching the
222    /// underlying `Map::insert` semantics — `None` for a new key,
223    /// `Some(prev)` for an overwrite.
224    fn insert_str(&mut self, key: impl Into<String>, value: impl Into<String>) -> Option<Value>;
225}
226
227impl JsonMapStrExt for Map<String, Value> {
228    #[inline]
229    fn insert_str(&mut self, key: impl Into<String>, value: impl Into<String>) -> Option<Value> {
230        self.insert(key.into(), Value::String(value.into()))
231    }
232}
233
234/// Substrate extension trait over `serde_json::Map<String, Value>` —
235/// the ONE substrate owner of the `.entry(<key>).or_insert_with(||
236/// Value::Object(<empty>))` seed-then-guard shape every JSON-mutating
237/// helper hand-authored at the "walk into this object slot on the
238/// parent map, seeding an empty object if the slot is absent, or fail
239/// loud if the slot exists but is a non-object" boundary.
240///
241/// Peer of [`ValueObjectExt::as_object_mut_or`] and
242/// [`JsonMapStrExt::insert_str`] on the JSON-mutation axis; split by
243/// SHAPE + SITE. [`ValueObjectExt::as_object_mut_or`] owns the "guard
244/// a `Value` handle into its object interior" step at ONE level;
245/// [`JsonMapStrExt::insert_str`] owns the "stamp a `Value::String` at
246/// a string-typed key" write shape; this trait owns the compound
247/// "get-or-seed the object at a slot, then guard" step every SSA-time
248/// re-injection walks when the caller intends to reach a nested
249/// object slot without asserting whether the parent has already
250/// populated it (a caller composing a fresh resource-body carries
251/// no `metadata` / `metadata.annotations` slot pre-seed; a caller
252/// composing atop a pre-populated resource does — both paths reach
253/// the same primitive).
254///
255/// Pre-lift the compound shape was hand-authored at TWO adjacent
256/// private helpers in `tatara-reconciler::ssapply` past the ★★
257/// PRIME-DIRECTIVE ≥ 2 duplication threshold, both walking the SAME
258/// 3-step `let X = <map>.entry(<slot>).or_insert_with(|| Value::Object
259/// (<empty>)); X.as_object_mut_or(<slot>)?` incantation:
260///
261/// * `metadata_object_mut(resource)` — the `metadata` slot seed-then-
262///   guard step at the root of every SSA-time re-injection walk
263///   (`inject_owner_reference` + `inject_annotations` reach it).
264/// * `inject_annotations(resource, process)` — the `annotations`
265///   slot seed-then-guard step nested one level deeper under the
266///   `metadata` object the primitive above returned.
267///
268/// Both restated the SAME 3-line shape verbatim: `.entry(<slot>)` on
269/// a `Map<String, Value>` handle known to be an object, then
270/// `.or_insert_with(|| Value::Object(<empty>))` to synthesize an
271/// empty object at the slot when absent, then a `.as_object_mut_or
272/// (<slot>)?` guard on the returned `&mut Value` to fail loud when
273/// the existing slot is a non-object. TWO byte-for-byte identical
274/// blocks past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold,
275/// differing only in the `&'static str` slot name each callsite
276/// stamped (`"metadata"` / `"annotations"`) — and the slot name is
277/// used at BOTH the entry key AND the guard error message so a
278/// regression that drifted the two apart at one callsite (a typo
279/// stamping `"metadata"` into the entry key + `"metadatas"` into
280/// the error message) would silently pass one pin and fail the
281/// other. Post-lift each callsite reads `<map>.object_slot_mut_or
282/// (<slot>)?` and the compound shape lives at ONE substrate owner
283/// here — the slot name is stamped ONCE per call and reaches both
284/// the entry key and the guard error slot mechanically.
285///
286/// ### Composability
287///
288/// * Slot name is `&'static str` — pre-lift both callsites stamped
289///   `&'static str` literals (`"metadata"` / `"annotations"`); a
290///   dynamic-slot caller (a callsite that reached this primitive
291///   with a `String` key computed at runtime) has no pre-lift
292///   precedent in the ssapply/render axis, so the `&'static str`
293///   bound stays honest to the pre-lift shape. A future caller
294///   needing a runtime slot name can widen this to
295///   `impl Into<String>` at the substrate; the pre-lift consumers
296///   inherit it mechanically.
297/// * Returns `anyhow::Result<&mut Map<String, Value>>` — matches the
298///   sibling [`ValueObjectExt::as_object_mut_or`] shape so the
299///   downstream `.entry(...).or_insert_with(...)` / `.insert(...)`
300///   mutation threads through `?` onto the caller's
301///   `Result<_, anyhow::Error>` return exactly as pre-lift.
302/// * Ok-arm returns the SAME `&mut Map<String, Value>` the pre-lift
303///   `.as_object_mut_or(<slot>)` step returned — no clone, no key-
304///   order reshape, no synthesis.
305///
306/// ### Naming — `object_slot_mut_or`, not `entry_object` or
307/// `get_or_insert_object_mut`
308///
309/// Same discipline as the two sibling traits above — the trait method
310/// deliberately does NOT collide with the inherent `Map::entry` /
311/// `Map::get_mut` / `Map::insert` methods (any of which a caller who
312/// has this trait in scope could resolve to by accident, silently
313/// dropping the type-guard step). The `_or` suffix names the intent
314/// (guard the `Option → Result` step at the same call, matching the
315/// pre-lift `.as_object_mut_or(<slot>)?` guard); `object_slot_mut`
316/// names the target shape (return an `&mut` object-typed `Map` at
317/// the slot). Together they read as "guard the slot into a mutable
318/// object interior or fail loud", matching the pre-lift semantics
319/// exactly.
320///
321/// ### `#[must_use]`
322///
323/// Every consumer threads the `?` short-circuit onto its handler's
324/// `Result<_, anyhow::Error>` return — dropping the guard swallows
325/// the underlying type-mismatch entirely, which is never the intended
326/// semantic at either pre-lift consumer (each downstream
327/// `.entry(...).or_insert_with(...)` / `.insert(...)` mutation
328/// depends on the returned `&mut Map` reference).
329///
330/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
331/// 3-line `.entry(<slot>).or_insert_with(|| Value::Object(<empty>))
332/// .as_object_mut_or(<slot>)?` compound shape recurred at two
333/// hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
334/// trigger, and is lifted to ONE substrate owner here). THEORY.md
335/// §II.1 invariant 5 (composition preserves proofs — a regression
336/// that drifted the entry-key slot vs. the guard-error slot at ONE
337/// site would silently pass one downstream pin and fail the other;
338/// post-lift the primitive stamps the slot ONCE per call so the
339/// substrate itself owns the entry-key ↔ guard-error name coherence).
340pub trait JsonMapObjectEntryExt {
341    /// Get-or-seed the object at `slot` in this JSON map, then guard
342    /// that the resulting handle is an object; returns
343    /// `&mut Map<String, Value>` on the object arm, and an
344    /// [`anyhow::Error`] whose `Display` reads
345    /// `"<slot> is not an object"` on the non-object arm (byte-
346    /// identical to the pre-lift `.as_object_mut_or(<slot>)?` guard,
347    /// sourced from the sibling [`ValueObjectExt::as_object_mut_or`]).
348    #[must_use = "an object-slot guard that isn't threaded via `?` swallows the underlying type mismatch"]
349    fn object_slot_mut_or(&mut self, slot: &'static str)
350        -> anyhow::Result<&mut Map<String, Value>>;
351}
352
353impl JsonMapObjectEntryExt for Map<String, Value> {
354    #[inline]
355    fn object_slot_mut_or(
356        &mut self,
357        slot: &'static str,
358    ) -> anyhow::Result<&mut Map<String, Value>> {
359        self.entry(slot)
360            .or_insert_with(|| Value::Object(Map::new()))
361            .as_object_mut_or(slot)
362    }
363}
364
365/// Substrate extension trait over `serde_json::Value` — the ONE
366/// substrate owner of the paired `.get(<key>).and_then(|v| v.as_<T>())`
367/// two-link READ chain every downstream projection walks to pull a
368/// typed leaf off a Kubernetes-status blob (or an equivalent
369/// rendered-resource JSON object) without asserting the slot is
370/// present, without asserting its variant, and without asserting the
371/// slot fits the target scalar type.
372///
373/// The trait carries ONE method per typed READ axis; the axis-family
374/// is [`Self::get_i64`] (integer counters) + [`Self::get_str`]
375/// (string slots) + [`Self::get_array`] (JSON array slots). Adding a
376/// new axis (a `get_bool` for `Value::Bool`, a `get_object` for
377/// `Value::Object`, a `get_f64` for `Value::Number` truncated to
378/// `f64`) lands as ONE new method here + ONE impl arm, inheriting
379/// the naming, `#[must_use]`, and inline discipline the existing
380/// axes pin. Never open a peer trait for a new axis — keep every
381/// READ projection on the ONE substrate owner so a caller who
382/// imports `ValueGetExt` reaches every axis through the same trait
383/// handle.
384///
385/// READ-side counterpart to the three MUTATION-side siblings already in
386/// this module — [`ValueObjectExt::as_object_mut_or`],
387/// [`JsonMapStrExt::insert_str`], [`JsonMapObjectEntryExt::object_slot_mut_or`]
388/// — partitioning the substrate along the (read, mutate) axis on the
389/// same `serde_json::Value` / `serde_json::Map<String, Value>` carrier
390/// pair.
391///
392/// Pre-lift the two-link chain was hand-authored at THREE adjacent
393/// slots inside `tatara-reconciler::boundary::fetch_job_status`, each
394/// projecting one `batch/v1::Job` `status.<counter>` field out of the
395/// fetched `serde_json::Value` object into a private `JobStatusView`
396/// row past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold:
397///
398/// * `status.get("succeeded").and_then(|v| v.as_i64())` — the
399///   Job-completion counter every `JobAttested` + `ClosedLoopAuth`
400///   postcondition evaluator gates on (`succeeded < 1` short-circuits
401///   to `Satisfaction::Unsatisfied("… still running (…)")`).
402/// * `status.get("failed").and_then(|v| v.as_i64())` — the
403///   Job-failure counter the same evaluators gate on
404///   (`failed > 0` short-circuits to
405///   `Satisfaction::Unsatisfied("… failed (status.failed={n})")`).
406/// * `status.get("active").and_then(|v| v.as_i64())` — the
407///   Job-in-flight counter the "still running" diagnostic tail
408///   reports as `(succeeded={s}, active={a})`.
409///
410/// All THREE sites walked the SAME two-link chain — `.get(<key>)` on a
411/// `serde_json::Value` already known to be the status object, then
412/// `.and_then(|v| v.as_i64())` on the returned `Option<&Value>` — and
413/// each was followed by an `if let Some(...)` write into the
414/// [`JobStatusView`] row initialised from `Default::default()`. Post-
415/// lift each callsite reads `status.get_i64(<key>)` and the two-link
416/// READ chain lives at ONE substrate owner here.
417///
418/// ### Naming — `get_i64`, not `as_i64` or `i64_at`
419///
420/// Same discipline as the three sibling traits above — the trait method
421/// deliberately does NOT collide with `serde_json::Value::as_i64` (the
422/// inherent projection on a single `Value` handle) nor with
423/// `serde_json::Value::get` (the inherent slot-lookup returning
424/// `Option<&Value>`). A name collision would let a caller who has
425/// `ValueGetExt` in scope resolve to one of the inherent methods by
426/// accident (inherent methods win over trait methods in method
427/// resolution) and silently drop half of the paired chain. The
428/// `get_i64(<key>)` shape names the intent: look up the slot at
429/// `<key>`, project the returned handle to `i64`, in ONE call.
430///
431/// ### `#[must_use]`
432///
433/// Every consumer either binds the returned `Option<i64>` into a
434/// downstream `if let Some(n) = ...` / `.unwrap_or_default()` / struct-
435/// field construction. Dropping the return silently discards the
436/// projection entirely, which is never the intended semantic at the
437/// three pre-lift consumers (each downstream write depends on the
438/// returned counter).
439///
440/// ### Composability
441///
442/// * Key slot is `&str` — matches every pre-lift `.get("<literal>")`
443///   callsite and the inherent `serde_json::Value::get`'s primary
444///   `str`-index arm. A caller with a runtime-computed key (a
445///   `String` produced by a template composer) reaches through
446///   `.get_i64(&s)` mechanically via `Deref<Target = str>`.
447/// * Returns `Option<i64>` matching the composed inherent chain's own
448///   return; a consumer wanting the "absent or non-integer → 0"
449///   fallback composes `.unwrap_or_default()` (or `.unwrap_or(0)`) at
450///   the callsite, keeping the "should this counter default to 0 or
451///   fail loud" decision at the caller rather than baking it into the
452///   primitive.
453/// * Non-object receivers (a `Value::String`, a `Value::Null`) return
454///   `None` verbatim via the inherent `Value::get`'s own non-object-
455///   arm behaviour, matching the pre-lift chain's semantics on the
456///   corner where the caller's status blob is malformed.
457///
458/// A future normalization — a per-fleet clamp that rejects negative
459/// counters (the K8s API server never emits them, but a fixture
460/// authoring bug could), a `Value::Number` fallback that accepts
461/// `f64` counters truncated to `i64`, a `checked` overflow arm that
462/// promotes an out-of-range integer to a diagnostic rather than a
463/// silent `None` — lands at THIS ONE substrate primitive and every
464/// downstream Job-status / Deployment-replica / HPA-desired-count
465/// counter reader inherits the upgrade mechanically. No per-site edit
466/// at any of the 3 listed callers or at future consumers (a
467/// Deployment `readyReplicas` projection, an HPA `currentReplicas`
468/// gate, a StatefulSet `updatedReplicas` freshness check).
469///
470/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
471/// two-link `.get(<key>).and_then(|v| v.as_i64())` chain recurred at
472/// three hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
473/// duplication trigger, and is lifted to ONE substrate owner here).
474/// THEORY.md §II.1 invariant 5 (composition preserves proofs — a
475/// regression that drifted the projection axis at ONE site — a swap
476/// of `as_i64` for `as_u64` narrowing the accepted range, a swap of
477/// `.get(<key>)` for `.pointer("<key>")` losing the direct-child
478/// semantics — would silently pass every downstream `JobStatusView`
479/// composition and surface as a wrong counter at operator-facing
480/// diagnostic wording; post-lift the projection lives at ONE typed
481/// owner so a regression surfaces at [`tests::get_i64_null_arm_returns_none`]
482/// / peers rather than as silent operator-facing drift).
483pub trait ValueGetExt {
484    /// Look up `key` on this JSON object and project the returned
485    /// handle to `i64`; returns `None` when the slot is absent, when
486    /// the receiver is not a JSON object, or when the slot's variant
487    /// is not integer-shaped.
488    #[must_use = "a JSON i64 projection that isn't bound swallows the counter entirely"]
489    fn get_i64(&self, key: &str) -> Option<i64>;
490
491    /// Look up `key` on this JSON object and project the returned
492    /// handle to `&str`; returns `None` when the slot is absent, when
493    /// the receiver is not a JSON object, or when the slot's variant
494    /// is not `Value::String`.
495    ///
496    /// String-axis sibling of [`Self::get_i64`] on the same
497    /// `.get(<key>).and_then(|v| v.as_<T>())` READ-chain lift. Pre-lift
498    /// the two-link chain was hand-authored at SEVEN production sites
499    /// across two crates past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
500    /// threshold:
501    ///
502    /// * `tatara-process::status::RenderedResourceCoords::from_json`
503    ///   — FOUR paired reads (`apiVersion`, `kind`, `metadata.name`,
504    ///   `metadata.namespace`) that project the four rendered-resource
505    ///   coordinate slots off a `serde_json::Value` rendered manifest
506    ///   into the typed `RenderedResourceCoords` row; the required
507    ///   three (`apiVersion` / `kind` / `metadata.name`) compose with
508    ///   `.ok_or_else(|| anyhow!("rendered resource missing X"))?
509    ///   .to_string()`, and the optional `metadata.namespace` composes
510    ///   with `.map(str::to_string)`.
511    /// * `tatara-reconciler::ssapply::ready_condition_value` — THREE
512    ///   paired reads (`type`, `status`, `message`) inside the
513    ///   condition-walker's per-condition classifier, each pulling a
514    ///   `Value::String` slot off a K8s Condition object off the
515    ///   `status.conditions[]` array.
516    ///
517    /// All seven sites walked the SAME two-link chain — `.get(<key>)`
518    /// on a `serde_json::Value` already known to be an object, then
519    /// `.and_then(|v| v.as_str())` on the returned `Option<&Value>` —
520    /// and each composed different downstream tails (fallible
521    /// `.ok_or_else(...)?.to_string()`, optional `.map(String::from)`,
522    /// pattern-match `Some("True")` / `Some("False")` / `_`). Post-lift
523    /// each callsite reads `<value>.get_str(<key>)` and the two-link
524    /// READ chain lives at ONE substrate owner here.
525    ///
526    /// ### Naming — `get_str`, not `as_str` or `str_at`
527    ///
528    /// Same discipline as [`Self::get_i64`] — the trait method
529    /// deliberately does NOT collide with `serde_json::Value::as_str`
530    /// (the inherent projection on a single `Value` handle) nor with
531    /// `serde_json::Value::get` (the inherent slot-lookup returning
532    /// `Option<&Value>`). A name collision would let a caller who has
533    /// [`ValueGetExt`] in scope resolve to one of the inherent methods
534    /// by accident (inherent methods win over trait methods in method
535    /// resolution) and silently drop half of the paired chain. The
536    /// `get_str(<key>)` shape names the intent: look up the slot at
537    /// `<key>`, project the returned handle to `&str`, in ONE call.
538    ///
539    /// ### `#[must_use]`
540    ///
541    /// Every pre-lift consumer binds the returned `Option<&str>` into
542    /// a downstream `.ok_or_else(...)?.to_string()` / `.map(String::from)`
543    /// / `.map(str::to_string)` / pattern-match arm. Dropping the
544    /// return silently discards the projection entirely, which is
545    /// never the intended semantic at any of the seven pre-lift
546    /// consumers.
547    ///
548    /// ### Return lifetime
549    ///
550    /// The `&str` borrows the same buffer the underlying
551    /// `Value::String` variant owns; the `Option<&str>` is bounded by
552    /// the receiver's lifetime (`&'_ self`), so a caller holding onto
553    /// the returned slice keeps the receiver borrowed. Matches the
554    /// pre-lift chain's own borrow shape (`v.as_str()` borrows through
555    /// the `&Value`).
556    ///
557    /// A future normalization on the projection — a Unicode
558    /// normalization pass (NFC-folding annotation values), a
559    /// per-fleet trim of leading/trailing whitespace, a rejection of
560    /// empty-string arms as "the caller meant absent" — lands at THIS
561    /// ONE substrate primitive and every downstream `apiVersion` /
562    /// `kind` / `metadata.name` / K8s-condition-string reader
563    /// inherits the upgrade mechanically.
564    ///
565    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
566    /// the two-link `.get(<key>).and_then(|v| v.as_str())` chain
567    /// recurred at SEVEN production sites across two crates past the
568    /// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to
569    /// ONE substrate owner here on the string axis of the same
570    /// READ-chain axis-family the `get_i64` sibling opened for the
571    /// integer axis). THEORY.md §II.1 invariant 5 (composition
572    /// preserves proofs — a regression that drifted the projection
573    /// axis at ONE site would silently pass every downstream
574    /// composition and surface as a wrong slot at operator-facing
575    /// diagnostic wording; post-lift the projection lives at ONE
576    /// typed owner so a regression surfaces at
577    /// [`tests::get_str_present_string_slot_returns_the_slice`] /
578    /// peers rather than as silent operator-facing drift).
579    #[must_use = "a JSON &str projection that isn't bound swallows the slot entirely"]
580    fn get_str(&self, key: &str) -> Option<&str>;
581
582    /// Look up `key` on this JSON object and project the returned
583    /// handle to `&Vec<Value>`; returns `None` when the slot is
584    /// absent, when the receiver is not a JSON object, or when the
585    /// slot's variant is not `Value::Array`.
586    ///
587    /// Array-axis sibling of [`Self::get_i64`] + [`Self::get_str`]
588    /// on the same `.get(<key>).and_then(|v| v.as_<T>())` READ-chain
589    /// axis-family. Pre-lift the two-link chain was hand-authored at
590    /// TWO production sites across two crates past the ★★
591    /// PRIME-DIRECTIVE ≥ 2 duplication threshold:
592    ///
593    /// * `tatara-reconciler::ssapply::ready_condition_value` — the
594    ///   tail of the `data.get("status").and_then(|s|
595    ///   s.get("conditions")).and_then(|c| c.as_array())` walker that
596    ///   opens the K8s Condition classifier every DynamicObject
597    ///   readiness probe rides through.
598    /// * `tatara-closed-loop-probe::probe::count_jwks_keys` — the
599    ///   JWKS-response walker that counts issuer-side public keys off
600    ///   the `keys` slot for the closed-loop probe's per-run
601    ///   `jwks_key_count` diagnostic.
602    ///
603    /// Both sites walked the SAME two-link chain — `.get(<key>)` on a
604    /// `serde_json::Value` already known to be an object, then
605    /// `.and_then(|v| v.as_array())` on the returned `Option<&Value>`
606    /// — and composed different downstream tails (`Some(conditions)`
607    /// pattern-match on the reconciler side, `.map(|xs| xs.len() as
608    /// u64)` on the probe side). Post-lift each callsite reads
609    /// `<value>.get_array(<key>)` and the two-link READ chain lives at
610    /// ONE substrate owner here. The probe-side variant additionally
611    /// sheds the pre-lift `.get("keys").cloned()` allocation because
612    /// this primitive borrows through the receiver rather than
613    /// cloning.
614    ///
615    /// ### Naming — `get_array`, not `as_array` or `array_at`
616    ///
617    /// Same discipline as [`Self::get_i64`] + [`Self::get_str`] — the
618    /// trait method deliberately does NOT collide with
619    /// `serde_json::Value::as_array` (the inherent projection on a
620    /// single `Value` handle) nor with `serde_json::Value::get` (the
621    /// inherent slot-lookup returning `Option<&Value>`). A name
622    /// collision would let a caller who has [`ValueGetExt`] in scope
623    /// resolve to one of the inherent methods by accident (inherent
624    /// methods win over trait methods in method resolution) and
625    /// silently drop half of the paired chain. The `get_array(<key>)`
626    /// shape names the intent: look up the slot at `<key>`, project
627    /// the returned handle to `&Vec<Value>`, in ONE call.
628    ///
629    /// ### `#[must_use]`
630    ///
631    /// Every pre-lift consumer binds the returned `Option<&Vec<Value>>`
632    /// into a downstream `let Some(...) = ... else { return ... }`
633    /// short-circuit or a `.map(|xs| xs.len() as u64).unwrap_or(0)`
634    /// counter composition. Dropping the return silently discards the
635    /// projection entirely, which is never the intended semantic at
636    /// either pre-lift consumer.
637    ///
638    /// ### Return lifetime
639    ///
640    /// The `&Vec<Value>` borrows the same buffer the underlying
641    /// `Value::Array` variant owns; the `Option<&Vec<Value>>` is
642    /// bounded by the receiver's lifetime (`&'_ self`), so a caller
643    /// iterating the returned slice keeps the receiver borrowed.
644    /// Matches the pre-lift chain's own borrow shape (`v.as_array()`
645    /// borrows through the `&Value`), and in the probe.rs case
646    /// eliminates the pre-lift `.cloned()` on the intermediate
647    /// `Value` that only existed to sidestep the borrow.
648    ///
649    /// A future normalization on the projection — a rejection of
650    /// empty arrays as "the caller meant absent", an accept-scalar
651    /// coercion (a `Value::String` promoted to a one-element array),
652    /// a per-fleet cap on array length that short-circuits pathological
653    /// payloads — lands at THIS ONE substrate primitive and every
654    /// downstream K8s-Condition classifier / JWKS-array counter /
655    /// future array-slot reader inherits the upgrade mechanically.
656    ///
657    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
658    /// the two-link `.get(<key>).and_then(|v| v.as_array())` chain
659    /// recurred at two production sites across two crates past the ★★
660    /// PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE
661    /// substrate owner here on the array axis of the same READ-chain
662    /// axis-family the `get_i64` + `get_str` siblings already own).
663    /// THEORY.md §II.1 invariant 5 (composition preserves proofs — a
664    /// regression that drifted the projection axis at ONE site would
665    /// silently pass every downstream composition and surface as a
666    /// wrong slot at operator-facing diagnostic wording; post-lift the
667    /// projection lives at ONE typed owner so a regression surfaces
668    /// at [`tests::get_array_present_array_slot_returns_the_slice`] /
669    /// peers rather than as silent operator-facing drift).
670    #[must_use = "a JSON array projection that isn't bound swallows the slot entirely"]
671    fn get_array(&self, key: &str) -> Option<&Vec<Value>>;
672}
673
674impl ValueGetExt for Value {
675    #[inline]
676    fn get_i64(&self, key: &str) -> Option<i64> {
677        self.get(key).and_then(Value::as_i64)
678    }
679
680    #[inline]
681    fn get_str(&self, key: &str) -> Option<&str> {
682        self.get(key).and_then(Value::as_str)
683    }
684
685    #[inline]
686    fn get_array(&self, key: &str) -> Option<&Vec<Value>> {
687        self.get(key).and_then(Value::as_array)
688    }
689}
690
691/// Receiver-shape widening of the READ-projection axis-family — the
692/// same three methods extended from `Value` (the `Value::Object` arm's
693/// walker) to `Map<String, Value>` (the object interior itself),
694/// closing the receiver-shape gap so a caller who already holds an
695/// `&Map<String, Value>` handle (via `.as_object().unwrap()`, via
696/// [`ValueObjectExt::as_object_mut_or`], via the two `JsonMap*Ext`
697/// siblings' returns, or via a helper like `ssapply::ownership_kv_pair`
698/// that composes and returns a `Map` directly) reaches the SAME
699/// `get_i64` / `get_str` / `get_array` methods without a
700/// `Value::Object(m)` rewrap detour.
701///
702/// Pre-lift the `.get(<key>).and_then(Value::as_<T>)` two-link chain
703/// was hand-authored at 30 `Map<String, Value>`-receiver sites past the
704/// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold — 19 in
705/// `tatara-reconciler::patch` tests (the phase-status wire-shape pins
706/// walking `obj = v.as_object().unwrap()` and `metadata = obj.get(
707/// "metadata").and_then(Value::as_object).unwrap()` receivers) plus
708/// 11 in `tatara-reconciler::ssapply` tests (the ownership-tag +
709/// composed-coord pins walking the `Map` handles returned by
710/// `ownership_annotations` / `ownership_labels` /
711/// `ownership_annotations_by_coord`). Post-lift each callsite reads
712/// `<map>.get_str(<key>)` / `<map>.get_array(<key>)` and the READ
713/// chain rides through the SAME substrate owner the `Value`-receiver
714/// callers already threaded through.
715///
716/// The axis-family invariant (a caller who imports `ValueGetExt`
717/// reaches every axis through the same trait handle — pinned at
718/// [`tests::get_array_axis_family_reaches_i64_str_and_array_through_one_trait_import`]
719/// and its `get_str` sibling) extends verbatim to the `Map` receiver:
720/// a single `use tatara_process::json_object::ValueGetExt;` unlocks
721/// every axis on both receiver shapes. A future new axis (e.g. a
722/// `get_bool` for `Value::Bool` slots) adds one method on the trait
723/// and inherits both impls; there is no separate `MapGetExt` peer to
724/// keep in sync.
725///
726/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
727/// two-link chain recurred at 30 `Map`-receiver sites past the ★★
728/// PRIME-DIRECTIVE ≥ 2 duplication trigger, and rides through the
729/// same substrate owner the pre-existing `Value`-receiver impl above
730/// already pinned). THEORY.md §II.1 invariant 5 (composition preserves
731/// proofs — the receiver-shape widening carries the axis-family
732/// invariant across without splitting it into two traits).
733impl ValueGetExt for Map<String, Value> {
734    #[inline]
735    fn get_i64(&self, key: &str) -> Option<i64> {
736        self.get(key).and_then(Value::as_i64)
737    }
738
739    #[inline]
740    fn get_str(&self, key: &str) -> Option<&str> {
741        self.get(key).and_then(Value::as_str)
742    }
743
744    #[inline]
745    fn get_array(&self, key: &str) -> Option<&Vec<Value>> {
746        self.get(key).and_then(Value::as_array)
747    }
748}
749
750#[cfg(test)]
751mod tests {
752    use super::*;
753    use serde_json::json;
754
755    // ─── ValueObjectExt::as_object_mut_or substrate pins ─────────────
756    //
757    // Fail-before-pass-after granularity: the `ValueObjectExt::
758    // as_object_mut_or` trait method did not exist before this commit,
759    // so each test below fails to compile pre-lift. Post-lift they
760    // collectively pin the object-guard shape at ONE substrate owner —
761    // a regression that drifts the error message wording, swaps the
762    // `<slot>` slot, wraps the source in a chain-form `source` (which
763    // would change `Display` output when downstream tracing formatters
764    // interpolate `{e}` rather than the chain-walking `{e:#}`), or
765    // promotes the pass-through arm to synthesis (a `None → Ok(&mut
766    // Map::default())` fallthrough that silently swallows a mistyped
767    // slot) surfaces HERE rather than as silent operator-facing skew
768    // across the three `ssapply.rs` pre-lift consumers whose log
769    // output already encoded the flat `"<slot> is not an object"`
770    // shape.
771
772    #[test]
773    fn as_object_mut_or_object_arm_returns_the_inner_map_mutably() {
774        // Ok-arm invariant: a `Value::Object` handle threaded through
775        // `as_object_mut_or("<slot>")` MUST return `Ok(&mut Map)`
776        // whose interior is the SAME `serde_json::Map` the underlying
777        // `serde_json::Value::as_object_mut` would return — no clone,
778        // no reshape, no synthesis. The `&mut` return is load-bearing
779        // at every consumer (each threads a downstream `.entry(...).
780        // or_insert_with(...)` / `.insert(...)` mutation onto the
781        // returned reference), so a regression that returned a fresh
782        // owned `Map` here would silently drop every downstream write.
783        let mut v = json!({ "existing_key": "existing_value" });
784        let map = v.as_object_mut_or("resource").expect("Value::Object");
785        map.insert("new_key".to_string(), json!("new_value"));
786        assert_eq!(v["existing_key"], "existing_value");
787        assert_eq!(v["new_key"], "new_value");
788    }
789
790    #[test]
791    fn as_object_mut_or_null_arm_errors_with_pre_lift_display_bytewise() {
792        // Byte-shape parity pin: the wrap output of `as_object_mut_or
793        // ("<slot>")` on a `Value::Null` handle MUST be `Display`-
794        // identical to the pre-lift hand-authored `.as_object_mut().
795        // ok_or_else(|| anyhow!("<slot> is not an object"))?` chain.
796        // A regression that inserted a synonym (`"<slot> is not a
797        // JSON object"`), reshaped the slot position (`"not an
798        // object: <slot>"`), or dropped the leading `<slot>` slot
799        // surfaces HERE rather than as silent drift at every
800        // downstream log-output consumer.
801        let mut v = Value::Null;
802        let err = v.as_object_mut_or("resource").unwrap_err();
803        assert_eq!(format!("{err}"), "resource is not an object");
804    }
805
806    #[test]
807    fn as_object_mut_or_array_arm_errors_with_pre_lift_display_bytewise() {
808        // Sibling to the null-arm byte-shape pin — a mistyped
809        // `metadata` slot authored as a JSON array (kubectl accepts
810        // `metadata: []` in a YAML manifest with no schema, though the
811        // apiserver later rejects it) surfaces the same guard error.
812        // Pins the "non-object variants ALL error via the same wire
813        // format" invariant — a regression that special-cased the
814        // array variant (returning a fresh empty map, silently
815        // coercing) surfaces HERE.
816        let mut v = json!(["not", "an", "object"]);
817        let err = v.as_object_mut_or("metadata").unwrap_err();
818        assert_eq!(format!("{err}"), "metadata is not an object");
819    }
820
821    #[test]
822    fn as_object_mut_or_string_arm_errors_with_pre_lift_display_bytewise() {
823        // Sibling to the null / array pins — a mistyped `annotations`
824        // slot authored as a JSON string (a common apiserver-layer
825        // authoring bug in kubectl-generated manifests where a
826        // stringified JSON object leaks through) surfaces the same
827        // guard error. Pins the "every non-object variant errors via
828        // the same wire format" invariant across the full
829        // `serde_json::Value` sum.
830        let mut v = json!("stringified");
831        let err = v.as_object_mut_or("annotations").unwrap_err();
832        assert_eq!(format!("{err}"), "annotations is not an object");
833    }
834
835    #[test]
836    fn as_object_mut_or_threads_the_slot_slug_verbatim_across_all_three_pre_lift_labels() {
837        // Cross-slot coherence pin: the three pre-lift consumers in
838        // `tatara-reconciler::ssapply` stamped THREE distinct slot
839        // slugs (`"resource"` / `"metadata"` / `"annotations"`), and
840        // the wrap-shape MUST honor each one verbatim as the leading
841        // slot in the `Display` output. A regression that hard-coded
842        // one slug (say `"resource"`) across every callsite would
843        // pass the first pin above and fail HERE — the three
844        // downstream error-stream greps operators run to bisect a
845        // "which SSA-time mutation faulted" alert would ALL collapse
846        // to the same slug.
847        for slot in ["resource", "metadata", "annotations"] {
848            let mut v = Value::Null;
849            let err = v.as_object_mut_or(slot).unwrap_err();
850            assert_eq!(format!("{err}"), format!("{slot} is not an object"));
851        }
852    }
853
854    #[test]
855    fn as_object_mut_or_object_arm_matches_inherent_as_object_mut_bytewise() {
856        // Cross-substrate coherence pin: on the Ok arm the trait
857        // method MUST return the SAME `&mut Map` the inherent
858        // `serde_json::Value::as_object_mut` would — no diverging
859        // view, no clone, no key-order reshape. A regression that
860        // introduced a normalization pass here (sorting keys,
861        // stripping a null-valued entry, coercing a nested string
862        // to a JSON scalar) would surface as silent per-consumer
863        // schema drift at the SSA-time mutation — an ownerReferences
864        // append that no longer landed in the same slot the apiserver
865        // reads, an annotations insert whose key ordering diverged
866        // from kubectl's canonical form.
867        let mut via_trait = json!({ "key": "value", "nested": { "inner": 1 } });
868        let mut via_inherent = via_trait.clone();
869        assert_eq!(
870            via_trait
871                .as_object_mut_or("resource")
872                .expect("Value::Object")
873                .clone(),
874            via_inherent.as_object_mut().expect("Value::Object").clone(),
875        );
876    }
877
878    // ─── JsonMapStrExt::insert_str substrate pins ─────────────────
879    //
880    // Fail-before-pass-after granularity: the `JsonMapStrExt::insert_str`
881    // trait method did not exist before this commit, so each test below
882    // fails to compile pre-lift. Post-lift they collectively pin the
883    // string-slot write shape at ONE substrate owner — a regression that
884    // dropped the `Value::String` wrap (silently coercing to a bare
885    // `Value::from(&str)` — byte-identical in the `Object` arm today but
886    // divergent for any future non-`&str` numeric caller who reached for
887    // `insert_str(k, n.to_string())`), swapped the key + value slot
888    // orientation, or drifted the return semantics from the inherent
889    // `Map::insert` (which returns the previous value on overwrite —
890    // load-bearing at any future caller that inspects the return) would
891    // surface HERE rather than as silent per-emit skew across the
892    // thirteen pre-lift `ssapply` + `render` + `edges` consumers.
893
894    #[test]
895    fn insert_str_new_key_returns_none_and_stamps_value_string() {
896        // New-key arm: matches inherent `Map::insert` return
897        // semantics — `None` for a fresh key — and stamps a
898        // `Value::String` (NOT `Value::from(&str)`, though they're
899        // byte-identical today) at the slot.
900        let mut m = Map::new();
901        let prev = m.insert_str("key", "value");
902        assert!(prev.is_none(), "new key returns None");
903        assert_eq!(m.get("key"), Some(&Value::String("value".to_string())));
904        assert!(matches!(m.get("key"), Some(Value::String(_))));
905    }
906
907    #[test]
908    fn insert_str_overwrite_returns_prior_value_and_stamps_new() {
909        // Overwrite arm: matches inherent `Map::insert` return
910        // semantics — `Some(prev)` on overwrite. Load-bearing for
911        // any future consumer that inspects the return to detect a
912        // slot collision (a fleet-wide sweep that flagged a
913        // duplicate SSA-time annotation stamp, for example).
914        let mut m = Map::new();
915        m.insert_str("key", "old");
916        let prev = m.insert_str("key", "new");
917        assert_eq!(prev, Some(Value::String("old".to_string())));
918        assert_eq!(m.get("key"), Some(&Value::String("new".to_string())));
919    }
920
921    #[test]
922    fn insert_str_accepts_str_and_owned_string_at_both_slots() {
923        // Composability pin: both slots MUST accept `&str` and
924        // `String` interchangeably — the pre-lift callsite inventory
925        // mixes both (SSA-time `annotations::PID` static + a
926        // `pid.to_string()` runtime String at the value slot;
927        // `spec.insert("interval".into(), Value::String("1m".into()))`
928        // with two `&str` slots). A regression that constrained
929        // either slot to one shape would break the callsite parity
930        // that motivated this substrate primitive.
931        let mut m1 = Map::new();
932        m1.insert_str("a", "b");
933        let mut m2 = Map::new();
934        m2.insert_str(String::from("a"), String::from("b"));
935        let mut m3 = Map::new();
936        m3.insert_str("a", String::from("b"));
937        let mut m4 = Map::new();
938        m4.insert_str(String::from("a"), "b");
939        assert_eq!(m1, m2);
940        assert_eq!(m2, m3);
941        assert_eq!(m3, m4);
942    }
943
944    #[test]
945    fn insert_str_matches_pre_lift_hand_authored_shape_bytewise() {
946        // Byte-shape parity pin: `insert_str(k, v)` MUST emit the
947        // SAME `Map` entry the pre-lift hand-authored `.insert(
948        // <k>.into(), Value::String(<v>.into()))` chain produced.
949        // Sweeps the four (str × String) × (str × String) key/value
950        // shape quadrants so a regression at the primitive that
951        // broke the byte identity with the pre-lift shape at ONE
952        // quadrant surfaces here rather than as a subtle per-emit
953        // divergence at that quadrant.
954        for (k_str, v_str) in [("a", "b"), ("x", ""), ("", "y"), ("", "")] {
955            // (str, str) quadrant
956            let mut via_primitive = Map::new();
957            via_primitive.insert_str(k_str, v_str);
958            let mut via_pre_lift = Map::new();
959            via_pre_lift.insert(k_str.into(), Value::String(v_str.into()));
960            assert_eq!(via_primitive, via_pre_lift);
961
962            // (String, String) quadrant
963            let mut via_primitive = Map::new();
964            via_primitive.insert_str(String::from(k_str), String::from(v_str));
965            let mut via_pre_lift = Map::new();
966            via_pre_lift.insert(String::from(k_str), Value::String(String::from(v_str)));
967            assert_eq!(via_primitive, via_pre_lift);
968        }
969    }
970
971    #[test]
972    fn insert_str_empty_value_stamps_empty_string_not_null() {
973        // Semantic pin: an empty value slot MUST stamp
974        // `Value::String("")`, NEVER `Value::Null`. Load-bearing at
975        // any callsite that stamps a placeholder empty-string
976        // annotation (say a `content_hash` slot pre-derive) where a
977        // `Null` slot would fail-loud at the K8s apiserver's
978        // annotation-value type check.
979        let mut m = Map::new();
980        m.insert_str("empty", "");
981        assert_eq!(m.get("empty"), Some(&Value::String(String::new())));
982        assert!(!matches!(m.get("empty"), Some(Value::Null)));
983    }
984
985    // ─── JsonMapObjectEntryExt::object_slot_mut_or substrate pins ─────
986    //
987    // Fail-before-pass-after granularity: the
988    // `JsonMapObjectEntryExt::object_slot_mut_or` trait method did not
989    // exist before this commit, so each test below fails to compile
990    // pre-lift. Post-lift they collectively pin the compound
991    // seed-then-guard shape at ONE substrate owner — a regression that
992    // dropped the seed step (leaving an absent slot to fall through the
993    // guard as `None → Err`), skipped the guard step (silently returning
994    // an `&mut Value` when the existing slot is a non-object variant),
995    // drifted the entry-key slot vs. the guard-error slot (a copy-paste
996    // typo that stamped `"metadata"` into the entry and `"metadatas"`
997    // into the guard error message), or drifted the empty-seed shape
998    // (a `Value::Null` fallback where `Value::Object(Map::new())` is
999    // load-bearing at the downstream `.entry(...).or_insert_with(...)`
1000    // / `.insert(...)` mutation) would surface HERE rather than as
1001    // silent per-emit skew across the two pre-lift `ssapply.rs`
1002    // consumers.
1003
1004    #[test]
1005    fn object_slot_mut_or_absent_slot_seeds_empty_object_and_returns_it() {
1006        // Absent-slot arm: the pre-lift `.entry(<slot>).or_insert_with
1007        // (|| Value::Object(Default::default()))` step MUST seed the
1008        // slot with an EMPTY `Value::Object` when the slot is not
1009        // present in the parent map. The returned handle is the fresh
1010        // empty map, MUTABLY, so a downstream `.insert(...)` writes
1011        // land in the parent map's `<slot>` object post-return.
1012        let mut parent = Map::new();
1013        {
1014            let child = parent
1015                .object_slot_mut_or("metadata")
1016                .expect("absent slot seeds an object");
1017            assert!(child.is_empty(), "fresh-seeded slot is an empty object");
1018            child.insert("name".into(), Value::String("demo".into()));
1019        }
1020        // The write landed in the parent map's metadata slot.
1021        assert_eq!(parent["metadata"]["name"], "demo");
1022        assert!(matches!(parent.get("metadata"), Some(Value::Object(_))));
1023    }
1024
1025    #[test]
1026    fn object_slot_mut_or_present_object_slot_returns_existing_interior_mutably() {
1027        // Present-object-slot arm: when the slot is already populated
1028        // with a `Value::Object`, the primitive MUST return the
1029        // EXISTING map interior mutably — no synthesis, no reshape, no
1030        // key-order rewrite. The downstream `.insert(...)` writes MUST
1031        // merge into the pre-existing keys rather than replace them.
1032        let mut parent = Map::new();
1033        parent.insert(
1034            "metadata".into(),
1035            serde_json::json!({ "existing_key": "existing_value" }),
1036        );
1037        {
1038            let child = parent
1039                .object_slot_mut_or("metadata")
1040                .expect("present-object slot returns Ok");
1041            assert_eq!(
1042                child.get("existing_key"),
1043                Some(&Value::String("existing_value".into()))
1044            );
1045            child.insert("new_key".into(), Value::String("new_value".into()));
1046        }
1047        assert_eq!(parent["metadata"]["existing_key"], "existing_value");
1048        assert_eq!(parent["metadata"]["new_key"], "new_value");
1049    }
1050
1051    #[test]
1052    fn object_slot_mut_or_present_non_object_slot_errors_with_pre_lift_display() {
1053        // Fail-loud arm: when the slot is present but holds a non-
1054        // object variant (a `Value::String` from a hand-authored
1055        // YAML manifest where `metadata: "malformed"` slipped past
1056        // kubectl's schema check), the primitive MUST fail with a
1057        // `Display` byte-identical to the pre-lift
1058        // `.as_object_mut_or(<slot>)?` guard — the sibling
1059        // [`ValueObjectExt::as_object_mut_or`] guard's wire format.
1060        // A regression that special-cased this arm (overwriting the
1061        // slot with a fresh empty object, silently coercing) would
1062        // silently swallow the operator's authoring error at the
1063        // SSA-time re-injection step.
1064        let mut parent = Map::new();
1065        parent.insert("metadata".into(), Value::String("malformed".into()));
1066        let err = parent.object_slot_mut_or("metadata").unwrap_err();
1067        assert_eq!(format!("{err}"), "metadata is not an object");
1068    }
1069
1070    #[test]
1071    fn object_slot_mut_or_threads_the_slot_slug_verbatim_across_both_pre_lift_labels() {
1072        // Cross-slot coherence pin: the TWO pre-lift consumers in
1073        // `tatara-reconciler::ssapply` stamped TWO distinct slot slugs
1074        // (`"metadata"` at the resource root, `"annotations"` at the
1075        // metadata child), and the wrap-shape MUST honor each one
1076        // verbatim as the leading slot in the `Display` output. A
1077        // regression that hard-coded one slug across every callsite
1078        // would pass the fail-loud pin above (on the `"metadata"` slug)
1079        // and fail HERE — the two downstream error-stream greps
1080        // operators run to bisect a "which SSA-time slot mutation
1081        // faulted" alert would ALL collapse to the same slug, hiding
1082        // whether the fault was at the resource-root object walk or
1083        // the metadata-child annotations walk.
1084        for slot in ["metadata", "annotations"] {
1085            let mut parent = Map::new();
1086            parent.insert(slot.into(), Value::Null);
1087            let err = parent.object_slot_mut_or(slot).unwrap_err();
1088            assert_eq!(format!("{err}"), format!("{slot} is not an object"));
1089        }
1090    }
1091
1092    #[test]
1093    fn object_slot_mut_or_present_empty_object_returns_existing_reference_not_synthesized() {
1094        // Precedence pin: a present slot holding an EMPTY
1095        // `Value::Object` MUST return the pre-existing empty map
1096        // interior — not a freshly-synthesized replacement. The
1097        // pre-lift `.entry(<slot>).or_insert_with(||...)` step's
1098        // short-circuit on the present-slot arm skips the closure
1099        // entirely; a regression that always evaluated the closure
1100        // (unconditionally overwriting an existing empty-object slot
1101        // with a fresh empty object) would type-check silently at
1102        // every callsite AND write byte-identical JSON at the empty-
1103        // slot corner, but it would break a hypothetical future
1104        // consumer that reached the primitive on a map whose slot
1105        // was seeded upstream with metadata (a caller intending to
1106        // preserve any keys the parent-composer already dropped in).
1107        let mut parent = Map::new();
1108        parent.insert("metadata".into(), Value::Object(Map::new()));
1109        let addr_before = parent.get("metadata").unwrap() as *const Value;
1110        {
1111            let _child = parent.object_slot_mut_or("metadata").unwrap();
1112        }
1113        let addr_after = parent.get("metadata").unwrap() as *const Value;
1114        assert_eq!(
1115            addr_before, addr_after,
1116            "present empty-object slot must return the pre-existing reference, not a fresh synthesis",
1117        );
1118    }
1119
1120    #[test]
1121    fn object_slot_mut_or_matches_pre_lift_hand_authored_compound_shape_bytewise() {
1122        // Byte-shape parity pin: `object_slot_mut_or(<slot>)?` MUST
1123        // produce the SAME `&mut Map` (and, on the non-object arm, the
1124        // SAME `Display`-shaped error) the pre-lift 3-line `.entry
1125        // (<slot>).or_insert_with(|| Value::Object(Default::default()))
1126        // .as_object_mut_or(<slot>)?` chain produced. Sweeps the three
1127        // pre-lift-reachable input corners (absent slot / present
1128        // object / present non-object) so a regression at the primitive
1129        // that broke byte identity with the pre-lift chain at ONE
1130        // corner surfaces here rather than as a subtle per-emit
1131        // divergence.
1132        for slot in ["metadata", "annotations"] {
1133            // (1) Absent-slot corner: both routes seed empty-object at
1134            //     the slot AND return the same empty map interior.
1135            let mut via_primitive = Map::new();
1136            let mut via_pre_lift = Map::new();
1137            {
1138                let _ = via_primitive.object_slot_mut_or(slot).unwrap();
1139                let _ = via_pre_lift
1140                    .entry(slot.to_string())
1141                    .or_insert_with(|| Value::Object(Map::new()))
1142                    .as_object_mut_or(slot)
1143                    .unwrap();
1144            }
1145            assert_eq!(via_primitive, via_pre_lift);
1146
1147            // (2) Present-object corner: both routes read back the
1148            //     same pre-populated interior mutably.
1149            let mut via_primitive = Map::new();
1150            via_primitive.insert(slot.into(), serde_json::json!({ "k": "v" }));
1151            let mut via_pre_lift = via_primitive.clone();
1152            {
1153                let a = via_primitive.object_slot_mut_or(slot).unwrap();
1154                let b = via_pre_lift
1155                    .entry(slot.to_string())
1156                    .or_insert_with(|| Value::Object(Map::new()))
1157                    .as_object_mut_or(slot)
1158                    .unwrap();
1159                assert_eq!(a, b);
1160            }
1161
1162            // (3) Present-non-object corner: both routes fail loud
1163            //     with the same wire-format Display shape.
1164            let mut via_primitive = Map::new();
1165            via_primitive.insert(slot.into(), Value::Bool(true));
1166            let mut via_pre_lift = via_primitive.clone();
1167            let err_primitive = via_primitive.object_slot_mut_or(slot).unwrap_err();
1168            let err_pre_lift = via_pre_lift
1169                .entry(slot.to_string())
1170                .or_insert_with(|| Value::Object(Map::new()))
1171                .as_object_mut_or(slot)
1172                .unwrap_err();
1173            assert_eq!(format!("{err_primitive}"), format!("{err_pre_lift}"));
1174        }
1175    }
1176
1177    // ─── ValueGetExt::get_i64 substrate pins ─────────────────────────
1178    //
1179    // Fail-before-pass-after granularity: the `ValueGetExt::get_i64`
1180    // trait method did not exist before this commit, so each test below
1181    // fails to compile pre-lift. Post-lift they collectively pin the
1182    // paired READ-shape at ONE substrate owner — a regression that
1183    // narrowed the projection to `as_u64` (silently losing every
1184    // negative counter K8s fixtures can carry for a JSON authoring
1185    // bug), swapped the slot lookup to `.pointer(<key>)` (losing the
1186    // direct-child semantics), promoted a present-but-non-integer
1187    // corner to `Some(0)` (silently paving over a malformed status
1188    // blob), or drifted the receiver-non-object arm from `None → Some(default)`
1189    // (silently synthesising a zero counter on a null status blob)
1190    // surfaces HERE rather than as silent operator-facing skew across
1191    // the three `boundary.rs::fetch_job_status` pre-lift consumers
1192    // whose JobStatusView row initialised at `Default::default()` and
1193    // conditionally overwrote each field on `Some(i64)`.
1194
1195    #[test]
1196    fn get_i64_present_integer_slot_returns_the_value() {
1197        // Primary Ok-arm invariant: a `Value::Number(i)` present at the
1198        // slot projects to `Some(i)`. Sweeps the three representative
1199        // counters every pre-lift `JobStatusView` field carried (a
1200        // completed Job's `succeeded=1`, a failed Job's `failed=3`, a
1201        // freshly-scheduled Job's `active=5`) so a regression at ONE
1202        // counter axis surfaces here rather than at the downstream
1203        // diagnostic.
1204        let status = json!({ "succeeded": 1, "failed": 3, "active": 5 });
1205        assert_eq!(status.get_i64("succeeded"), Some(1));
1206        assert_eq!(status.get_i64("failed"), Some(3));
1207        assert_eq!(status.get_i64("active"), Some(5));
1208    }
1209
1210    #[test]
1211    fn get_i64_absent_slot_returns_none() {
1212        // Absent-slot corner: a fresh `batch/v1::Job` before its
1213        // controller has stamped any counter into `status` (the JSON
1214        // is `{}` or missing the counter key). Every pre-lift consumer
1215        // routed this corner through the `if let Some(...)` guard so
1216        // the `JobStatusView` field kept its `Default::default()` `0`
1217        // seed. A regression that returned `Some(0)` on the absent
1218        // corner would collapse the "not yet reported" ↔ "reported
1219        // zero" distinction the K8s status protocol keeps.
1220        let status = json!({});
1221        assert_eq!(status.get_i64("succeeded"), None);
1222        assert_eq!(status.get_i64("any_missing_key"), None);
1223    }
1224
1225    #[test]
1226    fn get_i64_present_but_non_integer_slot_returns_none() {
1227        // Present-but-non-integer corner: a `Value::String`, a
1228        // `Value::Bool`, a `Value::Object`, or a `Value::Array` at the
1229        // slot ALL fall through to `None` — matches the pre-lift
1230        // `.and_then(|v| v.as_i64())` chain exactly. A regression that
1231        // promoted a `Value::String("1")` to `Some(1)` (adding a
1232        // parse-string fallback) would silently accept a malformed
1233        // status blob whose author stringified a counter.
1234        let status = json!({
1235            "stringy": "1",
1236            "boolean": true,
1237            "object": {},
1238            "array": [],
1239            "null_valued": null,
1240        });
1241        assert_eq!(status.get_i64("stringy"), None);
1242        assert_eq!(status.get_i64("boolean"), None);
1243        assert_eq!(status.get_i64("object"), None);
1244        assert_eq!(status.get_i64("array"), None);
1245        assert_eq!(status.get_i64("null_valued"), None);
1246    }
1247
1248    #[test]
1249    fn get_i64_negative_counter_survives_the_projection() {
1250        // Negative-integer corner: `as_i64` accepts negatives; `as_u64`
1251        // does not. A regression that narrowed the projection to
1252        // `as_u64` under a mistaken "K8s counters are always non-
1253        // negative" refactor would silently drop every negative
1254        // counter a JSON authoring bug could stamp — hiding the bug
1255        // rather than surfacing it as a counter the diagnostic reports
1256        // verbatim.
1257        let status = json!({ "n": -1 });
1258        assert_eq!(status.get_i64("n"), Some(-1));
1259    }
1260
1261    #[test]
1262    fn get_i64_non_object_receiver_returns_none_verbatim() {
1263        // Non-object receiver corner: a caller who reached this
1264        // primitive on a `Value::Null` / `Value::Bool` / `Value::Array`
1265        // handle (a malformed fetch response, an upstream default-value
1266        // fallback) MUST get `None` back rather than a panic or a
1267        // synthesized `Some(default)`. Matches the pre-lift chain's
1268        // behaviour: `Value::get` on a non-object receiver returns
1269        // `None`, `and_then` short-circuits.
1270        assert_eq!(Value::Null.get_i64("any"), None);
1271        assert_eq!(Value::Bool(true).get_i64("any"), None);
1272        assert_eq!(json!([1, 2, 3]).get_i64("any"), None);
1273        assert_eq!(json!("scalar").get_i64("any"), None);
1274    }
1275
1276    #[test]
1277    fn get_i64_matches_pre_lift_hand_authored_chain_shape() {
1278        // Byte-shape parity pin: `<value>.get_i64(<key>)` MUST return
1279        // the SAME `Option<i64>` the pre-lift hand-authored
1280        // `.get(<key>).and_then(|v| v.as_i64())` chain produced.
1281        // Sweeps the six pre-lift-reachable input corners (the three
1282        // "value present" + three "value absent/malformed" arms every
1283        // fetch_job_status callsite reached) so a regression at the
1284        // primitive that broke byte identity with the pre-lift chain at
1285        // ONE corner surfaces here rather than as a per-counter
1286        // divergence at the fetched-Job projection.
1287        let status = json!({
1288            "succeeded": 2,
1289            "failed": 0,
1290            "active": 7,
1291            "stringy": "1",
1292            "null_valued": null,
1293        });
1294        for key in [
1295            "succeeded",
1296            "failed",
1297            "active",
1298            "stringy",
1299            "null_valued",
1300            "missing",
1301        ] {
1302            let via_primitive = status.get_i64(key);
1303            let via_pre_lift = status.get(key).and_then(|v| v.as_i64());
1304            assert_eq!(
1305                via_primitive, via_pre_lift,
1306                "corner `{key}` must round-trip through both shapes",
1307            );
1308        }
1309    }
1310
1311    #[test]
1312    fn get_i64_composes_with_unwrap_or_default_at_default_seed_shape() {
1313        // Downstream composition pin: the canonical caller shape
1314        // post-lift is `<status>.get_i64(<key>).unwrap_or_default()` —
1315        // matches the pre-lift `JobStatusView::default()` seed +
1316        // conditional `if let Some(n)` write pattern. A regression that
1317        // reshaped the return form (an `i64` bare default, a
1318        // `Result<i64, _>` fallible arm) would break this composition.
1319        let status = json!({ "succeeded": 4 });
1320        // Absent slot composes to the type default (0 for i64).
1321        assert_eq!(status.get_i64("missing").unwrap_or_default(), 0_i64);
1322        // Present slot composes to the projected counter.
1323        assert_eq!(status.get_i64("succeeded").unwrap_or_default(), 4_i64);
1324    }
1325
1326    // ─── ValueGetExt::get_str substrate pins ─────────────────────────
1327    //
1328    // Fail-before-pass-after granularity: the `ValueGetExt::get_str`
1329    // trait method did not exist before this commit, so each test below
1330    // fails to compile pre-lift. Post-lift they collectively pin the
1331    // paired READ-shape at ONE substrate owner — a regression that
1332    // narrowed the projection to the wrong variant (accepting
1333    // `Value::Number`-stringified slots via a fallback, or accepting
1334    // `Value::Null` as `Some("")`), swapped the slot lookup to
1335    // `.pointer(<key>)` (losing the direct-child semantics), promoted
1336    // an absent slot to `Some("")` (silently paving over a missing
1337    // required slot), or drifted the receiver-non-object arm from
1338    // `None` (silently synthesising an empty string on a null status
1339    // blob) surfaces HERE rather than as silent operator-facing skew
1340    // across the SEVEN pre-lift consumers (`status::from_json`'s four
1341    // rendered-resource coordinate reads + `ssapply::ready_condition_value`'s
1342    // three K8s Condition slot reads).
1343
1344    #[test]
1345    fn get_str_present_string_slot_returns_the_slice() {
1346        // Primary Ok-arm invariant: a `Value::String(s)` present at the
1347        // slot projects to `Some(s.as_str())`. Sweeps the four
1348        // representative slots the pre-lift `RenderedResourceCoords::
1349        // from_json` consumer walked (`apiVersion`, `kind`,
1350        // `metadata.name`, `metadata.namespace`) so a regression at
1351        // ONE axis surfaces here rather than at the downstream
1352        // typed row's coordinate.
1353        let manifest = json!({
1354            "apiVersion": "helm.toolkit.fluxcd.io/v2",
1355            "kind": "HelmRelease",
1356            "name": "demo-app",
1357            "namespace": "demo",
1358        });
1359        assert_eq!(
1360            manifest.get_str("apiVersion"),
1361            Some("helm.toolkit.fluxcd.io/v2"),
1362        );
1363        assert_eq!(manifest.get_str("kind"), Some("HelmRelease"));
1364        assert_eq!(manifest.get_str("name"), Some("demo-app"));
1365        assert_eq!(manifest.get_str("namespace"), Some("demo"));
1366    }
1367
1368    #[test]
1369    fn get_str_absent_slot_returns_none() {
1370        // Absent-slot corner: a rendered manifest whose author forgot
1371        // the `apiVersion` slot (a common authoring bug) MUST return
1372        // `None` so `RenderedResourceCoords::from_json` fails loud
1373        // rather than silently synthesising an empty apiVersion. A
1374        // regression that returned `Some("")` on the absent corner
1375        // would collapse the "not authored" ↔ "authored empty"
1376        // distinction the fail-loud gate depends on.
1377        let manifest = json!({ "kind": "HelmRelease" });
1378        assert_eq!(manifest.get_str("apiVersion"), None);
1379        assert_eq!(manifest.get_str("any_missing_key"), None);
1380    }
1381
1382    #[test]
1383    fn get_str_present_but_non_string_slot_returns_none() {
1384        // Present-but-non-string corner: a `Value::Number`,
1385        // `Value::Bool`, `Value::Object`, `Value::Array`, or
1386        // `Value::Null` at the slot ALL fall through to `None` —
1387        // matches the pre-lift `.and_then(|v| v.as_str())` chain
1388        // exactly. A regression that stringified a `Value::Number`
1389        // (adding a `to_string()` fallback) would silently accept a
1390        // malformed manifest whose author numeric-typed a
1391        // conventionally-string slot.
1392        let manifest = json!({
1393            "numeric": 1,
1394            "boolean": true,
1395            "object": {},
1396            "array": [],
1397            "null_valued": null,
1398        });
1399        assert_eq!(manifest.get_str("numeric"), None);
1400        assert_eq!(manifest.get_str("boolean"), None);
1401        assert_eq!(manifest.get_str("object"), None);
1402        assert_eq!(manifest.get_str("array"), None);
1403        assert_eq!(manifest.get_str("null_valued"), None);
1404    }
1405
1406    #[test]
1407    fn get_str_empty_string_slot_survives_the_projection() {
1408        // Empty-string corner: a `Value::String("")` present at the
1409        // slot MUST project to `Some("")` — matches the pre-lift
1410        // `.and_then(|v| v.as_str())` chain exactly, keeping the
1411        // "authored empty" arm distinct from the "not authored" arm
1412        // upstream. A regression that promoted `Some("")` to `None`
1413        // under a "reject empty strings" refactor would silently
1414        // collapse the two arms and turn a valid empty `metadata.
1415        // namespace` (a cluster-scoped resource) into a fail-loud
1416        // error at the required-slot gates.
1417        let manifest = json!({ "namespace": "" });
1418        assert_eq!(manifest.get_str("namespace"), Some(""));
1419    }
1420
1421    #[test]
1422    fn get_str_non_object_receiver_returns_none_verbatim() {
1423        // Non-object receiver corner: a caller who reached this
1424        // primitive on a `Value::Null` / `Value::Bool` / `Value::Array`
1425        // handle (a malformed fetch response, an upstream default-value
1426        // fallback, a `serde_json::Value::Null` metadata slot chained
1427        // through `.and_then`) MUST get `None` back rather than a
1428        // panic or a synthesized `Some("")`. Matches the pre-lift
1429        // chain's behaviour: `Value::get` on a non-object receiver
1430        // returns `None`, `and_then` short-circuits.
1431        assert_eq!(Value::Null.get_str("any"), None);
1432        assert_eq!(Value::Bool(true).get_str("any"), None);
1433        assert_eq!(json!([1, 2, 3]).get_str("any"), None);
1434        assert_eq!(json!("scalar").get_str("any"), None);
1435    }
1436
1437    #[test]
1438    fn get_str_matches_pre_lift_hand_authored_chain_shape() {
1439        // Byte-shape parity pin: `<value>.get_str(<key>)` MUST return
1440        // the SAME `Option<&str>` the pre-lift hand-authored
1441        // `.get(<key>).and_then(|v| v.as_str())` chain produced.
1442        // Sweeps every pre-lift-reachable input corner (three
1443        // "value present" + three "value absent/malformed" arms every
1444        // status.rs / ssapply.rs callsite reached) so a regression at
1445        // the primitive that broke byte identity with the pre-lift
1446        // chain at ONE corner surfaces here rather than as a
1447        // per-slot divergence downstream.
1448        let manifest = json!({
1449            "apiVersion": "v1",
1450            "kind": "ConfigMap",
1451            "type": "Ready",
1452            "numeric": 1,
1453            "null_valued": null,
1454        });
1455        for key in [
1456            "apiVersion",
1457            "kind",
1458            "type",
1459            "numeric",
1460            "null_valued",
1461            "missing",
1462        ] {
1463            let via_primitive = manifest.get_str(key);
1464            let via_pre_lift = manifest.get(key).and_then(|v| v.as_str());
1465            assert_eq!(
1466                via_primitive, via_pre_lift,
1467                "corner `{key}` must round-trip through both shapes",
1468            );
1469        }
1470    }
1471
1472    #[test]
1473    fn get_str_composes_with_ok_or_else_at_from_json_shape() {
1474        // Downstream composition pin: the canonical caller shape at
1475        // `RenderedResourceCoords::from_json` is
1476        // `<manifest>.get_str(<key>).ok_or_else(|| anyhow!("rendered
1477        // resource missing X"))?.to_string()`. A regression that
1478        // reshaped the return form (an `&str` bare default, a
1479        // `Result<&str, _>` fallible arm) would break this
1480        // composition. Additionally sweeps the peer
1481        // `.map(String::from)` / `.map(str::to_string)` optional-slot
1482        // arm the `namespace` slot uses.
1483        let manifest = json!({ "apiVersion": "v1" });
1484        let ok_arm: String = manifest
1485            .get_str("apiVersion")
1486            .ok_or_else(|| anyhow::anyhow!("missing"))
1487            .unwrap()
1488            .to_string();
1489        assert_eq!(ok_arm, "v1");
1490        let err_arm = manifest
1491            .get_str("kind")
1492            .ok_or_else(|| anyhow::anyhow!("rendered resource missing kind"))
1493            .unwrap_err();
1494        assert_eq!(format!("{err_arm}"), "rendered resource missing kind");
1495        let opt_present: Option<String> = manifest.get_str("apiVersion").map(str::to_string);
1496        assert_eq!(opt_present.as_deref(), Some("v1"));
1497        let opt_absent: Option<String> = manifest.get_str("kind").map(String::from);
1498        assert!(opt_absent.is_none());
1499    }
1500
1501    #[test]
1502    fn get_str_return_lifetime_borrows_receiver_not_owned() {
1503        // Return-lifetime pin: the `&str` MUST borrow the receiver's
1504        // buffer rather than a fresh owned `String`. A regression that
1505        // reshaped the return to `Option<String>` (adding a
1506        // `to_string()` inside the primitive) would inflate every
1507        // callsite's allocation count and break `metadata.and_then(|m|
1508        // m.get_str("name"))`'s per-lookup zero-alloc guarantee. Bind
1509        // the invariant structurally: the borrow reaches back through
1510        // the receiver.
1511        let manifest = json!({ "apiVersion": "helm.toolkit.fluxcd.io/v2" });
1512        let s: &str = manifest.get_str("apiVersion").unwrap();
1513        let raw: &str = manifest.get("apiVersion").and_then(|v| v.as_str()).unwrap();
1514        assert!(std::ptr::eq(s.as_ptr(), raw.as_ptr()));
1515    }
1516
1517    #[test]
1518    fn get_str_axis_family_reaches_i64_and_str_through_one_trait_import() {
1519        // Axis-family pin: a caller who imports `ValueGetExt` reaches
1520        // BOTH the string axis (`get_str`) and the integer axis
1521        // (`get_i64`) through the SAME trait handle. A regression that
1522        // opened a peer `ValueGetStrExt` (or a peer trait per axis)
1523        // would break this — the caller would have to import each
1524        // trait separately and a partial import would silently miss
1525        // one axis at method-resolution time.
1526        //
1527        // Structurally: a bound `T: ValueGetExt` reaches both methods.
1528        fn probe<T: ValueGetExt>(t: &T) -> (Option<i64>, Option<&str>) {
1529            (t.get_i64("n"), t.get_str("s"))
1530        }
1531        let mixed = json!({ "n": 7, "s": "hello" });
1532        let (n, s) = probe(&mixed);
1533        assert_eq!(n, Some(7));
1534        assert_eq!(s, Some("hello"));
1535    }
1536
1537    // ─── ValueGetExt::get_array substrate pins ───────────────────────
1538    //
1539    // Fail-before-pass-after granularity: the `ValueGetExt::get_array`
1540    // trait method did not exist before this commit, so each test below
1541    // fails to compile pre-lift. Post-lift they collectively pin the
1542    // paired READ-shape at ONE substrate owner — a regression that
1543    // narrowed the projection to the wrong variant (accepting an
1544    // object slot via a `.values().collect()` synthesis, promoting an
1545    // absent slot to `Some(&Vec::new())`), swapped the slot lookup to
1546    // `.pointer(<key>)` (losing the direct-child semantics), or
1547    // drifted the receiver-non-object arm from `None` (silently
1548    // synthesising an empty array on a null status blob) surfaces
1549    // HERE rather than as silent operator-facing skew across the two
1550    // pre-lift consumers (`ssapply::ready_condition_value`'s
1551    // `status.conditions` walker + `probe::count_jwks_keys`'s `keys`
1552    // counter).
1553
1554    #[test]
1555    fn get_array_present_array_slot_returns_the_slice() {
1556        // Primary Ok-arm invariant: a `Value::Array` present at the
1557        // slot projects to `Some(&Vec::new())`-shaped borrow. Sweeps
1558        // the two representative shapes the pre-lift consumers walked
1559        // (a K8s `status.conditions` array of Condition objects on the
1560        // reconciler side; a JWKS `keys` array of key objects on the
1561        // probe side).
1562        let status = json!({
1563            "conditions": [
1564                { "type": "Ready", "status": "True" },
1565                { "type": "Progressing", "status": "False" },
1566            ],
1567        });
1568        let via = status.get_array("conditions").expect("Value::Array");
1569        assert_eq!(via.len(), 2);
1570        assert_eq!(via[0]["type"], "Ready");
1571
1572        let jwks = json!({
1573            "keys": [
1574                { "kty": "RSA", "kid": "1" },
1575                { "kty": "RSA", "kid": "2" },
1576                { "kty": "EC",  "kid": "3" },
1577            ],
1578        });
1579        assert_eq!(
1580            jwks.get_array("keys").map(Vec::len),
1581            Some(3),
1582            "probe count_jwks_keys composition must reach the same tail as pre-lift",
1583        );
1584    }
1585
1586    #[test]
1587    fn get_array_absent_slot_returns_none() {
1588        // Absent-slot corner: a fresh K8s status blob whose controller
1589        // has not stamped `conditions` yet (the `data.get("status")`
1590        // walker yields an object without the slot) MUST return
1591        // `None` so the caller's `let Some(...) = ... else { return
1592        // ReadyState::Unknown }` short-circuit fires. A regression that
1593        // returned `Some(&Vec::new())` on the absent corner would
1594        // silently drive the caller into an empty for-loop and skip
1595        // the fail-safe.
1596        let status = json!({});
1597        assert_eq!(status.get_array("conditions"), None);
1598        assert_eq!(status.get_array("any_missing_key"), None);
1599    }
1600
1601    #[test]
1602    fn get_array_present_but_non_array_slot_returns_none() {
1603        // Present-but-non-array corner: a `Value::String`,
1604        // `Value::Number`, `Value::Bool`, `Value::Object`, or
1605        // `Value::Null` at the slot ALL fall through to `None` —
1606        // matches the pre-lift `.and_then(|v| v.as_array())` chain
1607        // exactly. A regression that wrapped a scalar in a single-
1608        // element array under a "tolerant" refactor would silently
1609        // accept a malformed status blob whose author collapsed the
1610        // conditions array to a single scalar.
1611        let status = json!({
1612            "stringy": "ready",
1613            "numeric": 1,
1614            "boolean": true,
1615            "object": { "nested": true },
1616            "null_valued": null,
1617        });
1618        assert_eq!(status.get_array("stringy"), None);
1619        assert_eq!(status.get_array("numeric"), None);
1620        assert_eq!(status.get_array("boolean"), None);
1621        assert_eq!(status.get_array("object"), None);
1622        assert_eq!(status.get_array("null_valued"), None);
1623    }
1624
1625    #[test]
1626    fn get_array_empty_array_slot_survives_the_projection() {
1627        // Empty-array corner: a `Value::Array` with zero elements at
1628        // the slot MUST project to `Some(&Vec::new())` — matches the
1629        // pre-lift chain exactly, keeping the "authored empty" arm
1630        // distinct from the "not authored" arm upstream. The probe
1631        // consumer's `.map(|xs| xs.len() as u64).unwrap_or(0)` tail
1632        // depends on this: an authored-empty JWKS array reports 0
1633        // keys, distinct from a JWKS response missing the `keys` slot
1634        // altogether (which the caller could later choose to log
1635        // differently).
1636        let jwks = json!({ "keys": [] });
1637        let arr = jwks.get_array("keys").expect("Value::Array");
1638        assert!(arr.is_empty());
1639        assert_eq!(jwks.get_array("keys").map(Vec::len), Some(0));
1640    }
1641
1642    #[test]
1643    fn get_array_non_object_receiver_returns_none_verbatim() {
1644        // Non-object receiver corner: a caller who reached this
1645        // primitive on a `Value::Null` / `Value::Bool` / `Value::Array`
1646        // handle (a malformed fetch response, an upstream default-value
1647        // fallback, a `serde_json::Value::Null` intermediate chained
1648        // through `.and_then`) MUST get `None` back rather than a
1649        // panic or a synthesized `Some(&Vec::new())`. Matches the
1650        // pre-lift chain's behaviour: `Value::get` on a non-object
1651        // receiver returns `None`, `and_then` short-circuits.
1652        assert_eq!(Value::Null.get_array("any"), None);
1653        assert_eq!(Value::Bool(true).get_array("any"), None);
1654        assert_eq!(json!([1, 2, 3]).get_array("any"), None);
1655        assert_eq!(json!("scalar").get_array("any"), None);
1656    }
1657
1658    #[test]
1659    fn get_array_matches_pre_lift_hand_authored_chain_shape() {
1660        // Byte-shape parity pin: `<value>.get_array(<key>)` MUST return
1661        // the SAME `Option<&Vec<Value>>` the pre-lift hand-authored
1662        // `.get(<key>).and_then(|v| v.as_array())` chain produced.
1663        // Sweeps every pre-lift-reachable input corner (three
1664        // "value present" + three "value absent/malformed" arms
1665        // covering the two pre-lift consumers) so a regression at the
1666        // primitive that broke byte identity with the pre-lift chain
1667        // at ONE corner surfaces here rather than as a per-slot
1668        // divergence downstream.
1669        let manifest = json!({
1670            "conditions": [{ "type": "Ready" }],
1671            "keys": [{ "kid": "1" }, { "kid": "2" }],
1672            "empty": [],
1673            "stringy": "not-an-array",
1674            "null_valued": null,
1675        });
1676        for key in [
1677            "conditions",
1678            "keys",
1679            "empty",
1680            "stringy",
1681            "null_valued",
1682            "missing",
1683        ] {
1684            let via_primitive = manifest.get_array(key);
1685            let via_pre_lift = manifest.get(key).and_then(|v| v.as_array());
1686            assert_eq!(
1687                via_primitive, via_pre_lift,
1688                "corner `{key}` must round-trip through both shapes",
1689            );
1690        }
1691    }
1692
1693    #[test]
1694    fn get_array_composes_with_len_map_at_probe_count_jwks_keys_shape() {
1695        // Downstream composition pin: the canonical caller shape at
1696        // `probe::count_jwks_keys` is `<body_val>.get_array(<key>).
1697        // map(|xs| xs.len() as u64).unwrap_or(0)` — matches the
1698        // pre-lift `.get(<key>).cloned().and_then(|k| k.as_array().
1699        // map(|xs| xs.len() as u64)).unwrap_or(0)` chain shed of its
1700        // pre-lift `.cloned()` allocation. A regression that reshaped
1701        // the return form (an `Option<Vec<Value>>` owned, a
1702        // `Result<...>` fallible arm) would break this composition
1703        // AND reintroduce the eliminated allocation.
1704        let jwks = json!({ "keys": [{ "kid": "1" }, { "kid": "2" }, { "kid": "3" }] });
1705        let n: u64 = jwks
1706            .get_array("keys")
1707            .map(|xs| xs.len() as u64)
1708            .unwrap_or(0);
1709        assert_eq!(n, 3);
1710        // Missing slot composes to 0 through the same unwrap_or arm.
1711        let empty = json!({});
1712        let z: u64 = empty
1713            .get_array("keys")
1714            .map(|xs| xs.len() as u64)
1715            .unwrap_or(0);
1716        assert_eq!(z, 0);
1717    }
1718
1719    #[test]
1720    fn get_array_composes_with_let_else_short_circuit_at_ready_condition_shape() {
1721        // Downstream composition pin: the canonical caller shape at
1722        // `ssapply::ready_condition_value` is `let Some(conditions) =
1723        // <data>.get("status").and_then(|s| s.get_array("conditions"))
1724        // else { return ReadyState::Unknown; }` — the walker rides
1725        // the `get_array` primitive on the tail of a nested walk. A
1726        // regression that changed the return to `Option<Vec<Value>>`
1727        // owned would break the `for c in conditions` borrow-iterate
1728        // pattern downstream (each `c` borrows through the receiver).
1729        let data = json!({
1730            "status": {
1731                "conditions": [
1732                    { "type": "Ready",       "status": "True" },
1733                    { "type": "Progressing", "status": "False" },
1734                ],
1735            },
1736        });
1737        let conditions = data
1738            .get("status")
1739            .and_then(|s| s.get_array("conditions"))
1740            .expect("nested walk resolves");
1741        assert_eq!(conditions.len(), 2);
1742        // Verifies borrow-through-receiver: iterate without cloning.
1743        let types: Vec<&str> = conditions
1744            .iter()
1745            .filter_map(|c| c.get_str("type"))
1746            .collect();
1747        assert_eq!(types, vec!["Ready", "Progressing"]);
1748    }
1749
1750    #[test]
1751    fn get_array_return_lifetime_borrows_receiver_not_owned() {
1752        // Return-lifetime pin: the `&Vec<Value>` MUST borrow the
1753        // receiver's buffer rather than a fresh owned `Vec`. A
1754        // regression that reshaped the return to `Option<Vec<Value>>`
1755        // (adding a `.clone()` inside the primitive) would inflate
1756        // every callsite's allocation count and — for the
1757        // ssapply.rs caller — reintroduce a per-reconcile clone of
1758        // every K8s Condition on every DynamicObject readiness probe.
1759        // Bind the invariant structurally: the borrow reaches back
1760        // through the receiver.
1761        let manifest = json!({ "keys": [{ "kid": "1" }, { "kid": "2" }] });
1762        let via_primitive: &Vec<Value> = manifest.get_array("keys").unwrap();
1763        let via_raw: &Vec<Value> = manifest.get("keys").and_then(|v| v.as_array()).unwrap();
1764        assert!(std::ptr::eq(via_primitive.as_ptr(), via_raw.as_ptr()));
1765    }
1766
1767    #[test]
1768    fn get_array_axis_family_reaches_i64_str_and_array_through_one_trait_import() {
1769        // Axis-family pin: a caller who imports `ValueGetExt` reaches
1770        // the integer axis (`get_i64`), the string axis (`get_str`),
1771        // AND the array axis (`get_array`) through the SAME trait
1772        // handle. A regression that opened a peer `ValueGetArrayExt`
1773        // (or a peer trait per axis) would break this — the caller
1774        // would have to import each trait separately and a partial
1775        // import would silently miss one axis at method-resolution
1776        // time.
1777        //
1778        // Structurally: a bound `T: ValueGetExt` reaches all three
1779        // methods. This test extends the pre-existing
1780        // `get_str_axis_family_reaches_i64_and_str_through_one_trait_import`
1781        // sibling to cover the new axis; either drops means the
1782        // axis-family invariant no longer holds.
1783        fn probe<T: ValueGetExt>(t: &T) -> (Option<i64>, Option<&str>, Option<&Vec<Value>>) {
1784            (t.get_i64("n"), t.get_str("s"), t.get_array("a"))
1785        }
1786        let mixed = json!({ "n": 7, "s": "hello", "a": [1, 2, 3] });
1787        let (n, s, a) = probe(&mixed);
1788        assert_eq!(n, Some(7));
1789        assert_eq!(s, Some("hello"));
1790        assert_eq!(a.map(Vec::len), Some(3));
1791    }
1792
1793    // ─── ValueGetExt receiver-shape widening — Map impl pins ─────────
1794    //
1795    // Fail-before-pass-after granularity: `impl ValueGetExt for
1796    // Map<String, Value>` did not exist before this commit, so each
1797    // test below fails to compile pre-lift (a bare `Map<String, Value>`
1798    // receiver has no `.get_str(<key>)` inherent method — only the
1799    // upstream `.get(<key>).and_then(Value::as_str)` chain — so the
1800    // callsite fails method resolution). Post-lift they collectively
1801    // pin the widening at ONE substrate owner — a regression that
1802    // dropped the `Map` impl and re-forced every `&Map` receiver into
1803    // a `Value::Object(m.clone())` rewrap detour would surface HERE
1804    // rather than as silent per-emit skew across the 30
1805    // `Map`-receiver pre-lift consumers in `tatara-reconciler::
1806    // {patch,ssapply}` tests.
1807
1808    #[test]
1809    fn map_receiver_reaches_str_i64_and_array_axes_through_the_same_trait() {
1810        // Receiver-parity pin: an `&Map<String, Value>` handle reaches
1811        // the SAME three axes (`get_str`, `get_i64`, `get_array`) the
1812        // `&Value` receiver already exposes. A regression that
1813        // implemented only one axis on the Map arm (a copy-paste
1814        // omission at the impl block) would surface here as one of the
1815        // three assertions failing to compile / returning `None`.
1816        let obj: Map<String, Value> = json!({
1817            "s": "hello",
1818            "n": 42,
1819            "a": [1, 2, 3],
1820        })
1821        .as_object()
1822        .unwrap()
1823        .clone();
1824        assert_eq!(obj.get_str("s"), Some("hello"));
1825        assert_eq!(obj.get_i64("n"), Some(42));
1826        assert_eq!(obj.get_array("a").map(Vec::len), Some(3));
1827    }
1828
1829    #[test]
1830    fn map_receiver_get_str_matches_pre_lift_hand_authored_chain_bytewise() {
1831        // Byte-shape parity pin: `<map>.get_str(<key>)` on a
1832        // `&Map<String, Value>` MUST return the SAME `Option<&str>` the
1833        // pre-lift `.get(<key>).and_then(Value::as_str)` chain
1834        // produced. Sweeps every pre-lift-reachable corner (present
1835        // string, present non-string, absent) so a regression at the
1836        // Map impl that broke byte identity with the pre-lift chain at
1837        // ONE corner surfaces here rather than as a per-slot divergence
1838        // at every `patch::phase_status_*` / `ssapply::ownership_*` pin.
1839        let obj: Map<String, Value> = json!({
1840            "phase": "Running",
1841            "phaseSince": "2026-01-01T00:00:00Z",
1842            "message": "",
1843            "numeric": 7,
1844            "null_valued": null,
1845        })
1846        .as_object()
1847        .unwrap()
1848        .clone();
1849        for key in [
1850            "phase",
1851            "phaseSince",
1852            "message",
1853            "numeric",
1854            "null_valued",
1855            "missing",
1856        ] {
1857            let via_primitive = obj.get_str(key);
1858            let via_pre_lift = obj.get(key).and_then(Value::as_str);
1859            assert_eq!(
1860                via_primitive, via_pre_lift,
1861                "corner `{key}` on Map receiver must round-trip through both shapes",
1862            );
1863        }
1864    }
1865
1866    #[test]
1867    fn map_receiver_get_array_matches_pre_lift_hand_authored_chain_bytewise() {
1868        // Sibling to the `get_str` byte-parity pin on the array axis
1869        // — sweeps present-array / present-non-array / absent so a
1870        // regression at the Map impl's `get_array` arm surfaces here
1871        // rather than as silent drift at
1872        // `patch::finalizers_metadata_patch_wraps_list_in_two_slot_metadata_body`
1873        // and its peers whose `metadata.get("finalizers").and_then(
1874        // Value::as_array)` chain lifts through this substrate.
1875        let obj: Map<String, Value> = json!({
1876            "finalizers": ["tatara.pleme.io/process-finalizer", "other.io/finalizer"],
1877            "fluxResources": [],
1878            "stringy": "not-array",
1879        })
1880        .as_object()
1881        .unwrap()
1882        .clone();
1883        for key in ["finalizers", "fluxResources", "stringy", "missing"] {
1884            let via_primitive = obj.get_array(key);
1885            let via_pre_lift = obj.get(key).and_then(Value::as_array);
1886            assert_eq!(
1887                via_primitive, via_pre_lift,
1888                "corner `{key}` on Map receiver's array axis must round-trip through both shapes",
1889            );
1890        }
1891    }
1892
1893    #[test]
1894    fn map_receiver_get_i64_matches_pre_lift_hand_authored_chain_bytewise() {
1895        // Sibling to the `get_str` / `get_array` byte-parity pins on
1896        // the integer axis — closes the third axis of the family and
1897        // pins that a Map-receiver caller reaching this arm gets the
1898        // SAME `Option<i64>` the pre-lift chain produced.
1899        let obj: Map<String, Value> = json!({
1900            "succeeded": 2,
1901            "failed": 0,
1902            "active": 5,
1903            "stringy": "1",
1904            "null_valued": null,
1905        })
1906        .as_object()
1907        .unwrap()
1908        .clone();
1909        for key in [
1910            "succeeded",
1911            "failed",
1912            "active",
1913            "stringy",
1914            "null_valued",
1915            "missing",
1916        ] {
1917            let via_primitive = obj.get_i64(key);
1918            let via_pre_lift = obj.get(key).and_then(Value::as_i64);
1919            assert_eq!(
1920                via_primitive, via_pre_lift,
1921                "corner `{key}` on Map receiver's integer axis must round-trip through both shapes",
1922            );
1923        }
1924    }
1925
1926    #[test]
1927    fn map_receiver_get_str_matches_value_object_arm_bytewise() {
1928        // Cross-receiver coherence pin: an `&Map<String, Value>`
1929        // receiver's `.get_str(<key>)` MUST return the SAME
1930        // `Option<&str>` that walking the equivalent `Value::Object(m)`
1931        // through the pre-existing `Value` impl would. A regression
1932        // that specialised the Map arm (a slot-name-normalisation
1933        // pass, a per-fleet trim) at ONE receiver but not the other
1934        // would silently split the two receiver shapes' behaviour and
1935        // break the "widening preserves semantics" invariant.
1936        let v: Value = json!({
1937            "apiVersion": "v1",
1938            "kind": "ConfigMap",
1939            "phase": "Running",
1940        });
1941        let m: &Map<String, Value> = v.as_object().unwrap();
1942        for key in ["apiVersion", "kind", "phase", "missing"] {
1943            assert_eq!(
1944                <Map<String, Value> as ValueGetExt>::get_str(m, key),
1945                <Value as ValueGetExt>::get_str(&v, key),
1946                "receiver-shape parity: `{key}` must project identically through both impls",
1947            );
1948        }
1949    }
1950
1951    #[test]
1952    fn map_receiver_axis_family_reaches_all_three_axes_through_one_trait_import() {
1953        // Axis-family + receiver-shape pin combined: a generic
1954        // `T: ValueGetExt` bound reaches ALL THREE axes on the Map
1955        // receiver — the SAME structural invariant the pre-existing
1956        // `get_array_axis_family_reaches_...` sibling pins for the
1957        // `Value` receiver. This test walks the SAME `probe`-style
1958        // generic through the Map arm, so a regression that split the
1959        // trait into per-axis peers would break the invariant on both
1960        // receiver shapes simultaneously.
1961        fn probe<T: ValueGetExt>(t: &T) -> (Option<i64>, Option<&str>, Option<&Vec<Value>>) {
1962            (t.get_i64("n"), t.get_str("s"), t.get_array("a"))
1963        }
1964        let m: Map<String, Value> = json!({ "n": 7, "s": "hello", "a": [1, 2, 3] })
1965            .as_object()
1966            .unwrap()
1967            .clone();
1968        let (n, s, a) = probe(&m);
1969        assert_eq!(n, Some(7));
1970        assert_eq!(s, Some("hello"));
1971        assert_eq!(a.map(Vec::len), Some(3));
1972    }
1973}