Skip to main content

codewhale_config/
catalog.rs

1//! Models.dev-backed provider catalog snapshots and a secret-free live cache
2//! (#3385, feeding EPIC #2608 and #3383).
3//!
4//! This module is **network-free** by construction. Callers supply parsed
5//! [`crate::models_dev::ModelsDevCatalog`] JSON (bundled snapshot or live
6//! refresh) and live [`ProviderCatalogDelta`]s; the HTTP `/models` fetch layer
7//! lives above this module. Nothing here performs I/O or reads credentials.
8//!
9//! Layering (lowest precedence first):
10//!
11//! ```text
12//! bundled Models.dev snapshot / built-in seeds
13//!   < provider live `/models` cache  (scoped per provider + base-URL fingerprint)
14//!   < user / custom overrides        (custom endpoints, pinned models, explicit facts)
15//! ```
16//!
17//! Invariants preserved from #2608 / #3497:
18//! - A catalog row is **not** an executable route. Rows still compile through
19//!   `RouteResolver` into a `ReadyRouteCandidate` before execution.
20//! - `wire_model_id` is kept separate from `canonical_model`; a provider row may
21//!   not expose a canonical `base_model` join, and a prefix never proves
22//!   canonical ownership.
23//! - Unknown / custom / local rows are supported with explicit provenance and a
24//!   `None` canonical model.
25//!
26//! The on-disk cache format intentionally uses plain `String` identity fields
27//! rather than the internal route newtypes, so the persisted shape is decoupled
28//! from internal types and trivially auditable for "no secrets" (see
29//! [`ProviderCatalogCache`] tests).
30
31use std::collections::BTreeMap;
32use std::time::{SystemTime, UNIX_EPOCH};
33
34use serde::{Deserialize, Serialize};
35use serde_json::Value;
36
37use crate::models_dev::{ModelsDevCatalog, ModelsDevCost, ModelsDevLimit, ModelsDevModalities};
38use crate::route::{ModelId, ProviderId, ProviderModelOffering, RouteLimits, WireModelId};
39
40/// Provenance of a catalog row. Drives layer precedence and UI provenance.
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(tag = "kind", rename_all = "snake_case")]
43pub enum CatalogSource {
44    /// Bundled, network-free seed (a Models.dev snapshot or built-in defaults).
45    #[default]
46    Bundled,
47    /// A provider live `/models` row, scoped to a base-URL fingerprint and the
48    /// unix timestamp it was fetched at.
49    Live {
50        base_url_fingerprint: String,
51        fetched_at: u64,
52    },
53    /// A user / custom override (custom endpoint, pinned model, explicit facts).
54    UserOverride,
55}
56
57/// One catalog-layer offering row.
58///
59/// This carries the routing identity (provider + wire id + optional canonical
60/// model + endpoint) plus the offering-owned Models.dev facts CodeWhale wants to
61/// preserve (family, limits, cost, reasoning support/options). It is a superset
62/// of [`ProviderModelOffering`]; use [`CatalogOffering::to_offering`] to project
63/// the minimal routing identity the resolver consumes.
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
65pub struct CatalogOffering {
66    /// Provider id serving this offering.
67    pub provider: String,
68    /// Provider-owned wire id sent on the request (verbatim).
69    pub wire_model_id: String,
70    /// Canonical model identity, only when an explicit join exists.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub canonical_model: Option<String>,
73    /// Endpoint key the offering is served on (e.g. `chat`).
74    pub endpoint_key: String,
75    /// Whether this is the provider's default offering.
76    #[serde(default)]
77    pub default_for_provider: bool,
78    /// Model family/series as exposed for this offering (e.g. `glm`, `deepseek`).
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub family: Option<String>,
81    /// Token limits for this offering, when known.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub limit: Option<ModelsDevLimit>,
84    /// Provider-scoped pricing, when known.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub cost: Option<ModelsDevCost>,
87    /// Input/output modalities for this offering, when known. Carried as the
88    /// raw Models.dev shape so a factual `text` vs `multimodal` label can be
89    /// derived without guessing; `None` means the layer did not state it (an
90    /// unknown, not "text-only").
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub modalities: Option<ModelsDevModalities>,
93    /// Whether this offering supports reasoning, when known.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub reasoning: Option<bool>,
96    /// Provider-scoped reasoning controls / accepted effort metadata. Kept as
97    /// raw JSON so the same model family served through different gateways can
98    /// expose different effort vocabularies without lossy collapsing.
99    #[serde(default, skip_serializing_if = "Vec::is_empty")]
100    pub reasoning_options: Vec<Value>,
101    /// Where this row came from.
102    pub source: CatalogSource,
103}
104
105impl CatalogOffering {
106    /// The provider id as a route newtype.
107    #[must_use]
108    pub fn provider_id(&self) -> ProviderId {
109        ProviderId::from(self.provider.clone())
110    }
111
112    /// The wire model id as a route newtype.
113    #[must_use]
114    pub fn wire_id(&self) -> WireModelId {
115        WireModelId::from(self.wire_model_id.clone())
116    }
117
118    /// Project the minimal routing identity the resolver consumes.
119    ///
120    /// The catalog deliberately carries richer facts than routing needs; this
121    /// drops most of them so `RouteResolver::from_offerings` stays the single
122    /// seam. The route-facing pricing meter is the exception: it is projected
123    /// here (where the offering's sourced `cost` is in scope) via
124    /// [`crate::pricing::route_pricing_sku`] so a resolved candidate can carry
125    /// honest pricing without the route layer ever seeing raw cost (#3085).
126    #[must_use]
127    pub fn to_offering(&self) -> ProviderModelOffering {
128        ProviderModelOffering {
129            provider: self.provider_id(),
130            canonical_model: self.canonical_model.clone().map(ModelId::from),
131            wire_model_id: self.wire_id(),
132            endpoint_key: self.endpoint_key.clone(),
133            default_for_provider: self.default_for_provider,
134            limits: self
135                .limit
136                .as_ref()
137                .map(RouteLimits::from)
138                .unwrap_or_default(),
139            pricing: crate::pricing::route_pricing_sku(self),
140        }
141    }
142
143    /// Stable identity key for de-duplication and layer merging.
144    fn merge_key(&self) -> (String, String) {
145        (self.provider.clone(), self.wire_model_id.clone())
146    }
147}
148
149/// The committed, network-free Models.dev-shaped catalog snapshot (#3385).
150///
151/// Curated from in-repo verified model facts (context windows / output caps from
152/// `crates/tui/src/models.rs`, USD pricing from `crates/tui/src/pricing.rs`)
153/// rather than a live models.dev dump, because the public catalog tracks a
154/// different real model generation than CodeWhale's curated forward-dated set.
155/// This is the default bundled layer feeding [`crate::route::RouteResolver::new`].
156/// See the asset's `_meta` block for sourcing and the honesty rule on omitted
157/// pricing (`UnknownOrStale`, never a fabricated zero).
158pub const BUNDLED_MODELS_DEV_JSON: &str = include_str!("../assets/models_dev.bundled.json");
159
160/// Parse the committed bundled Models.dev snapshot.
161///
162/// # Panics
163/// Panics only if the committed asset is not valid Models.dev JSON. The
164/// `tests::bundled_asset_parses` guard makes that a build-time failure, so this
165/// never panics in shipped builds.
166#[must_use]
167pub fn bundled_models_dev_catalog() -> ModelsDevCatalog {
168    ModelsDevCatalog::parse_json(BUNDLED_MODELS_DEV_JSON)
169        .expect("committed bundled Models.dev asset must be valid JSON")
170}
171
172/// The bundled-layer [`CatalogOffering`] rows from the committed snapshot.
173///
174/// This is the real-data source for the default resolver: every text-chat row
175/// from [`BUNDLED_MODELS_DEV_JSON`], tagged [`CatalogSource::Bundled`], with
176/// honest limits and pricing.
177#[must_use]
178pub fn bundled_catalog_offerings() -> Vec<CatalogOffering> {
179    bundled_offerings_from_models_dev(&bundled_models_dev_catalog())
180}
181
182/// Hydrate bundled [`CatalogOffering`] rows from a parsed Models.dev catalog.
183///
184/// Only text-chat offerings are emitted (TTS/audio-only rows stay in the parsed
185/// catalog but are excluded from route candidates, matching
186/// [`ModelsDevCatalog::provider_offerings`]). Each row is tagged
187/// [`CatalogSource::Bundled`]. No canonical model is inferred from a prefix; the
188/// canonical link is set only from an explicit `base_model`.
189#[must_use]
190pub fn bundled_offerings_from_models_dev(catalog: &ModelsDevCatalog) -> Vec<CatalogOffering> {
191    let mut out = Vec::new();
192    for (provider_key, provider) in &catalog.providers {
193        let provider_id = if provider.id.trim().is_empty() {
194            provider_key.trim().to_string()
195        } else {
196            provider.id.trim().to_string()
197        };
198        for model in provider.models.values() {
199            if !model.supports_text_chat() {
200                continue;
201            }
202            out.push(CatalogOffering {
203                provider: provider_id.clone(),
204                wire_model_id: model.id.clone(),
205                canonical_model: model.base_model.clone(),
206                endpoint_key: "chat".to_string(),
207                default_for_provider: model.default_for_provider,
208                family: model.family.clone(),
209                limit: model.limit.clone(),
210                cost: model.cost.clone(),
211                modalities: model.modalities.clone(),
212                reasoning: model.reasoning,
213                reasoning_options: model.reasoning_options.clone(),
214                source: CatalogSource::Bundled,
215            });
216        }
217    }
218    out
219}
220
221/// A provider's live `/models` refresh result, scoped to a base-URL fingerprint.
222///
223/// Returned as a delta rather than mutating any global model state directly, per
224/// the #3385 architecture contract.
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
226pub struct ProviderCatalogDelta {
227    /// Provider this delta belongs to.
228    pub provider: String,
229    /// Fingerprint of the base URL the rows were fetched from.
230    pub base_url_fingerprint: String,
231    /// Unix seconds the rows were fetched at.
232    pub fetched_at: u64,
233    /// Live offering rows. Sources are normalized to `Live` on ingest.
234    pub offerings: Vec<CatalogOffering>,
235}
236
237/// Why a provider live catalog refresh did not produce usable rows.
238///
239/// Every variant must leave previously cached / bundled / configured rows
240/// available; a refresh failure is never fatal to model selection.
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(rename_all = "snake_case")]
243pub enum CatalogRefreshError {
244    /// 401 — auth missing or invalid.
245    Unauthorized,
246    /// 403 — auth present but not permitted.
247    Forbidden,
248    /// 404 — provider does not expose `/models` at this base URL.
249    NotFound,
250    /// 429 — rate limited.
251    RateLimited,
252    /// Response was not parseable as a model listing.
253    InvalidResponse,
254    /// Provider returned an empty model list.
255    EmptyList,
256    /// Transport / network failure.
257    Network,
258}
259
260/// Freshness / health of a provider's cached live catalog.
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(tag = "state", rename_all = "snake_case")]
263pub enum CatalogStatus {
264    /// Cached rows are within their TTL.
265    Fresh,
266    /// Cached rows exist but are past their TTL.
267    Stale { age_secs: u64 },
268    /// The last refresh failed; any rows present are from an earlier success.
269    Failed { reason: CatalogRefreshError },
270    /// No refresh has been attempted for this provider + base URL.
271    Unknown,
272}
273
274/// A secret-free cached provider catalog for one provider + base-URL fingerprint.
275#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
276pub struct CachedProviderCatalog {
277    /// Provider id.
278    pub provider: String,
279    /// Base-URL fingerprint the rows were fetched from.
280    pub base_url_fingerprint: String,
281    /// Unix seconds of the last successful fetch (unchanged on failure).
282    pub fetched_at: u64,
283    /// Time-to-live, in seconds, after which rows are considered stale.
284    pub ttl_secs: u64,
285    /// Cached live offering rows (possibly empty after a failure with no prior).
286    pub offerings: Vec<CatalogOffering>,
287    /// Last known status of this entry.
288    pub status: CatalogStatus,
289}
290
291impl CachedProviderCatalog {
292    /// Age in seconds relative to `now_unix`, saturating at zero for clock skew.
293    #[must_use]
294    pub fn age_secs(&self, now_unix: u64) -> u64 {
295        now_unix.saturating_sub(self.fetched_at)
296    }
297
298    /// Whether the cached rows are past their TTL at `now_unix`.
299    ///
300    /// A `ttl_secs` of zero means "always stale" (never serve as fresh).
301    #[must_use]
302    pub fn is_stale(&self, now_unix: u64) -> bool {
303        self.age_secs(now_unix) >= self.ttl_secs
304    }
305
306    /// Whether this entry may contribute live offerings at `now_unix`.
307    ///
308    /// An entry is fresh only when it is within its TTL **and** its last
309    /// recorded refresh succeeded. A `Failed` entry is never fresh even inside
310    /// its TTL window — its rows survive a failed refresh for explicit fallback
311    /// display via [`ProviderCatalogCache::get`], but they are not served as
312    /// current live data.
313    #[must_use]
314    pub fn is_fresh(&self, now_unix: u64) -> bool {
315        !self.is_stale(now_unix) && !matches!(self.status, CatalogStatus::Failed { .. })
316    }
317}
318
319/// A secret-free store of cached provider catalogs, keyed by provider + base-URL
320/// fingerprint.
321///
322/// Scoping rule (#3385): the SAME provider on DIFFERENT base URLs must not share
323/// rows, and DIFFERENT providers on the same base URL must not share rows.
324#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
325pub struct ProviderCatalogCache {
326    /// Entries keyed by [`ProviderCatalogCache::cache_key`].
327    #[serde(default)]
328    pub entries: BTreeMap<String, CachedProviderCatalog>,
329}
330
331impl ProviderCatalogCache {
332    /// Construct an empty cache.
333    #[must_use]
334    pub fn new() -> Self {
335        Self::default()
336    }
337
338    /// Compute the composite cache key for a provider + base-URL fingerprint.
339    #[must_use]
340    pub fn cache_key(provider: &str, base_url_fingerprint: &str) -> String {
341        // Unit separator avoids ambiguity between provider and fingerprint.
342        format!("{}\u{1f}{}", provider.trim(), base_url_fingerprint.trim())
343    }
344
345    /// Look up a cached entry by provider + base-URL fingerprint.
346    #[must_use]
347    pub fn get(
348        &self,
349        provider: &str,
350        base_url_fingerprint: &str,
351    ) -> Option<&CachedProviderCatalog> {
352        self.entries
353            .get(&Self::cache_key(provider, base_url_fingerprint))
354    }
355
356    /// Record a successful refresh, replacing any prior entry for this scope.
357    ///
358    /// Offering sources are normalized to [`CatalogSource::Live`] with the
359    /// delta's fingerprint and `fetched_at`, so cached rows always carry honest
360    /// provenance regardless of how the delta was assembled.
361    pub fn record_success(&mut self, delta: ProviderCatalogDelta, ttl_secs: u64) {
362        let ProviderCatalogDelta {
363            provider,
364            base_url_fingerprint,
365            fetched_at,
366            offerings,
367        } = delta;
368        let offerings = offerings
369            .into_iter()
370            .map(|mut row| {
371                row.source = CatalogSource::Live {
372                    base_url_fingerprint: base_url_fingerprint.clone(),
373                    fetched_at,
374                };
375                row
376            })
377            .collect();
378        let key = Self::cache_key(&provider, &base_url_fingerprint);
379        self.entries.insert(
380            key,
381            CachedProviderCatalog {
382                provider,
383                base_url_fingerprint,
384                fetched_at,
385                ttl_secs,
386                offerings,
387                status: CatalogStatus::Fresh,
388            },
389        );
390    }
391
392    /// Record a refresh failure.
393    ///
394    /// Previously cached rows for this scope are preserved (so the UI can still
395    /// offer them with a visible "stale/failed" status); only the status is
396    /// updated. When no prior entry exists, an empty `Failed` entry is created so
397    /// the failure is observable.
398    pub fn record_failure(
399        &mut self,
400        provider: &str,
401        base_url_fingerprint: &str,
402        reason: CatalogRefreshError,
403    ) {
404        let key = Self::cache_key(provider, base_url_fingerprint);
405        match self.entries.get_mut(&key) {
406            Some(entry) => entry.status = CatalogStatus::Failed { reason },
407            None => {
408                self.entries.insert(
409                    key,
410                    CachedProviderCatalog {
411                        provider: provider.trim().to_string(),
412                        base_url_fingerprint: base_url_fingerprint.trim().to_string(),
413                        fetched_at: 0,
414                        ttl_secs: 0,
415                        offerings: Vec::new(),
416                        status: CatalogStatus::Failed { reason },
417                    },
418                );
419            }
420        }
421    }
422
423    /// The resolved status of an entry at `now_unix`.
424    ///
425    /// A `Fresh`-recorded entry that has since aged past its TTL reports
426    /// `Stale`; `Failed`/`Unknown` are returned as stored.
427    #[must_use]
428    pub fn status(
429        &self,
430        provider: &str,
431        base_url_fingerprint: &str,
432        now_unix: u64,
433    ) -> CatalogStatus {
434        match self.get(provider, base_url_fingerprint) {
435            None => CatalogStatus::Unknown,
436            Some(entry) => match &entry.status {
437                CatalogStatus::Failed { reason } => CatalogStatus::Failed { reason: *reason },
438                CatalogStatus::Unknown => CatalogStatus::Unknown,
439                CatalogStatus::Fresh | CatalogStatus::Stale { .. } => {
440                    if entry.is_stale(now_unix) {
441                        CatalogStatus::Stale {
442                            age_secs: entry.age_secs(now_unix),
443                        }
444                    } else {
445                        CatalogStatus::Fresh
446                    }
447                }
448            },
449        }
450    }
451
452    /// Fresh (within-TTL) live offerings for one provider + base URL at
453    /// `now_unix`. Stale or failed entries contribute nothing here; callers fall
454    /// back to bundled/configured rows and surface the status separately.
455    #[must_use]
456    pub fn fresh_offerings(
457        &self,
458        provider: &str,
459        base_url_fingerprint: &str,
460        now_unix: u64,
461    ) -> Vec<CatalogOffering> {
462        match self.get(provider, base_url_fingerprint) {
463            Some(entry) if entry.is_fresh(now_unix) => entry.offerings.clone(),
464            _ => Vec::new(),
465        }
466    }
467
468    /// All fresh live offerings across every cached provider + base URL.
469    #[must_use]
470    pub fn all_fresh_offerings(&self, now_unix: u64) -> Vec<CatalogOffering> {
471        self.entries
472            .values()
473            .filter(|entry| entry.is_fresh(now_unix))
474            .flat_map(|entry| entry.offerings.clone())
475            .collect()
476    }
477}
478
479/// A compiled, layer-merged catalog snapshot.
480#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
481pub struct CatalogSnapshot {
482    /// Merged offerings, de-duplicated by (provider, wire id), in stable order.
483    pub offerings: Vec<CatalogOffering>,
484}
485
486impl CatalogSnapshot {
487    /// Project routing offerings for `RouteResolver::from_offerings`.
488    #[must_use]
489    pub fn to_offerings(&self) -> Vec<ProviderModelOffering> {
490        self.offerings
491            .iter()
492            .map(CatalogOffering::to_offering)
493            .collect()
494    }
495
496    /// All offerings for one provider id.
497    #[must_use]
498    pub fn offerings_for_provider(&self, provider: &str) -> Vec<&CatalogOffering> {
499        self.offerings
500            .iter()
501            .filter(|row| row.provider == provider)
502            .collect()
503    }
504}
505
506/// Builds a [`CatalogSnapshot`] by merging layers in precedence order:
507/// bundled < live < user overrides. Later layers override earlier rows that
508/// share a (provider, wire id) identity.
509#[derive(Debug, Clone, Default)]
510pub struct CatalogCompiler {
511    bundled: Vec<CatalogOffering>,
512    live: Vec<CatalogOffering>,
513    overrides: Vec<CatalogOffering>,
514}
515
516impl CatalogCompiler {
517    /// Start an empty compiler.
518    #[must_use]
519    pub fn new() -> Self {
520        Self::default()
521    }
522
523    /// Add bundled (lowest-precedence) rows.
524    #[must_use]
525    pub fn with_bundled(mut self, rows: Vec<CatalogOffering>) -> Self {
526        self.bundled.extend(rows);
527        self
528    }
529
530    /// Seed bundled rows from a parsed Models.dev catalog.
531    #[must_use]
532    pub fn with_models_dev(mut self, catalog: &ModelsDevCatalog) -> Self {
533        self.bundled
534            .extend(bundled_offerings_from_models_dev(catalog));
535        self
536    }
537
538    /// Add live (middle-precedence) rows.
539    #[must_use]
540    pub fn with_live(mut self, rows: Vec<CatalogOffering>) -> Self {
541        self.live.extend(rows);
542        self
543    }
544
545    /// Add user/custom override (highest-precedence) rows.
546    #[must_use]
547    pub fn with_overrides(mut self, rows: Vec<CatalogOffering>) -> Self {
548        self.overrides.extend(rows);
549        self
550    }
551
552    /// Merge all layers into a deterministic snapshot.
553    #[must_use]
554    pub fn compile(self) -> CatalogSnapshot {
555        let mut merged: BTreeMap<(String, String), CatalogOffering> = BTreeMap::new();
556        for row in self
557            .bundled
558            .into_iter()
559            .chain(self.live)
560            .chain(self.overrides)
561        {
562            merged.insert(row.merge_key(), row);
563        }
564        CatalogSnapshot {
565            offerings: merged.into_values().collect(),
566        }
567    }
568}
569
570/// Normalize a base URL and fingerprint it for cache scoping.
571///
572/// Normalization folds case in the scheme/host, trims trailing slashes, and
573/// drops a default-port suffix, so cosmetically different spellings of the same
574/// endpoint share a cache scope while genuinely different endpoints do not. The
575/// fingerprint is a dependency-free FNV-1a hex digest; it is deterministic
576/// within and across runs but is not a cryptographic hash (it identifies a
577/// cache bucket, nothing security-sensitive).
578#[must_use]
579pub fn base_url_fingerprint(base_url: &str) -> String {
580    let normalized = normalize_base_url(base_url);
581    fnv1a_hex(normalized.as_bytes())
582}
583
584fn normalize_base_url(base_url: &str) -> String {
585    let trimmed = base_url.trim().trim_end_matches('/');
586    // Lowercase only the scheme://host authority; leave the path case-sensitive.
587    if let Some(idx) = trimmed.find("://") {
588        let (scheme, rest) = trimmed.split_at(idx);
589        let scheme = scheme.to_ascii_lowercase();
590        let rest = &rest[3..];
591        let (authority, path) = match rest.find('/') {
592            Some(p) => (&rest[..p], &rest[p..]),
593            None => (rest, ""),
594        };
595        let authority = authority.to_ascii_lowercase();
596        // Strip only the scheme's own default port, so a non-default pairing
597        // such as `http://host:443` stays distinct from `http://host`.
598        let default_port = match scheme.as_str() {
599            "https" => Some(":443"),
600            "http" => Some(":80"),
601            _ => None,
602        };
603        let authority = default_port
604            .and_then(|port| authority.strip_suffix(port))
605            .unwrap_or(&authority);
606        format!("{scheme}://{authority}{path}")
607    } else {
608        trimmed.to_ascii_lowercase()
609    }
610}
611
612fn fnv1a_hex(bytes: &[u8]) -> String {
613    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
614    const PRIME: u64 = 0x0000_0100_0000_01b3;
615    let mut hash = OFFSET;
616    for &b in bytes {
617        hash ^= u64::from(b);
618        hash = hash.wrapping_mul(PRIME);
619    }
620    format!("{hash:016x}")
621}
622
623/// Current unix time in seconds, for callers assembling deltas / cache entries.
624///
625/// Pure cache logic takes `now_unix` explicitly so it stays deterministic in
626/// tests; this helper is the one place that reads the wall clock.
627#[must_use]
628pub fn now_unix() -> u64 {
629    SystemTime::now()
630        .duration_since(UNIX_EPOCH)
631        .map(|d| d.as_secs())
632        .unwrap_or(0)
633}
634
635#[cfg(test)]
636mod tests;