aurum-core 0.0.23

On-device speech I/O core: whisper.cpp STT, ONNX TTS, cleanup, providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! Provider support-tier evidence, freshness, and demotion policy (JOE-2223).
//!
//! `supported` is an operational claim: reviewed factory + mocks + **fresh**
//! protected inference evidence (≤30 days). Mocks alone never promote a remote
//! route. Evidence never retains payloads, keys, or private voice IDs.

use crate::error::{Result, UserError};
use crate::provider_platform::{list_provider_summaries, ProviderRegistry, ProviderStability};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

/// Evidence record schema version.
pub const PROVIDER_EVIDENCE_SCHEMA_VERSION: u32 = 1;

/// Maximum age (seconds) of a passing protected smoke for a `supported` route.
pub const SUPPORTED_EVIDENCE_MAX_AGE_SECS: u64 = 30 * 24 * 60 * 60; // 30 days

/// Product support tier (code/docs/CLI). Distinct from registry
/// [`ProviderStability`] which describes implementation maturity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SupportTier {
    /// Meets full entry rules including fresh protected evidence.
    Supported,
    /// Implemented + mocks; evidence missing/stale/limited. Never a default.
    Experimental,
    /// Requires deliberate selection; hidden from normal recommendation flows.
    ExplicitOnly,
}

impl SupportTier {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Supported => "supported",
            Self::Experimental => "experimental",
            Self::ExplicitOnly => "explicit_only",
        }
    }

    pub fn parse(s: &str) -> Result<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "supported" | "stable" => Ok(Self::Supported),
            "experimental" => Ok(Self::Experimental),
            "explicit_only" | "explicit-only" | "explicit" => Ok(Self::ExplicitOnly),
            other => Err(UserError::InvalidConfig {
                reason: format!(
                    "unknown support tier '{other}' (use supported|experimental|explicit_only)"
                ),
            }
            .into()),
        }
    }
}

/// Operation covered by an evidence record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceOperation {
    Stt,
    Tts,
}

impl EvidenceOperation {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Stt => "stt",
            Self::Tts => "tts",
        }
    }
}

/// Closed failure categories (no free-form vendor bodies).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceFailureCategory {
    #[default]
    None,
    Auth,
    RateLimit,
    Quota,
    Network,
    ModelUnavailable,
    ProtocolDrift,
    AccountGuardrail,
    InvalidPayload,
    Timeout,
    Other,
}

/// Machine-readable provider evidence record (redacted).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProviderEvidenceRecord {
    pub schema_version: u32,
    pub provider_id: String,
    pub operation: EvidenceOperation,
    pub model_id: String,
    /// Reviewed voice alias (never private ElevenLabs IDs in public evidence).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub voice_alias: Option<String>,
    pub support_tier: SupportTier,
    /// Full git commit when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aurum_commit: Option<String>,
    pub aurum_version: String,
    /// Protocol/endpoint contract label (e.g. `openai_stt_v1`).
    pub protocol_contract: String,
    /// UTC unix seconds when the protected smoke executed.
    pub executed_at_unix: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workflow_run_id: Option<String>,
    pub auth_ok: bool,
    pub passed: bool,
    #[serde(default)]
    pub failure_category: EvidenceFailureCategory,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latency_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encoded_bytes: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decoded_bytes: Option<u64>,
    /// Non-empty result without payload (text chars or audio samples count only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_units: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sample_rate_hz: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backend_kind: Option<String>,
    #[serde(default)]
    pub timestamps_reliable: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capability_snapshot_digest: Option<String>,
    /// Explicit expiry (unix). If absent, freshness uses max age from execution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at_unix: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
}

impl ProviderEvidenceRecord {
    pub fn validate_schema(&self) -> Result<()> {
        if self.schema_version != PROVIDER_EVIDENCE_SCHEMA_VERSION {
            return Err(UserError::Other {
                message: format!(
                    "unsupported provider evidence schema_version {} (expected {PROVIDER_EVIDENCE_SCHEMA_VERSION})",
                    self.schema_version
                ),
            }
            .into());
        }
        if self.provider_id.trim().is_empty() || self.model_id.trim().is_empty() {
            return Err(UserError::Other {
                message: "provider evidence requires non-empty provider_id and model_id".into(),
            }
            .into());
        }
        if self.executed_at_unix == 0 {
            return Err(UserError::Other {
                message: "provider evidence requires executed_at_unix".into(),
            }
            .into());
        }
        // Privacy: notes must not look like secrets/payloads.
        if let Some(ref n) = self.notes {
            for bad in ["sk-", "Bearer ", "BEGIN_", "transcript=", "pcm="] {
                if n.contains(bad) {
                    return Err(UserError::Other {
                        message: format!(
                            "provider evidence notes contain forbidden fragment {bad:?}"
                        ),
                    }
                    .into());
                }
            }
        }
        Ok(())
    }

