everruns-core 0.13.0

Core agent abstractions for Everruns - agent loop, events, tools, LLM 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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
// OpenRouter Workspace Capability
//
// Provides host-facing tools for inspecting OpenRouter workspace/key policy
// metadata and detecting drift between local routing config and upstream
// workspace constraints.
//
// Tools contributed:
//   - inspect_openrouter_workspace: reads key status, budget, and rate-limit
//     from OpenRouter's /api/v1/auth/key endpoint. Sensitive key material is
//     never returned; only derived metadata.
//   - check_openrouter_policy_compatibility: compares local routing parameters
//     against the inspected workspace policy and returns a structured
//     compatibility report with detected drifts.
//
// Security: TM-LLM — API key sourced from provider_credential_store and never
// logged or returned to callers. TM-API — only the /api/v1/auth/key endpoint
// is called; no write operations against the workspace.

use super::{Capability, CapabilityLocalization, CapabilityStatus};
use crate::tools::{Tool, ToolExecutionResult};
use crate::traits::ToolContext;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

pub const OPENROUTER_WORKSPACE_CAPABILITY_ID: &str = "openrouter_workspace";

/// Capability that contributes workspace-inspection and policy-compatibility
/// tools for OpenRouter providers.
pub struct OpenRouterWorkspaceCapability;

impl Capability for OpenRouterWorkspaceCapability {
    fn id(&self) -> &str {
        OPENROUTER_WORKSPACE_CAPABILITY_ID
    }

    fn name(&self) -> &str {
        "OpenRouter Workspace"
    }

    fn description(&self) -> &str {
        "Inspect OpenRouter workspace policy (budget, rate limits, tier) and detect incompatibilities with local routing configuration."
    }

    fn localizations(&self) -> Vec<CapabilityLocalization> {
        vec![]
    }

    fn status(&self) -> CapabilityStatus {
        CapabilityStatus::Available
    }

    fn icon(&self) -> Option<&str> {
        Some("shield-check")
    }

    fn category(&self) -> Option<&str> {
        Some("AI")
    }

    fn tools(&self) -> Vec<Box<dyn Tool>> {
        vec![
            Box::new(InspectOpenRouterWorkspaceTool),
            Box::new(CheckOpenRouterPolicyCompatibilityTool),
        ]
    }
}

// ============================================================================
// Workspace policy types
// ============================================================================

/// Key/workspace metadata returned by OpenRouter's /api/v1/auth/key endpoint.
///
/// Usage and limit are converted from OpenRouter's millionths-of-USD integers
/// to human-readable USD floats. The raw API key is never included.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpenRouterKeyInfo {
    /// Human-readable label assigned to this API key.
    pub label: String,
    /// Total spend in USD against this key.
    pub usage_usd: f64,
    /// Spend cap in USD. `None` means unlimited.
    pub limit_usd: Option<f64>,
    /// Remaining budget in USD. `None` means unlimited.
    pub remaining_usd: Option<f64>,
    /// Whether this is a free-tier key (subject to model and rate restrictions).
    pub is_free_tier: bool,
    /// Rate limit applied to this key, if any.
    pub rate_limit: Option<OpenRouterRateLimit>,
}

impl OpenRouterKeyInfo {
    /// Parse the raw JSON response from /api/v1/auth/key.
    ///
    /// `usage` and `limit` arrive as millionths of USD (integer). This method
    /// converts them to USD floats and computes `remaining_usd`.
    fn from_api_response(data: &Value) -> Result<Self, String> {
        let label = data
            .get("label")
            .and_then(|v| v.as_str())
            .unwrap_or("(unnamed)")
            .to_string();

        // usage is in millionths of USD
        let usage_usd = data
            .get("usage")
            .and_then(|v| v.as_f64())
            .map(|u| u / 1_000_000.0)
            .unwrap_or(0.0);

        let limit_usd = data
            .get("limit")
            .and_then(|v| if v.is_null() { None } else { v.as_f64() })
            .map(|l| l / 1_000_000.0);

        let remaining_usd = limit_usd.map(|l| (l - usage_usd).max(0.0));

        let is_free_tier = data
            .get("is_free_tier")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let rate_limit = data.get("rate_limit").and_then(|rl| {
            let requests = rl.get("requests")?.as_u64()?.try_into().ok()?;
            let interval = rl.get("interval")?.as_str()?.to_string();
            Some(OpenRouterRateLimit { requests, interval })
        });

        Ok(OpenRouterKeyInfo {
            label,
            usage_usd,
            limit_usd,
            remaining_usd,
            is_free_tier,
            rate_limit,
        })
    }
}

