lean-ctx 3.12.8

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
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
// SPDX-License-Identifier: Apache-2.0
//! The cockpit's view of Cloud engine metrics (telemetry SPEC §7, §10):
//!
//! - `GET /api/cloud/workspace?range=&group=&resolution=&instance=self` returns the
//!   Insights of the workspace this engine is enrolled in. Cloud computes them
//!   (`GET /v1/metrics/insights`, C0 2.0 `metrics.schema.json#/$defs/insights_response`)
//!   with the engine's own credentials, as its owner's member view. An engine
//!   that is not enrolled answers `{connected: false}` and makes **no network
//!   call**. Cloud being unreachable, the lease lapsing or a refusal is an
//!   `error` the page shows; the dashboard never fails over it.
//! - `GET /api/cloud/explained` serves the "Numbers explained" page (K9): the
//!   formula, trust label and local source of every metric, plus the price
//!   table and the fallback price this engine prices spend with. It is local,
//!   and Cloud links the same text.

use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};

use serde_json::{Value, json};

use lean_ctx_cloud::auth::Session;
use lean_ctx_cloud::state::InstanceRecord;
use lean_ctx_cloud::{CloudError, CloudStore};
use lean_ctx_protocol::cloud::lease::LeaseState;

use super::helpers::extract_query_param;

const RANGES: [&str; 5] = ["24h", "7d", "30d", "90d", "365d"];
const GROUPS: [&str; 4] = ["total", "instance", "person", "vault"];
const RESOLUTIONS: [&str; 3] = ["hour", "day", "week"];
const INSIGHTS_SCHEMA: &str = "leanctx.cloud.insights/v1";
/// One call's budget, token mint included; the page stays responsive offline.
const BUDGET: Duration = Duration::from_secs(10);
/// SPEC §7: the engine caches an answer for 5 minutes.
const CACHE_FOR: Duration = Duration::from_secs(300);

static CACHE: Mutex<Vec<(String, Instant, Value)>> = Mutex::new(Vec::new());

pub(super) fn handle(
    path: &str,
    query: &str,
    method: &str,
    _body: &str,
) -> Option<(&'static str, &'static str, String)> {
    if !method.eq_ignore_ascii_case("GET") {
        return None;
    }
    match path {
        "/api/cloud/workspace" => Some(workspace(query)),
        "/api/cloud/explained" => Some(ok(&explained())),
        _ => None,
    }
}

fn ok(value: &Value) -> (&'static str, &'static str, String) {
    ("200 OK", "application/json", value.to_string())
}

/// The Insights request the page asked for, from closed sets only.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Request {
    range: &'static str,
    group: &'static str,
    resolution: Option<&'static str>,
    own_engine: bool,
}

impl Request {
    fn parse(query: &str) -> Result<Self, &'static str> {
        fn pick(
            query: &str,
            key: &'static str,
            allowed: &[&'static str],
            default: Option<&'static str>,
        ) -> Result<Option<&'static str>, &'static str> {
            match extract_query_param(query, key) {
                None => Ok(default),
                Some(value) => allowed
                    .iter()
                    .find(|a| **a == value)
                    .copied()
                    .map(Some)
                    .ok_or(key),
            }
        }
        let range = pick(query, "range", &RANGES, Some("7d"))?.unwrap_or("7d");
        let group = pick(query, "group", &GROUPS, Some("total"))?.unwrap_or("total");
        let resolution = pick(query, "resolution", &RESOLUTIONS, None)?;
        let own_engine = pick(query, "instance", &["self"], None)?.is_some();
        Ok(Self {
            range,
            group,
            resolution,
            own_engine,
        })
    }

    /// The engine route (`/v1` is the client's base).
    fn path(&self) -> String {
        let mut path = format!(
            "/metrics/insights?range={}&group={}",
            self.range, self.group
        );
        if let Some(resolution) = self.resolution {
            path.push_str("&resolution=");
            path.push_str(resolution);
        }
        if self.own_engine {
            path.push_str("&instance=self");
        }
        path
    }
}