    pub fn route_key(&self) -> String {
        format!(
            "{}:{}:{}:{}",
            self.provider_id,
            self.operation.as_str(),
            self.model_id,
            self.voice_alias.as_deref().unwrap_or("-")
        )
    }

    /// Freshness relative to `now_unix` (typically wall clock).
    pub fn is_fresh(&self, now_unix: u64) -> bool {
        if let Some(exp) = self.expires_at_unix {
            return now_unix <= exp;
        }
        now_unix.saturating_sub(self.executed_at_unix) <= SUPPORTED_EVIDENCE_MAX_AGE_SECS
    }

    /// A route may claim `supported` only with a fresh **passing** record.
    pub fn qualifies_as_supported(&self, now_unix: u64) -> bool {
        matches!(self.support_tier, SupportTier::Supported)
            && self.passed
            && self.auth_ok
            && self.is_fresh(now_unix)
    }

    pub fn load(path: &Path) -> Result<Self> {
        let data = fs::read_to_string(path).map_err(|e| UserError::Other {
            message: format!("read provider evidence {}: {e}", path.display()),
        })?;
        if data.len() > 256 * 1024 {
            return Err(UserError::Other {
                message: "provider evidence file exceeds 256 KiB bound".into(),
            }
            .into());
        }
        let rec: Self = serde_json::from_str(&data).map_err(|e| UserError::Other {
            message: format!("parse provider evidence: {e}"),
        })?;
        rec.validate_schema()?;
        Ok(rec)
    }

    pub fn to_json_pretty(&self) -> Result<String> {
        serde_json::to_string_pretty(self).map_err(|e| {
            UserError::Other {
                message: format!("serialize provider evidence: {e}"),
            }
            .into()
        })
    }
}

/// Reviewed claim that a route is product-supported (must be backed by evidence).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SupportedRouteClaim {
    pub provider_id: String,
    pub operation: EvidenceOperation,
    pub model_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub voice_alias: Option<String>,
    /// When true, missing/stale evidence fails the release gate.
    #[serde(default = "default_true")]
    pub required_for_release: bool,
}

fn default_true() -> bool {
    true
}

impl SupportedRouteClaim {
    pub fn route_key(&self) -> String {
        format!(
            "{}:{}:{}:{}",
            self.provider_id,
            self.operation.as_str(),
            self.model_id,
            self.voice_alias.as_deref().unwrap_or("-")
        )
    }
}

/// Versioned index of claims + optional evidence directory.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProviderEvidenceIndex {
    pub schema_version: u32,
    pub aurum_version: String,
    /// Routes that product code/docs currently claim as `supported`.
    pub supported_claims: Vec<SupportedRouteClaim>,
    /// Routes intentionally experimental (documentation only; do not block release).
    #[serde(default)]
    pub experimental_routes: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
}

impl ProviderEvidenceIndex {
    pub fn load(path: &Path) -> Result<Self> {
        let data = fs::read_to_string(path).map_err(|e| UserError::Other {
            message: format!("read evidence index {}: {e}", path.display()),
        })?;
        let idx: Self = serde_json::from_str(&data).map_err(|e| UserError::Other {
            message: format!("parse evidence index: {e}"),
        })?;
        if idx.schema_version != PROVIDER_EVIDENCE_SCHEMA_VERSION {
            return Err(UserError::Other {
                message: format!(
                    "unsupported evidence index schema_version {}",
                    idx.schema_version
                ),
            }
            .into());
        }
        Ok(idx)
    }
}

/// One gate finding.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EvidenceGateFinding {
    pub severity: String,
    pub route: String,
    pub code: String,
    pub message: String,
}

/// Result of evaluating supported claims against evidence files.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EvidenceGateReport {
    pub passed: bool,
    pub now_unix: u64,
    pub findings: Vec<EvidenceGateFinding>,
}