/// Rate limit information for an OpenRouter API key.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpenRouterRateLimit {
    /// Maximum number of requests allowed in the interval.
    pub requests: u32,
    /// Time window for the rate limit (e.g. "10s", "1m").
    pub interval: String,
}

/// A detected incompatibility between local routing config and the upstream
/// OpenRouter workspace policy.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum WorkspacePolicyDrift {
    /// The workspace has a spend cap and the remaining budget is zero.
    BudgetExhausted {
        usage_usd: f64,
        limit_usd: f64,
        message: String,
    },
    /// The remaining budget is below the caller-requested per-probe threshold.
    BudgetBelowThreshold {
        remaining_usd: f64,
        threshold_usd: f64,
        message: String,
    },
    /// The key is on the free tier but the routing config requires paid-tier
    /// features (e.g. `zdr`, `data_collection: deny`, paid-only providers).
    FreeTierRestriction { feature: String, message: String },
}

/// Full compatibility report produced by `check_openrouter_policy_compatibility`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyCompatibilityReport {
    /// `true` when no drifts were detected.
    pub compatible: bool,
    /// Workspace metadata at the time of the check (no API key material).
    pub workspace: OpenRouterKeyInfo,
    /// Detected incompatibilities, empty when `compatible` is `true`.
    pub drifts: Vec<WorkspacePolicyDrift>,
}

/// Evaluate workspace policy against caller-supplied routing parameters and
/// return detected drift entries.
pub fn detect_policy_drift(
    workspace: &OpenRouterKeyInfo,
    min_remaining_budget_usd: Option<f64>,
    requires_paid_features: bool,
) -> Vec<WorkspacePolicyDrift> {
    let mut drifts = Vec::new();

    // Check budget exhaustion
    if let (Some(remaining), Some(limit)) = (workspace.remaining_usd, workspace.limit_usd) {
        if remaining <= 0.0 {
            drifts.push(WorkspacePolicyDrift::BudgetExhausted {
                usage_usd: workspace.usage_usd,
                limit_usd: limit,
                message: format!(
                    "Workspace budget exhausted: spent ${:.6} of ${:.6} limit",
                    workspace.usage_usd, limit
                ),
            });
        } else if let Some(threshold) = min_remaining_budget_usd.filter(|&t| remaining < t) {
            drifts.push(WorkspacePolicyDrift::BudgetBelowThreshold {
                remaining_usd: remaining,
                threshold_usd: threshold,
                message: format!(
                    "Remaining workspace budget (${remaining:.6}) is below the requested \
                     threshold (${threshold:.6})"
                ),
            });
        }
    }
    // Unlimited budget (no limit set) always passes threshold check — no action needed.

    // Check free-tier vs paid-feature requirements
    if workspace.is_free_tier && requires_paid_features {
        drifts.push(WorkspacePolicyDrift::FreeTierRestriction {
            feature: "paid_tier_routing".to_string(),
            message: "Workspace is on the free tier, which restricts access to paid-only \
                      providers, ZDR endpoints, and data-retention controls. Upgrade to a paid \
                      key to use these features."
                .to_string(),
        });
    }

    drifts
}

// ============================================================================
// Tool: inspect_openrouter_workspace
// ============================================================================

struct InspectOpenRouterWorkspaceTool;

#[async_trait]
impl Tool for InspectOpenRouterWorkspaceTool {
    fn name(&self) -> &str {
        "inspect_openrouter_workspace"
    }