fn workspace(query: &str) -> (&'static str, &'static str, String) {
    let request = match Request::parse(query) {
        Ok(request) => request,
        Err(field) => {
            return (
                "400 Bad Request",
                "application/json",
                json!({ "error": { "code": "invalid_field", "field": field } }).to_string(),
            );
        }
    };
    let store = match CloudStore::open() {
        Ok(store) => store,
        Err(error) => return ok(&local_failure(&error)),
    };
    let config = lean_ctx::core::config::Config::load().cloud;
    if config.enabled == Some(false) {
        return ok(&json!({ "connected": false, "disabled": true }));
    }
    let instance = match store.instance() {
        Ok(instance) => instance,
        Err(error) => return ok(&local_failure(&error)),
    };
    let key = instance
        .as_ref()
        .map(|i| format!("{}\0{}", i.instance_id, request.path()));
    if let Some(key) = &key
        && let Some(hit) = cached(key)
    {
        return ok(&hit);
    }
    let answer = answer(instance.as_ref(), || fetch(&store, &config, &request));
    if let Some(key) = key
        && answer.get("insights").is_some()
    {
        remember(key, answer.clone());
    }
    ok(&answer)
}

fn cached(key: &str) -> Option<Value> {
    let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner);
    cache.retain(|(_, at, _)| at.elapsed() < CACHE_FOR);
    cache
        .iter()
        .find(|(k, _, _)| k == key)
        .map(|(_, _, v)| v.clone())
}

fn remember(key: String, value: Value) {
    let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner);
    cache.retain(|(k, at, _)| *k != key && at.elapsed() < CACHE_FOR);
    // Bounded: ranges × groups × resolutions × engine filter.
    if cache.len() >= 64 {
        cache.remove(0);
    }
    cache.push((key, Instant::now(), value));
}

fn local_failure(error: &CloudError) -> Value {
    json!({ "connected": false, "error": { "code": "local_state", "message": error.to_string() } })
}

/// One authenticated, time-bounded `GET /v1/metrics/insights`.
fn fetch(
    store: &CloudStore,
    config: &lean_ctx_cloud::CloudConfig,
    request: &Request,
) -> Result<Value, CloudError> {
    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
    let root = lean_ctx_cloud::root_cert::trust_root(store, config, &instance.url)?;
    let session = Session::load(store.clone(), root)?;
    if !matches!(
        session.lease.state_at(lean_ctx_time::UtcDateTime::now()),
        LeaseState::Valid | LeaseState::Grace
    ) {
        return Err(CloudError::LeaseLapsed);
    }
    session
        .bounded_client(Instant::now() + BUDGET)?
        .get(&request.path())
}

/// The page's answer. Without an enrolment `fetch` is never called: no
/// network while not connected (SPEC §10).
fn answer(
    instance: Option<&InstanceRecord>,
    fetch: impl FnOnce() -> Result<Value, CloudError>,
) -> Value {
    let Some(instance) = instance else {
        return json!({ "connected": false });
    };
    let mut answer = json!({
        "connected": true,
        "workspace": {
            "label": instance.workspace_label(),
            "kind": instance.org_kind,
            "web_url": instance.web_url,
        },
    });
    match fetch() {
        Ok(insights) if insights.get("schema").and_then(Value::as_str) == Some(INSIGHTS_SCHEMA) => {
            answer["insights"] = insights;
        }
        Ok(_) => {
            answer["error"] = json!({
                "code": "unavailable",
                "message": "LeanCTX Cloud answered without instance Insights; it may predate this feature.",
            });
        }
        Err(error) => {
            answer["error"] = json!({ "code": error_code(&error), "message": error.to_string() });
            // Cloud answered: a locked workspace (`trial_ended`/`plan_ended`) is
            // a state the page shows, not a failure; the reason is structured.
            if let CloudError::PlanRequired(need) = &error
                && let Some(reason) = need.locked()
            {
                answer["error"]["reason"] = json!(reason);
                answer["error"]["locked"] = json!(true);
            }
        }
    }
    answer
}