/// Load all `*.json` evidence records under `dir` (non-recursive).
pub fn load_evidence_dir(dir: &Path) -> Result<Vec<ProviderEvidenceRecord>> {
    if !dir.is_dir() {
        return Err(UserError::Other {
            message: format!("evidence directory missing: {}", dir.display()),
        }
        .into());
    }
    let mut out = Vec::new();
    for ent in fs::read_dir(dir).map_err(|e| UserError::Other {
        message: format!("read evidence dir: {e}"),
    })? {
        let ent = ent.map_err(|e| UserError::Other {
            message: format!("read evidence entry: {e}"),
        })?;
        let path = ent.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        if path.file_name().and_then(|n| n.to_str()) == Some("index.json") {
            continue;
        }
        out.push(ProviderEvidenceRecord::load(&path)?);
    }
    Ok(out)
}

fn now_unix() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Evaluate release readiness for supported remote routes.
///
/// Local routes never require protected network evidence.
pub fn evaluate_supported_evidence_gate(
    index: &ProviderEvidenceIndex,
    records: &[ProviderEvidenceRecord],
    now: Option<u64>,
) -> EvidenceGateReport {
    let now_unix = now.unwrap_or_else(now_unix);
    let mut by_route: BTreeMap<String, Vec<&ProviderEvidenceRecord>> = BTreeMap::new();
    for r in records {
        by_route.entry(r.route_key()).or_default().push(r);
    }

    let mut findings = Vec::new();
    for claim in &index.supported_claims {
        if !claim.required_for_release {
            continue;
        }
        // Local is always supported without remote smoke.
        if claim.provider_id == "local" {
            findings.push(EvidenceGateFinding {
                severity: "pass".into(),
                route: claim.route_key(),
                code: "local_supported".into(),
                message: "local route does not require protected network evidence".into(),
            });
            continue;
        }

        let key = claim.route_key();
        let Some(list) = by_route.get(&key) else {
            findings.push(EvidenceGateFinding {
                severity: "fail".into(),
                route: key,
                code: "missing_evidence".into(),
                message: "no evidence record for supported claim; demote, restore, or remove"
                    .into(),
            });
            continue;
        };

        let best = list
            .iter()
            .filter(|r| r.passed && r.auth_ok)
            .max_by_key(|r| r.executed_at_unix);
        match best {
            None => findings.push(EvidenceGateFinding {
                severity: "fail".into(),
                route: key,
                code: "no_passing_evidence".into(),
                message: "evidence exists but no passing/auth_ok record".into(),
            }),
            Some(r) if !r.is_fresh(now_unix) => findings.push(EvidenceGateFinding {
                severity: "fail".into(),
                route: key,
                code: "stale_evidence".into(),
                message: format!(
                    "latest passing evidence is older than {} days (executed_at_unix={})",
                    SUPPORTED_EVIDENCE_MAX_AGE_SECS / 86400,
                    r.executed_at_unix
                ),
            }),
            Some(r) if !matches!(r.support_tier, SupportTier::Supported) => {
                findings.push(EvidenceGateFinding {
                    severity: "fail".into(),
                    route: key,
                    code: "tier_mismatch".into(),
                    message: format!(
                        "claim is supported but evidence tier is {}",
                        r.support_tier.as_str()
                    ),
                });
            }
            Some(_) => findings.push(EvidenceGateFinding {
                severity: "pass".into(),
                route: key,
                code: "ok".into(),
                message: "fresh passing evidence present".into(),
            }),
        }
    }

    let passed = findings.iter().all(|f| f.severity != "fail");
    EvidenceGateReport {
        passed,
        now_unix,
        findings,
    }
}

/// Catalogue drift: reviewed model IDs that discovery no longer lists.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CatalogueDriftReport {
    pub provider_id: String,
    pub missing_from_discovery: Vec<String>,
    pub unexpected_in_discovery: Vec<String>,
}

/// Compare a reviewed allowlist to a discovery set (never auto-trust discovery).
pub fn detect_catalogue_drift(
    provider_id: &str,
    reviewed: &[String],
    discovered: &[String],
) -> CatalogueDriftReport {
    let rev: std::collections::BTreeSet<_> = reviewed.iter().cloned().collect();
    let disc: std::collections::BTreeSet<_> = discovered.iter().cloned().collect();
    CatalogueDriftReport {
        provider_id: provider_id.into(),
        missing_from_discovery: rev.difference(&disc).cloned().collect(),
        unexpected_in_discovery: disc.difference(&rev).cloned().collect(),
    }
}