    fn description(&self) -> &str {
        "Fetch OpenRouter workspace/key metadata (budget, rate limits, tier status). \
         Returns structured policy metadata without exposing the API key itself. \
         Use this to understand workspace constraints before configuring model routing."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {},
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "inspect_openrouter_workspace requires provider credentials — use execute_with_context",
        )
    }

    async fn execute_with_context(
        &self,
        _arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        const URL: &str = "https://openrouter.ai/api/v1/auth/key";
        if let Some(acl) = context.network_access.as_ref()
            && !acl.is_url_allowed(URL)
        {
            return ToolExecutionResult::tool_error(
                "OpenRouter workspace API is blocked by session network access policy",
            );
        }

        let api_key = match resolve_openrouter_key(context).await {
            Ok(k) => k,
            Err(e) => return ToolExecutionResult::tool_error(e),
        };

        let client = match reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .build()
        {
            Ok(c) => c,
            Err(e) => {
                return ToolExecutionResult::tool_error(format!(
                    "Failed to build HTTP client: {e}"
                ));
            }
        };
        let response = match client.get(URL).bearer_auth(&api_key).send().await {
            Ok(r) => r,
            Err(e) => {
                return ToolExecutionResult::tool_error(format!(
                    "Failed to reach OpenRouter workspace API: {e}"
                ));
            }
        };

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return ToolExecutionResult::tool_error(format!(
                "OpenRouter /auth/key returned HTTP {status}: {body}"
            ));
        }

        let body: Value = match response.json().await {
            Ok(v) => v,
            Err(e) => {
                return ToolExecutionResult::tool_error(format!(
                    "Failed to parse OpenRouter workspace response: {e}"
                ));
            }
        };

        let data = match body.get("data") {
            Some(d) => d,
            None => {
                return ToolExecutionResult::tool_error(
                    "OpenRouter /auth/key response missing 'data' field",
                );
            }
        };

        let info = match OpenRouterKeyInfo::from_api_response(data) {
            Ok(i) => i,
            Err(e) => return ToolExecutionResult::tool_error(e),
        };

        ToolExecutionResult::Success(json!(info))
    }
}

// ============================================================================
// Tool: check_openrouter_policy_compatibility
// ============================================================================

struct CheckOpenRouterPolicyCompatibilityTool;

#[async_trait]
impl Tool for CheckOpenRouterPolicyCompatibilityTool {
    fn name(&self) -> &str {
        "check_openrouter_policy_compatibility"
    }

    fn description(&self) -> &str {
        "Check whether local routing configuration is compatible with the current OpenRouter \
         workspace policy. Returns a compatibility report listing any detected drift between \
         local settings and upstream workspace constraints (budget, tier, rate limits). \
         Use before finalizing routing config to catch incompatibilities early."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "min_remaining_budget_usd": {
                    "type": "number",
                    "minimum": 0,
                    "description": "Minimum remaining workspace budget (USD) required by your \
                                    routing plan. A drift is reported if the workspace has less \
                                    than this amount remaining. Omit to skip budget-threshold check."
                },
                "requires_paid_features": {
                    "type": "boolean",
                    "description": "Set true if the routing config uses paid-tier features such as \
                                    ZDR endpoints, data-collection controls, or paid-only providers. \
                                    A drift is reported when the workspace is on the free tier.",
                    "default": false
                }
            },
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "check_openrouter_policy_compatibility requires provider credentials — use execute_with_context",
        )
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let min_remaining_budget_usd = arguments
            .get("min_remaining_budget_usd")
            .and_then(|v| v.as_f64())
            .filter(|&v| v >= 0.0);
        let requires_paid_features = arguments
            .get("requires_paid_features")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        const URL: &str = "https://openrouter.ai/api/v1/auth/key";
        if let Some(acl) = context.network_access.as_ref()
            && !acl.is_url_allowed(URL)
        {
            return ToolExecutionResult::tool_error(
                "OpenRouter workspace API is blocked by session network access policy",
            );
        }

        let api_key = match resolve_openrouter_key(context).await {
            Ok(k) => k,
            Err(e) => return ToolExecutionResult::tool_error(e),
        };

        let client = match reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .build()
        {
            Ok(c) => c,
            Err(e) => {
                return ToolExecutionResult::tool_error(format!(
                    "Failed to build HTTP client: {e}"
                ));
            }
        };
        let response = match client.get(URL).bearer_auth(&api_key).send().await {
            Ok(r) => r,
            Err(e) => {
                return ToolExecutionResult::tool_error(format!(
                    "Failed to reach OpenRouter workspace API: {e}"
                ));
            }
        };

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return ToolExecutionResult::tool_error(format!(
                "OpenRouter /auth/key returned HTTP {status}: {body}"
            ));
        }

        let body: Value = match response.json().await {
            Ok(v) => v,
            Err(e) => {
                return ToolExecutionResult::tool_error(format!(
                    "Failed to parse OpenRouter workspace response: {e}"
                ));
            }
        };

        let data = match body.get("data") {
            Some(d) => d,
            None => {
                return ToolExecutionResult::tool_error(
                    "OpenRouter /auth/key response missing 'data' field",
                );
            }
        };

        let workspace = match OpenRouterKeyInfo::from_api_response(data) {
            Ok(i) => i,
            Err(e) => return ToolExecutionResult::tool_error(e),
        };

        let drifts =
            detect_policy_drift(&workspace, min_remaining_budget_usd, requires_paid_features);
        let compatible = drifts.is_empty();

        let report = PolicyCompatibilityReport {
            compatible,
            workspace,
            drifts,
        };

        ToolExecutionResult::Success(json!(report))
    }
}