fn error_code(error: &CloudError) -> &'static str {
    match error {
        CloudError::Offline(_) => "offline",
        CloudError::NotConnected => "not_connected",
        CloudError::Unauthorized => "unauthorized",
        CloudError::LeaseLapsed => "lease_lapsed",
        CloudError::Revoked(_) => "revoked",
        CloudError::Forbidden => "forbidden",
        CloudError::PolicyDenied(_) => "policy_denied",
        CloudError::PlanRequired(_) => "plan_required",
        CloudError::QuotaExceeded(_) => "quota_exceeded",
        CloudError::StorageFull(_) => "storage_quota_exceeded",
        CloudError::UploadRateLimited { .. } => "upload_rate_limited",
        _ => "unavailable",
    }
}

// ---------------------------------------------------------------- K9

/// Every metric of the contract (`metrics.schema.json#/$defs/metric_name`) with
/// its trust label (`labels`, K7), formula and local source. The order is the
/// contract's.
pub(crate) const METRICS: &[(&str, &str, &str, &str)] = &[
    (
        "tokens.input",
        "estimated",
        "Tokens the agent would have received without LeanCTX (the baseline).",
        "savings ledger: baseline_tokens",
    ),
    (
        "tokens.output",
        "measured",
        "Tokens LeanCTX actually delivered to the agent.",
        "savings ledger: actual_tokens",
    ),
    (
        "tokens.saved",
        "estimated",
        "tokens.input − tokens.output, after bounce corrections.",
        "savings ledger: saved_tokens − bounce_adjustment",
    ),
    (
        "savings.measured",
        "measured",
        "Saved tokens whose evidence class is measured (counted by a local tokenizer).",
        "savings ledger: evidence_class = measured",
    ),
    (
        "savings.estimated",
        "estimated",
        "Saved tokens that rest on an estimate (approximated, statistical, declared or unclassified evidence).",
        "savings ledger: evidence_class ≠ measured",
    ),
    (
        "savings.estimated_low",
        "estimated",
        "Lower end of the range of savings.estimated.",
        "savings ledger: confidence",
    ),
    (
        "savings.estimated_high",
        "estimated",
        "Upper end of the range of savings.estimated.",
        "savings ledger: confidence",
    ),
    (
        "savings.evidenced",
        "evidenced",
        "The part of the savings backed by a gateway receipt or provider reconciliation.",
        "savings ledger: measurement_method = provider_reconciled, receipts",
    ),
    (
        "savings.overhead",
        "measured",
        "Tokens LeanCTX itself added (instructions, tool schemas, hints). Net own savings = savings.measured + savings.estimated − savings.overhead, and may be negative. The provider cache is not part of it (ledger.cache_discount).",
        "instance instruction and schema counters",
    ),
    (
        "calls.tool_calls",
        "measured",
        "Tool calls through LeanCTX.",
        "savings ledger events",
    ),
    (
        "calls.cache_reads",
        "measured",
        "Re-reads that could be served from the read cache.",
        "stats: cep.total_cache_reads",
    ),
    (
        "calls.cache_hits",
        "measured",
        "Re-reads served from the read cache. Cache-hit rate = cache_hits ÷ cache_reads.",
        "stats: cep.total_cache_hits",
    ),
    (
        "compression.original",
        "measured",
        "Tokens of tool output before compression.",
        "stats: cep.total_tokens_original",
    ),
    (
        "compression.compressed",
        "measured",
        "Tokens of tool output after compression. Compression = 1 − compressed ÷ original.",
        "stats: cep.total_tokens_compressed",
    ),
    (
        "ledger.reduction",
        "estimated",
        "Savings from shortening context.",
        "savings ledger kind: reduction",
    ),
    (
        "ledger.cache_discount",
        "measured",
        "The provider's cache discount the proxy observed; not LeanCTX's own saving.",
        "savings ledger kind: proxy cache",
    ),
    (
        "ledger.correction",
        "estimated",
        "Corrections for content the agent had to fetch again.",
        "savings ledger kind: bounce correction",
    ),
    (
        "ledger.edit",
        "estimated",
        "Savings from edit tools.",
        "savings ledger kind: edit",
    ),
    (
        "ledger.other",
        "estimated",
        "Every other ledger entry.",
        "savings ledger kind: other",
    ),
    (
        "guards.secrets_redacted",
        "measured",
        "Secrets replaced before the model saw them.",
        "audit trail: secret_redacted",
    ),
    (
        "guards.pii_redacted",
        "measured",
        "PII values masked by the gateway.",
        "audit trail: pii_redacted",
    ),
    (
        "guards.injection_flags",
        "measured",
        "Tool outputs flagged for prompt injection.",
        "audit trail: injection_flagged",
    ),
    (
        "guards.content_withheld",
        "measured",
        "Sources the gateway withheld.",
        "audit trail: content_withheld",
    ),
    (
        "guards.paths_blocked",
        "measured",
        "Paths outside the project jail that were refused.",
        "audit trail: path_blocked",
    ),
    (
        "guards.shell_blocked",
        "measured",
        "Shell commands the allowlist refused.",
        "audit trail: shell_blocked",
    ),
    (
        "guards.partial_inspections",
        "measured",
        "Sources delivered although a detector did not inspect all of them.",
        "audit trail: coverage_incomplete",
    ),
    (
        "policy.blocked",
        "measured",
        "Refusals by rules in force, per rule.",
        "gateway decisions",
    ),
    (
        "policy.would_block",
        "measured",
        "Refusals a rule in monitor mode would make, before it goes live.",
        "gateway decisions (monitor)",
    ),
    (
        "refetch.truncated",
        "measured",
        "Outputs shortened by a filter (read mode or compression pattern).",
        "truncation pointers",
    ),
    (
        "refetch.refetched",
        "measured",
        "Shortened outputs the agent fetched back in full. Re-fetch rate = refetched ÷ truncated.",
        "ctx_expand of a truncation pointer",
    ),
    (
        "unregulated.calls",
        "measured",
        "Calls no enforcing rule covers: programs a command ran, tool calls of a host family without an intercepting hook, and calls relayed to MCP servers.",
        "the gateway's decision record: no enforcing rule matched",
    ),
    (
        "sessions.started",
        "measured",
        "Agent sessions started.",
        "session store",
    ),
    (
        "hosts.tool_calls",
        "measured",
        "Tool calls per agent host.",
        "session store: client",
    ),
    (
        "spend.requests",
        "measured",
        "Model requests where the instance measures spend.",
        "proxy usage meter, host logs",
    ),
    (
        "spend.input_tokens",
        "measured",
        "Model input tokens.",
        "proxy usage meter, host logs",
    ),
    (
        "spend.output_tokens",
        "measured",
        "Model output tokens.",
        "proxy usage meter, host logs",
    ),
    (
        "spend.cached_tokens",
        "measured",
        "Model input tokens served from the provider cache.",
        "proxy usage meter, host logs",
    ),
    (
        "spend.usd_micros",
        "estimated",
        "Cost at list price (tokens × price table below, the fallback price for unknown models); estimated · list price, never an invoice.",
        "price table",
    ),
    (
        "knowledge.facts_current",
        "measured",
        "Knowledge facts in the vault at the end of the period (a level, not a sum).",
        "knowledge store",
    ),
    (
        "instances.active",
        "derived",
        // Word for word the golden records/metrics_fields.json.
        "Instances that reported at least one hour in the period (Cloud only).",
        "Cloud",
    ),
];