/// Map registry stability to product support tier **before** evidence overlay.
pub fn tier_from_registry_stability(s: ProviderStability) -> SupportTier {
    match s {
        ProviderStability::Stable => SupportTier::Supported,
        ProviderStability::Experimental => SupportTier::Experimental,
        ProviderStability::TestOnly => SupportTier::ExplicitOnly,
    }
}

/// Effective tier for a provider after applying evidence (local stays supported).
pub fn effective_provider_tier(
    provider_id: &str,
    registry_stability: ProviderStability,
    evidence: &[ProviderEvidenceRecord],
    now_unix: u64,
) -> SupportTier {
    if provider_id == "local" {
        return SupportTier::Supported;
    }
    let base = tier_from_registry_stability(registry_stability);
    if !matches!(base, SupportTier::Supported) {
        return base;
    }
    // Registry says stable/supported — require at least one fresh passing evidence
    // for any STT or TTS model route, else demote to experimental for gate purposes.
    let has_fresh = evidence
        .iter()
        .any(|r| r.provider_id == provider_id && r.qualifies_as_supported(now_unix));
    if has_fresh {
        SupportTier::Supported
    } else {
        SupportTier::Experimental
    }
}

/// Summarize builtin registry + evidence for documentation/release.
pub fn provider_tier_matrix(
    registry: &ProviderRegistry,
    evidence: &[ProviderEvidenceRecord],
    now_unix: u64,
) -> Vec<(String, SupportTier, bool, bool)> {
    list_provider_summaries(registry)
        .into_iter()
        .map(|s| {
            let tier = effective_provider_tier(&s.id, s.stability, evidence, now_unix);
            (s.id, tier, s.stt, s.tts)
        })
        .collect()
}

/// Built-in local evidence record (always valid for CI / offline).
pub fn local_stt_evidence(now_unix: u64) -> ProviderEvidenceRecord {
    ProviderEvidenceRecord {
        schema_version: PROVIDER_EVIDENCE_SCHEMA_VERSION,
        provider_id: "local".into(),
        operation: EvidenceOperation::Stt,
        model_id: "base".into(),
        voice_alias: None,
        support_tier: SupportTier::Supported,
        aurum_commit: None,
        aurum_version: env!("CARGO_PKG_VERSION").into(),
        protocol_contract: "local_whisper_v1".into(),
        executed_at_unix: now_unix,
        workflow_run_id: Some("offline-ci".into()),
        auth_ok: true,
        passed: true,
        failure_category: EvidenceFailureCategory::None,
        latency_ms: None,
        encoded_bytes: None,
        decoded_bytes: None,
        result_units: Some(1),
        sample_rate_hz: Some(16_000),
        backend_kind: Some("asr".into()),
        timestamps_reliable: true,
        capability_snapshot_digest: None,
        expires_at_unix: Some(now_unix + SUPPORTED_EVIDENCE_MAX_AGE_SECS),
        notes: Some("local STT — no network evidence required".into()),
    }
}