// ============================================================================
// Credential helper (shared with model_scout pattern)
// ============================================================================

async fn resolve_openrouter_key(context: &ToolContext) -> Result<String, String> {
    let store = context
        .provider_credential_store
        .as_ref()
        .ok_or_else(|| "No provider credential store available".to_string())?;

    let creds = store
        .get_default_provider_credentials("openrouter")
        .await
        .map_err(|e| format!("Failed to resolve OpenRouter credentials: {e}"))?
        .ok_or_else(|| {
            "No OpenRouter provider configured — add an OpenRouter provider to your org".to_string()
        })?;

    Ok(creds.api_key)
}

// ============================================================================
// Tests
// ============================================================================

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

    fn unlimited_key() -> OpenRouterKeyInfo {
        OpenRouterKeyInfo {
            label: "test-key".to_string(),
            usage_usd: 0.05,
            limit_usd: None,
            remaining_usd: None,
            is_free_tier: false,
            rate_limit: Some(OpenRouterRateLimit {
                requests: 200,
                interval: "10s".to_string(),
            }),
        }
    }

    fn capped_key(usage: f64, limit: f64) -> OpenRouterKeyInfo {
        OpenRouterKeyInfo {
            label: "capped-key".to_string(),
            usage_usd: usage,
            limit_usd: Some(limit),
            remaining_usd: Some((limit - usage).max(0.0)),
            is_free_tier: false,
            rate_limit: None,
        }
    }

    fn free_tier_key() -> OpenRouterKeyInfo {
        OpenRouterKeyInfo {
            label: "free-key".to_string(),
            usage_usd: 0.0,
            limit_usd: None,
            remaining_usd: None,
            is_free_tier: true,
            rate_limit: Some(OpenRouterRateLimit {
                requests: 20,
                interval: "1m".to_string(),
            }),
        }
    }

    // -------------------------------------------------------------------------
    // OpenRouterKeyInfo::from_api_response
    // -------------------------------------------------------------------------

    #[test]
    fn parse_unlimited_key_response() {
        let raw = json!({
            "label": "my-key",
            "usage": 12_345,
            "limit": null,
            "is_free_tier": false,
            "rate_limit": { "requests": 200, "interval": "10s" }
        });
        let info = OpenRouterKeyInfo::from_api_response(&raw).unwrap();
        assert_eq!(info.label, "my-key");
        assert!((info.usage_usd - 0.012345).abs() < 1e-9);
        assert!(info.limit_usd.is_none());
        assert!(info.remaining_usd.is_none());
        assert!(!info.is_free_tier);
        assert_eq!(info.rate_limit.as_ref().unwrap().requests, 200);
        assert_eq!(info.rate_limit.as_ref().unwrap().interval, "10s");
    }

    #[test]
    fn parse_capped_key_response() {
        let raw = json!({
            "label": "capped",
            "usage": 500_000,
            "limit": 1_000_000,
            "is_free_tier": false
        });
        let info = OpenRouterKeyInfo::from_api_response(&raw).unwrap();
        assert!((info.usage_usd - 0.5).abs() < 1e-9);
        assert!((info.limit_usd.unwrap() - 1.0).abs() < 1e-9);
        assert!((info.remaining_usd.unwrap() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn parse_exhausted_key_response() {
        let raw = json!({
            "label": "empty",
            "usage": 1_000_000,
            "limit": 1_000_000,
            "is_free_tier": false
        });
        let info = OpenRouterKeyInfo::from_api_response(&raw).unwrap();
        assert!((info.remaining_usd.unwrap()).abs() < 1e-9);
    }

    #[test]
    fn parse_free_tier_key_response() {
        let raw = json!({
            "usage": 0,
            "limit": null,
            "is_free_tier": true,
            "rate_limit": { "requests": 20, "interval": "1m" }
        });
        let info = OpenRouterKeyInfo::from_api_response(&raw).unwrap();
        assert!(info.is_free_tier);
        assert_eq!(info.rate_limit.as_ref().unwrap().requests, 20);
    }

    #[test]
    fn parse_missing_label_uses_default() {
        let raw = json!({ "usage": 0, "is_free_tier": false });
        let info = OpenRouterKeyInfo::from_api_response(&raw).unwrap();
        assert_eq!(info.label, "(unnamed)");
    }

    // -------------------------------------------------------------------------
    // detect_policy_drift
    // -------------------------------------------------------------------------

    #[test]
    fn no_drift_unlimited_key_no_constraints() {
        let drifts = detect_policy_drift(&unlimited_key(), None, false);
        assert!(drifts.is_empty());
    }

    #[test]
    fn no_drift_unlimited_key_with_threshold() {
        // Unlimited budget always passes threshold check.
        let drifts = detect_policy_drift(&unlimited_key(), Some(100.0), false);
        assert!(drifts.is_empty());
    }

    #[test]
    fn drift_budget_exhausted() {
        let key = capped_key(1.0, 1.0);
        let drifts = detect_policy_drift(&key, None, false);
        assert_eq!(drifts.len(), 1);
        assert!(matches!(
            &drifts[0],
            WorkspacePolicyDrift::BudgetExhausted { .. }
        ));
    }

    #[test]
    fn drift_budget_below_threshold() {
        let key = capped_key(0.95, 1.0); // $0.05 remaining
        let drifts = detect_policy_drift(&key, Some(0.10), false);
        assert_eq!(drifts.len(), 1);
        if let WorkspacePolicyDrift::BudgetBelowThreshold {
            remaining_usd,
            threshold_usd,
            ..
        } = &drifts[0]
        {
            assert!((remaining_usd - 0.05).abs() < 1e-9);
            assert!((threshold_usd - 0.10).abs() < 1e-9);
        } else {
            panic!("wrong drift kind");
        }
    }

    #[test]
    fn no_drift_budget_above_threshold() {
        let key = capped_key(0.5, 1.0); // $0.50 remaining
        let drifts = detect_policy_drift(&key, Some(0.10), false);
        assert!(drifts.is_empty());
    }

    #[test]
    fn drift_free_tier_requires_paid() {
        let key = free_tier_key();
        let drifts = detect_policy_drift(&key, None, true);
        assert_eq!(drifts.len(), 1);
        assert!(matches!(
            &drifts[0],
            WorkspacePolicyDrift::FreeTierRestriction { .. }
        ));
    }

    #[test]
    fn no_drift_free_tier_no_paid_requirement() {
        let key = free_tier_key();
        let drifts = detect_policy_drift(&key, None, false);
        assert!(drifts.is_empty());
    }

    #[test]
    fn multiple_drifts_exhausted_and_free_tier() {
        let mut key = capped_key(1.0, 1.0);
        key.is_free_tier = true;
        let drifts = detect_policy_drift(&key, None, true);
        assert_eq!(drifts.len(), 2);
        assert!(
            drifts
                .iter()
                .any(|d| matches!(d, WorkspacePolicyDrift::BudgetExhausted { .. }))
        );
        assert!(
            drifts
                .iter()
                .any(|d| matches!(d, WorkspacePolicyDrift::FreeTierRestriction { .. }))
        );
    }

    #[test]
    fn policy_compatibility_report_serializes() {
        let report = PolicyCompatibilityReport {
            compatible: false,
            workspace: capped_key(1.0, 1.0),
            drifts: vec![WorkspacePolicyDrift::BudgetExhausted {
                usage_usd: 1.0,
                limit_usd: 1.0,
                message: "exhausted".to_string(),
            }],
        };
        let json = serde_json::to_value(&report).unwrap();
        assert_eq!(json["compatible"], false);
        assert_eq!(json["drifts"][0]["kind"], "budget_exhausted");
    }

    #[test]
    fn workspace_policy_drift_messages_are_non_empty() {
        // Verify the `message` field produced by detect_policy_drift is
        // non-empty for every drift kind.
        let key = capped_key(1.0, 1.0);
        let drifts = detect_policy_drift(&key, Some(0.10), true);
        // BudgetExhausted + FreeTierRestriction (key is not free_tier here, so
        // just check exhausted)
        for d in &drifts {
            let msg = match d {
                WorkspacePolicyDrift::BudgetExhausted { message, .. } => message.as_str(),
                WorkspacePolicyDrift::BudgetBelowThreshold { message, .. } => message.as_str(),
                WorkspacePolicyDrift::FreeTierRestriction { message, .. } => message.as_str(),
            };
            assert!(!msg.is_empty(), "drift message should not be empty");
        }
    }
}