/// K7 trust labels, worded exactly like the Cockpit chip (`static/ui/badge.js`).
const LABELS: &[(&str, &str)] = &[
    (
        "measured",
        "Counted by the instance on this device; reproducible.",
    ),
    (
        "estimated",
        "Rests on a model or a price table; shown with its range where one exists.",
    ),
    (
        "evidenced",
        "Backed by a signed receipt, the hash-chained ledger or the provider's own figures.",
    ),
    ("derived", "Computed from other figures."),
];

fn explained() -> Value {
    let pricing = lean_ctx::core::gain::model_pricing::ModelPricing::load();
    let fallback = pricing.quote(None);
    let mut prices: Vec<Value> = pricing
        .rows()
        .into_iter()
        .filter(|(model, _)| *model != fallback.model_key)
        .map(|(model, cost)| price(model, &cost))
        .collect();
    prices.sort_by(|a, b| a["model"].as_str().cmp(&b["model"].as_str()));
    json!({
        "labels": LABELS.iter().map(|(label, meaning)| json!({ "label": label, "meaning": meaning })).collect::<Vec<_>>(),
        "metrics": METRICS.iter().map(|(name, label, formula, source)| json!({
            "name": name, "label": label, "formula": formula, "source": source,
        })).collect::<Vec<_>>(),
        "prices": prices,
        "fallback": price(&fallback.model_key, &fallback.cost),
        "price_unit": "USD per 1M tokens",
    })
}