pub fn local_tts_evidence(now_unix: u64) -> ProviderEvidenceRecord {
    ProviderEvidenceRecord {
        schema_version: PROVIDER_EVIDENCE_SCHEMA_VERSION,
        provider_id: "local".into(),
        operation: EvidenceOperation::Tts,
        model_id: "kitten-nano-int8".into(),
        voice_alias: Some("Luna".into()),
        support_tier: SupportTier::Supported,
        aurum_commit: None,
        aurum_version: env!("CARGO_PKG_VERSION").into(),
        protocol_contract: "local_kitten_v1".into(),
        executed_at_unix: now_unix,
        workflow_run_id: Some("offline-ci".into()),
        auth_ok: true,
        passed: true,
        failure_category: EvidenceFailureCategory::None,
        latency_ms: None,
        encoded_bytes: None,
        decoded_bytes: None,
        result_units: Some(1),
        sample_rate_hz: Some(24_000),
        backend_kind: Some("local".into()),
        timestamps_reliable: false,
        capability_snapshot_digest: None,
        expires_at_unix: Some(now_unix + SUPPORTED_EVIDENCE_MAX_AGE_SECS),
        notes: Some("local TTS — no network evidence required".into()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn claim(provider: &str, op: EvidenceOperation, model: &str) -> SupportedRouteClaim {
        SupportedRouteClaim {
            provider_id: provider.into(),
            operation: op,
            model_id: model.into(),
            voice_alias: None,
            required_for_release: true,
        }
    }

    #[test]
    fn local_gate_passes_without_files() {
        let idx = ProviderEvidenceIndex {
            schema_version: 1,
            aurum_version: "0.0.22".into(),
            supported_claims: vec![claim("local", EvidenceOperation::Stt, "base")],
            experimental_routes: vec![],
            notes: None,
        };
        let rep = evaluate_supported_evidence_gate(&idx, &[], None);
        assert!(rep.passed, "{:?}", rep.findings);
    }

    #[test]
    fn missing_remote_evidence_fails() {
        let idx = ProviderEvidenceIndex {
            schema_version: 1,
            aurum_version: "0.0.22".into(),
            supported_claims: vec![claim("openai", EvidenceOperation::Stt, "whisper-1")],
            experimental_routes: vec![],
            notes: None,
        };
        let rep = evaluate_supported_evidence_gate(&idx, &[], Some(1_700_000_000));
        assert!(!rep.passed);
        assert!(rep.findings.iter().any(|f| f.code == "missing_evidence"));
    }

    #[test]
    fn stale_evidence_fails() {
        let now = 2_000_000_000u64;
        let mut rec = local_stt_evidence(now);
        rec.provider_id = "openai".into();
        rec.model_id = "whisper-1".into();
        rec.protocol_contract = "openai_stt_v1".into();
        rec.executed_at_unix = now - SUPPORTED_EVIDENCE_MAX_AGE_SECS - 10;
        rec.expires_at_unix = None;
        let idx = ProviderEvidenceIndex {
            schema_version: 1,
            aurum_version: "0.0.22".into(),
            supported_claims: vec![claim("openai", EvidenceOperation::Stt, "whisper-1")],
            experimental_routes: vec![],
            notes: None,
        };
        let rep = evaluate_supported_evidence_gate(&idx, &[rec], Some(now));
        assert!(!rep.passed);
        assert!(rep.findings.iter().any(|f| f.code == "stale_evidence"));
    }

    #[test]
    fn fresh_passing_remote_ok() {
        let now = 2_000_000_000u64;
        let mut rec = local_stt_evidence(now);
        rec.provider_id = "openai".into();
        rec.model_id = "whisper-1".into();
        rec.protocol_contract = "openai_stt_v1".into();
        let idx = ProviderEvidenceIndex {
            schema_version: 1,
            aurum_version: "0.0.22".into(),
            supported_claims: vec![claim("openai", EvidenceOperation::Stt, "whisper-1")],
            experimental_routes: vec![],
            notes: None,
        };
        let rep = evaluate_supported_evidence_gate(&idx, &[rec], Some(now));
        assert!(rep.passed, "{:?}", rep.findings);
    }

    #[test]
    fn catalogue_drift_detects_removed_model() {
        let d = detect_catalogue_drift(
            "openai",
            &["whisper-1".into(), "gone-model".into()],
            &["whisper-1".into(), "new-model".into()],
        );
        assert_eq!(d.missing_from_discovery, vec!["gone-model".to_string()]);
        assert_eq!(d.unexpected_in_discovery, vec!["new-model".to_string()]);
    }

    #[test]
    fn effective_tier_demotes_without_evidence() {
        let now = 2_000_000_000u64;
        let t = effective_provider_tier("openai", ProviderStability::Stable, &[], now);
        assert_eq!(t, SupportTier::Experimental);
        let rec = {
            let mut r = local_stt_evidence(now);
            r.provider_id = "openai".into();
            r.model_id = "whisper-1".into();
            r
        };
        let t2 = effective_provider_tier("openai", ProviderStability::Stable, &[rec], now);
        assert_eq!(t2, SupportTier::Supported);
    }

    #[test]
    fn privacy_rejects_secret_notes() {
        let mut r = local_stt_evidence(1);
        r.notes = Some("sk-abc".into());
        assert!(r.validate_schema().is_err());
    }
}