fn price(model: &str, cost: &lean_ctx::core::gain::model_pricing::ModelCost) -> Value {
    json!({
        "model": model,
        "input": cost.input_per_m,
        "output": cost.output_per_m,
        "cache_write": cost.cache_write_per_m,
        "cache_read": cost.cache_read_per_m,
    })
}

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

    const SCHEMA: &str = include_str!(
        "../../../../lean-ctx-protocol/tests/fixtures/cloud-v2/schemas/metrics.schema.json"
    );
    const ENGINE_VIEW: &str = include_str!(
        "../../../../lean-ctx-protocol/tests/fixtures/cloud-v2/routes/metrics_insights.response.json"
    );

    fn instance() -> InstanceRecord {
        InstanceRecord {
            instance_id: "inst_5d1f3b7a9c2e4f6a8b0d1c3e5f7a9b2d".into(),
            org_id: "org_1".into(),
            org_name: "Platform".into(),
            label: "ada-mbp".into(),
            url: "https://cloud.leanctx.com".into(),
            org_salt_id: "salt".into(),
            enrolled_at: "2026-10-02T07:00:00Z".into(),
            web_url: Some("https://cloud.leanctx.com".into()),
            org_kind: Some("team".into()),
            company_name: None,
        }
    }

    #[test]
    fn not_connected_makes_no_network_call() {
        let answer = answer(None, || panic!("fetched while not connected"));
        assert_eq!(answer, json!({ "connected": false }));
    }

    #[test]
    fn the_contract_answer_passes_and_anything_else_is_an_error() {
        let insights: Value = serde_json::from_str(ENGINE_VIEW).unwrap();
        let shown = answer(Some(&instance()), || Ok(insights.clone()));
        assert_eq!(shown["connected"], true);
        assert_eq!(shown["workspace"]["label"], "Team Platform");
        assert_eq!(shown["insights"], insights);
        assert!(shown.get("error").is_none());

        let old = answer(Some(&instance()), || Ok(json!({ "items": [] })));
        assert_eq!(old["error"]["code"], "unavailable");
        assert!(old.get("insights").is_none());

        let offline = answer(Some(&instance()), || {
            Err(CloudError::Offline("connect refused".into()))
        });
        assert_eq!(offline["error"]["code"], "offline");
        let lapsed = answer(Some(&instance()), || Err(CloudError::LeaseLapsed));
        assert_eq!(lapsed["error"]["code"], "lease_lapsed");
        assert!(lapsed["error"].get("locked").is_none());
    }

    #[test]
    fn a_locked_workspace_carries_its_reason_and_one_line() {
        let need = |reason: &str| {
            CloudError::PlanRequired(Box::new(lean_ctx_cloud::error::PlanNeed {
                feature: Some("read_only".into()),
                plan_needed: Some("personal".into()),
                reason: Some(reason.into()),
                ..Default::default()
            }))
        };
        let locked = answer(Some(&instance()), || Err(need("trial_ended")));
        assert_eq!(locked["connected"], true);
        assert_eq!(locked["error"]["code"], "plan_required");
        assert_eq!(locked["error"]["reason"], "trial_ended");
        assert_eq!(locked["error"]["locked"], true);
        assert_eq!(
            locked["error"]["message"],
            "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again."
        );
        assert_eq!(locked["workspace"]["web_url"], "https://cloud.leanctx.com");
        let ended = answer(Some(&instance()), || Err(need("plan_ended")));
        assert_eq!(ended["error"]["reason"], "plan_ended");
        // `no_plan` is not a lock: the plain refusal, without the flag.
        let none = answer(Some(&instance()), || Err(need("no_plan")));
        assert_eq!(none["error"]["code"], "plan_required");
        assert!(none["error"].get("locked").is_none());
    }

    #[test]
    fn only_closed_parameters_reach_cloud() {
        assert_eq!(
            Request::parse("").unwrap().path(),
            "/metrics/insights?range=7d&group=total"
        );
        assert_eq!(
            Request::parse("range=24h&group=instance&resolution=hour&instance=self")
                .unwrap()
                .path(),
            "/metrics/insights?range=24h&group=instance&resolution=hour&instance=self"
        );
        assert_eq!(Request::parse("range=1y"), Err("range"));
        assert_eq!(Request::parse("group=workspace"), Err("group"));
        assert_eq!(Request::parse("instance=inst_1"), Err("instance"));
        assert_eq!(Request::parse("resolution=minute"), Err("resolution"));
        assert_eq!(Request::parse("range=7d%26x%3D1"), Err("range"));
    }

    #[test]
    fn the_explained_table_is_the_contracts_metric_list_with_its_labels() {
        let schema: Value = serde_json::from_str(SCHEMA).unwrap();
        let names: Vec<&str> = schema["$defs"]["metric_name"]["enum"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        let ours: Vec<&str> = METRICS.iter().map(|m| m.0).collect();
        assert_eq!(ours, names, "same names, same order");
        let labels: Vec<&str> = schema["$defs"]["trust_label"]["enum"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert_eq!(LABELS.iter().map(|l| l.0).collect::<Vec<_>>(), labels);
        // The labels Cloud sends are the ones this page explains.
        let view: Value = serde_json::from_str(ENGINE_VIEW).unwrap();
        for (name, label, formula, source) in METRICS {
            assert_eq!(view["labels"][name], *label, "{name}");
            assert!(!formula.is_empty() && !source.is_empty(), "{name}");
        }
    }

    #[test]
    fn explained_lists_prices_and_the_fallback() {
        let page = explained();
        assert_eq!(page["metrics"].as_array().unwrap().len(), METRICS.len());
        assert!(!page["prices"].as_array().unwrap().is_empty());
        assert_eq!(page["fallback"]["model"], "fallback-blended");
        assert!(page["fallback"]["input"].as_f64().unwrap() > 0.0);
    }

    /// K9: the formulas Cloud shows (`records/metrics_fields.json`) are this
    /// page's, word for word.
    #[test]
    fn the_formulas_are_the_contracts_field_list() {
        let fields: Value = serde_json::from_str(include_str!(
            "../../../../lean-ctx-protocol/tests/fixtures/cloud-v2/records/metrics_fields.json"
        ))
        .unwrap();
        let theirs: Vec<(&str, &str, &str, &str)> = fields["metrics"]
            .as_array()
            .unwrap()
            .iter()
            .map(|m| {
                (
                    m["name"].as_str().unwrap(),
                    m["label"].as_str().unwrap(),
                    m["formula"].as_str().unwrap(),
                    m["source"].as_str().unwrap(),
                )
            })
            .collect();
        assert_eq!(theirs, METRICS.to_vec());
    }
}