Skip to main content

lean_ctx_cloud/
cpao.rs

1// SPDX-License-Identifier: Apache-2.0
2//! LeanCTX Cloud cost per accepted outcome (`GET /v1/cpao`, contract W2):
3//! what the team's agents cost over the last 7 and 30 days, divided by the
4//! outcomes that were accepted (a landed merge request or an accepted task
5//! result), for a local reader such as LeanCTX Code.
6//!
7//! Read only from a server that announced the `cpao` capability
8//! ([`FEATURE_CPAO`], cached by [`crate::session_ref`]); an older server gets
9//! no request. The cloud answers:
10//! - `200 {schema: leanctx.cloud.cpao/v1, periods: […]}` → [`CloudCpaoV1`];
11//! - `503 not_configured`, or `404` from a cloud without the route → not
12//!   available (`Ok(None)`);
13//! - `403` → [`CloudError::Forbidden`]; [`answer`] also says which refusal
14//!   it was ([`Refusal`]).
15//!
16//! The answer is passed on as the cloud computed it: this module never
17//! derives a number. It checks the schema and drops periods and agent rows
18//! that are malformed, so one bad row does not hide the rest. When the
19//! server does not answer, the last answer of that server is returned with
20//! `live: false` (kept in `<data>/cpao.json`).
21
22use serde::{Deserialize, Serialize};
23use serde_json::Value;
24
25use lean_ctx_time::UtcDateTime;
26
27use crate::CloudError;
28use crate::config::CloudConfig;
29use crate::state::{CloudStore, write_private};
30
31/// The `features` entry of a server that serves `GET /v1/cpao`.
32pub const FEATURE_CPAO: &str = "cpao";
33
34/// `schema` of the answer.
35pub const CPAO_SCHEMA: &str = "leanctx.cloud.cpao/v1";
36
37/// The cloud route (under `/v1`).
38const PATH: &str = "/cpao";
39/// Largest answer read.
40const MAX_ANSWER_BYTES: usize = 256 * 1024;
41/// The periods a reader knows.
42const PERIODS: [&str; 2] = ["7d", "30d"];
43/// Most agent rows kept per period.
44const MAX_AGENTS: usize = 64;
45/// Longest agent name accepted.
46const MAX_AGENT_LEN: usize = 64;
47/// The last answer.
48const CPAO_FILE: &str = "cpao.json";
49
50/// One agent's share of a period.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct CpaoAgentV1 {
53    /// `claude`, `codex`, `cursor`, …
54    pub agent: String,
55    /// Millionths of a US dollar; `null` while the cloud does not price per
56    /// agent (passed on as `null`, never as `0`).
57    pub cost_usd_micros: Option<u64>,
58    pub accepted_outcomes: u64,
59}
60
61/// One period of the answer.
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct CpaoPeriodV1 {
64    /// `7d` or `30d`.
65    pub period: String,
66    /// What the agents cost in the period, in millionths of a US dollar.
67    pub cost_usd_micros: u64,
68    /// Landed merge requests and accepted task results.
69    pub accepted_outcomes: u64,
70    /// Cost per accepted outcome as the cloud computed it; `null` without one.
71    pub cpao_usd_micros: Option<u64>,
72    /// Change against the period before, in percent, when the cloud sent it.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub trend_pct: Option<f64>,
75    /// `true`: the period's revert window has closed (the figures are not
76    /// frozen: a later revert still lowers the count); `false`: provisional,
77    /// the window is still open. Left out when the cloud did not say.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub settled: Option<bool>,
80    /// By agent, when the cloud sent it.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub by_agent: Option<Vec<CpaoAgentV1>>,
83}
84
85/// `GET /v1/cpao`, checked.
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87pub struct CloudCpaoV1 {
88    pub schema: String,
89    pub periods: Vec<CpaoPeriodV1>,
90}
91
92/// An answer and when it was read.
93#[derive(Debug, Clone, PartialEq)]
94pub struct CpaoRead {
95    pub cpao: CloudCpaoV1,
96    /// When the answer was read (RFC 3339).
97    pub as_of: Option<String>,
98    /// Read just now (`false`: the last answer; the server did not answer).
99    pub live: bool,
100}
101
102#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
103#[serde(default)]
104struct Cache {
105    /// The origin that answered; another enrolled server reads none of it.
106    server: String,
107    fetched_at: Option<String>,
108    cpao: Option<CloudCpaoV1>,
109}
110
111/// Whether the enrolled server announced `cpao` when last asked.
112#[must_use]
113pub fn announced(store: &CloudStore) -> bool {
114    crate::session_ref::announced(store, FEATURE_CPAO)
115}
116
117/// Which refusal a `403` of `GET /v1/cpao` was.
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub enum Refusal {
120    /// The person's role in the team may not see the team's costs
121    /// (`forbidden` naming a team `required_role`).
122    Role,
123    /// Any other refusal, with the server's message when it sent one.
124    Other(Option<String>),
125}
126
127impl Refusal {
128    fn of(body: &Value) -> Self {
129        let error = &body["error"];
130        let team_role = error["required_role"]
131            .as_str()
132            .is_some_and(|role| !role.is_empty() && role != "company_admin");
133        if error["code"].as_str() == Some("forbidden") && team_role {
134            Self::Role
135        } else {
136            Self::Other(
137                error["message"]
138                    .as_str()
139                    .and_then(crate::error::safe_message),
140            )
141        }
142    }
143}
144
145/// The CPAO for a reader: read now, else the last answer of this server.
146/// `None` when the server did not announce `cpao` (no request is sent) or
147/// answered that it does not offer it. A refusal (`403`) is never answered
148/// from the last answer; it is [`CloudError::Forbidden`].
149pub fn read(
150    store: &CloudStore,
151    config: &CloudConfig,
152    now: UtcDateTime,
153) -> Result<Option<CpaoRead>, CloudError> {
154    answer(store, config, now)?.map_err(|_| CloudError::Forbidden)
155}
156
157/// [`read`], with a refusal (`403`) as the inner error that says which one.
158pub fn answer(
159    store: &CloudStore,
160    config: &CloudConfig,
161    now: UtcDateTime,
162) -> Result<Result<Option<CpaoRead>, Refusal>, CloudError> {
163    if !announced(store) {
164        return Ok(Ok(None));
165    }
166    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
167    let mut refusal = None;
168    let live = crate::scheduler::connected_session(store, config).and_then(|session| {
169        let (status, body) = session.with_client(|client| {
170            let (status, body) = client.send_answer("GET", PATH, None, MAX_ANSWER_BYTES)?;
171            // A refused token goes through the session's refresh.
172            if status == 401 {
173                return Err(CloudError::from_response(status, &body));
174            }
175            Ok((status, body))
176        })?;
177        if status == 403 {
178            refusal = Some(Refusal::of(&body));
179        }
180        classify(status, &body)
181    });
182    if let Some(refusal) = refusal {
183        return Ok(Err(refusal));
184    }
185    let mut cache = load_for(store, &instance.url);
186    let read = match live {
187        Ok(Some(cpao)) => {
188            cache.cpao = Some(cpao.clone());
189            cache.fetched_at = Some(stamp(now));
190            save(store, &cache);
191            Ok(Some(CpaoRead {
192                cpao,
193                as_of: cache.fetched_at,
194                live: true,
195            }))
196        }
197        Ok(None) => Ok(None),
198        Err(error) if matches!(error, CloudError::Offline(_)) || error.is_transient() => {
199            match cache.cpao {
200                Some(cpao) => Ok(Some(CpaoRead {
201                    cpao,
202                    as_of: cache.fetched_at,
203                    live: false,
204                })),
205                None => Err(error),
206            }
207        }
208        Err(error) => Err(error),
209    };
210    read.map(Ok)
211}
212
213/// The answer of `status` and `body`: the checked document, `None` for a
214/// cloud that does not offer it, or the error.
215fn classify(status: u16, body: &Value) -> Result<Option<CloudCpaoV1>, CloudError> {
216    let code = body["error"]["code"].as_str().unwrap_or_default();
217    match status {
218        200 => decode(body).map(Some),
219        503 if code == "not_configured" => Ok(None),
220        404 if code.is_empty() || code == "not_found" => Ok(None),
221        403 => Err(CloudError::Forbidden),
222        _ => Err(CloudError::from_response(status, body)),
223    }
224}
225
226/// The checked document: the schema must match and `periods` must be a
227/// list; malformed periods and agent rows are left out, never repaired.
228fn decode(body: &Value) -> Result<CloudCpaoV1, CloudError> {
229    let bad = |why: &str| CloudError::Protocol(format!("cpao: {why}"));
230    if body["schema"].as_str() != Some(CPAO_SCHEMA) {
231        return Err(bad(&format!("schema must be {CPAO_SCHEMA}")));
232    }
233    let periods = body["periods"]
234        .as_array()
235        .ok_or_else(|| bad("periods is not a list"))?;
236    let mut kept: Vec<CpaoPeriodV1> = Vec::new();
237    for raw in periods {
238        let Some(period) = period(raw) else { continue };
239        // One row per period; the first wins.
240        if kept.iter().all(|p| p.period != period.period) {
241            kept.push(period);
242        }
243    }
244    Ok(CloudCpaoV1 {
245        schema: CPAO_SCHEMA.to_string(),
246        periods: kept,
247    })
248}
249
250/// A wire period as sent; required members typed, optional ones loose.
251#[derive(Deserialize)]
252struct WirePeriod {
253    period: String,
254    cost_usd_micros: u64,
255    accepted_outcomes: u64,
256    #[serde(default)]
257    cpao_usd_micros: Option<u64>,
258    #[serde(default)]
259    trend_pct: Option<Value>,
260    #[serde(default)]
261    settled: Option<Value>,
262    #[serde(default)]
263    by_agent: Option<Value>,
264}
265
266fn period(raw: &Value) -> Option<CpaoPeriodV1> {
267    let wire: WirePeriod = serde_json::from_value(raw.clone()).ok()?;
268    if !PERIODS.contains(&wire.period.as_str()) {
269        return None;
270    }
271    // A cost per outcome without any outcome is a broken row.
272    if wire.accepted_outcomes == 0 && wire.cpao_usd_micros.is_some() {
273        return None;
274    }
275    let trend_pct = match wire.trend_pct {
276        None | Some(Value::Null) => None,
277        Some(v) => Some(v.as_f64().filter(|t| t.is_finite())?),
278    };
279    let by_agent = match wire.by_agent {
280        None | Some(Value::Null) => None,
281        Some(Value::Array(rows)) => {
282            let mut agents: Vec<CpaoAgentV1> = Vec::new();
283            for row in &rows {
284                let Some(agent) = agent(row) else { continue };
285                if agents.len() < MAX_AGENTS && agents.iter().all(|a| a.agent != agent.agent) {
286                    agents.push(agent);
287                }
288            }
289            Some(agents)
290        }
291        Some(_) => return None,
292    };
293    Some(CpaoPeriodV1 {
294        period: wire.period,
295        cost_usd_micros: wire.cost_usd_micros,
296        accepted_outcomes: wire.accepted_outcomes,
297        cpao_usd_micros: wire.cpao_usd_micros,
298        trend_pct,
299        // An older cloud sends no `settled`; anything but a bool is unknown.
300        settled: wire.settled.and_then(|v| v.as_bool()),
301        by_agent,
302    })
303}
304
305fn agent(raw: &Value) -> Option<CpaoAgentV1> {
306    let agent: CpaoAgentV1 = serde_json::from_value(raw.clone()).ok()?;
307    let name_ok = !agent.agent.is_empty()
308        && agent.agent.len() <= MAX_AGENT_LEN
309        && agent.agent.bytes().all(|b| {
310            b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-' | b'.')
311        });
312    name_ok.then_some(agent)
313}
314
315fn stamp(at: UtcDateTime) -> String {
316    at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
317}
318
319/// The cache of `server`; another server's starts empty.
320fn load_for(store: &CloudStore, server: &str) -> Cache {
321    let cache: Cache = std::fs::read(store.data_dir().join(CPAO_FILE))
322        .ok()
323        .and_then(|b| serde_json::from_slice(&b).ok())
324        .unwrap_or_default();
325    if cache.server == server {
326        cache
327    } else {
328        Cache {
329            server: server.to_string(),
330            ..Cache::default()
331        }
332    }
333}
334
335fn save(store: &CloudStore, cache: &Cache) {
336    if let Ok(bytes) = serde_json::to_vec_pretty(cache) {
337        let _ = write_private(store.data_dir(), CPAO_FILE, &bytes);
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344    use serde_json::json;
345
346    fn answer() -> Value {
347        json!({
348            "schema": CPAO_SCHEMA,
349            "periods": [
350                {"period": "7d", "cost_usd_micros": 12_500_000u64, "accepted_outcomes": 5,
351                 "cpao_usd_micros": 2_500_000u64, "trend_pct": -12.5,
352                 "by_agent": [
353                     {"agent": "claude", "cost_usd_micros": 10_000_000u64, "accepted_outcomes": 4},
354                     {"agent": "codex", "cost_usd_micros": 2_500_000u64, "accepted_outcomes": 1}
355                 ]},
356                {"period": "30d", "cost_usd_micros": 0, "accepted_outcomes": 0,
357                 "cpao_usd_micros": null}
358            ]
359        })
360    }
361
362    #[test]
363    fn the_answer_is_passed_on_as_the_cloud_computed_it() {
364        let cpao = classify(200, &answer()).expect("ok").expect("some");
365        assert_eq!(cpao.schema, CPAO_SCHEMA);
366        assert_eq!(cpao.periods.len(), 2);
367        let week = &cpao.periods[0];
368        assert_eq!(week.period, "7d");
369        assert_eq!(week.cpao_usd_micros, Some(2_500_000));
370        assert_eq!(week.trend_pct, Some(-12.5));
371        let agents = week.by_agent.as_ref().expect("agents");
372        assert_eq!(agents[0].agent, "claude");
373        assert_eq!(agents[0].cost_usd_micros, Some(10_000_000));
374        assert_eq!(agents[1].accepted_outcomes, 1);
375        let month = serde_json::to_value(&cpao.periods[1]).expect("json");
376        // no outcome: the cost per outcome stays null, nothing is derived
377        assert!(month["cpao_usd_micros"].is_null());
378        assert!(month.get("trend_pct").is_none());
379        assert!(month.get("by_agent").is_none());
380    }
381
382    /// LeanCTX Cloud's answer as it sends it (p37 !150): it does not price per
383    /// agent yet, so every agent row carries `cost_usd_micros: null`.
384    fn cloud_fixture() -> Value {
385        serde_json::from_str(include_str!(
386            "../../lean-ctx-protocol/tests/fixtures/cloud/cpao.response.json"
387        ))
388        .expect("fixture")
389    }
390
391    #[test]
392    fn the_cloud_answer_keeps_agent_rows_without_a_cost() {
393        let cpao = classify(200, &cloud_fixture()).expect("ok").expect("some");
394        assert_eq!(cpao.periods.len(), 2);
395        for period in &cpao.periods {
396            let agents = period.by_agent.as_ref().expect("agents");
397            assert!(!agents.is_empty(), "{}: agent rows kept", period.period);
398            assert!(agents.iter().all(|a| a.cost_usd_micros.is_none()));
399        }
400        let week = &cpao.periods[0];
401        assert_eq!(week.cost_usd_micros, 42_000_000);
402        assert_eq!(week.cpao_usd_micros, Some(3_500_000));
403        let agents = week.by_agent.as_ref().expect("agents");
404        assert_eq!(
405            agents.iter().map(|a| a.agent.as_str()).collect::<Vec<_>>(),
406            ["claude", "codex", "unknown"]
407        );
408        assert_eq!(agents[0].accepted_outcomes, 7);
409        // passed on as null, never as 0
410        let json = serde_json::to_value(week).expect("json");
411        assert!(json["by_agent"][0]["cost_usd_micros"].is_null());
412        assert_eq!(cpao.periods[1].trend_pct, None);
413        assert_eq!(week.settled, Some(false));
414    }
415
416    #[test]
417    fn settled_is_passed_on_true_false_or_missing() {
418        let with = |settled: Value| {
419            let mut raw = answer();
420            match settled {
421                Value::Null => {}
422                v => raw["periods"][0]["settled"] = v,
423            }
424            let cpao = decode(&raw).expect("decoded");
425            assert_eq!(cpao.periods.len(), 2, "the period is kept");
426            let json = serde_json::to_value(&cpao.periods[0]).expect("json");
427            (cpao.periods[0].settled, json.get("settled").cloned())
428        };
429        assert_eq!(with(json!(true)), (Some(true), Some(json!(true))));
430        assert_eq!(with(json!(false)), (Some(false), Some(json!(false))));
431        // an older cloud does not send it: unknown, left out of the JSON
432        assert_eq!(with(Value::Null), (None, None));
433        // not a bool: unknown, the period still counts
434        assert_eq!(with(json!("yes")), (None, None));
435        // a cache written before `settled` existed still reads
436        let old: CpaoPeriodV1 = serde_json::from_value(json!({
437            "period": "7d", "cost_usd_micros": 1, "accepted_outcomes": 1,
438            "cpao_usd_micros": 1
439        }))
440        .expect("old cache");
441        assert_eq!(old.settled, None);
442    }
443
444    #[test]
445    fn malformed_periods_and_agents_are_left_out() {
446        let mut raw = answer();
447        raw["later"] = json!(1);
448        let periods = raw["periods"].as_array_mut().expect("list");
449        periods[0]["by_agent"]
450            .as_array_mut()
451            .expect("agents")
452            .extend([
453                json!({"agent": "Bad Name", "cost_usd_micros": 1, "accepted_outcomes": 1}),
454                json!({"agent": "cursor", "cost_usd_micros": -1, "accepted_outcomes": 1}),
455                json!({"agent": "claude", "cost_usd_micros": 9, "accepted_outcomes": 9}),
456                json!("cursor"),
457            ]);
458        periods.extend([
459            json!({"period": "90d", "cost_usd_micros": 1, "accepted_outcomes": 1}),
460            json!({"period": "7d", "cost_usd_micros": 1, "accepted_outcomes": 1}),
461            json!({"period": "30d", "cost_usd_micros": "1", "accepted_outcomes": 1}),
462            json!({"period": "30d", "cost_usd_micros": 1, "accepted_outcomes": 0,
463                   "cpao_usd_micros": 5}),
464            json!({"period": "30d", "cost_usd_micros": 1, "accepted_outcomes": 1,
465                   "trend_pct": "up"}),
466            json!(null),
467        ]);
468        let cpao = decode(&raw).expect("decoded");
469        assert_eq!(cpao, decode(&answer()).expect("clean"));
470    }
471
472    #[test]
473    fn another_schema_or_no_period_list_is_refused() {
474        let mut raw = answer();
475        raw["schema"] = "leanctx.cloud.cpao/v2".into();
476        assert!(classify(200, &raw).is_err());
477        assert!(classify(200, &json!({"schema": CPAO_SCHEMA})).is_err());
478    }
479
480    #[test]
481    fn a_cloud_without_cpao_is_not_available_and_a_refusal_is_forbidden() {
482        let err = |code: &str| json!({"error": {"code": code}});
483        assert_eq!(classify(503, &err("not_configured")).expect("off"), None);
484        assert_eq!(classify(404, &Value::Null).expect("older cloud"), None);
485        assert!(matches!(
486            classify(403, &err("forbidden")),
487            Err(CloudError::Forbidden)
488        ));
489        assert!(matches!(
490            classify(403, &Value::Null),
491            Err(CloudError::Forbidden)
492        ));
493        // a real outage is not "not configured"
494        assert!(classify(503, &Value::Null).is_err());
495        assert!(classify(500, &err("internal")).is_err());
496    }
497
498    #[test]
499    fn only_a_team_role_refusal_is_a_role_refusal() {
500        // what Cloud answers when the role may not see the team's costs
501        let role = json!({"error": {"code": "forbidden", "message": "this needs the admin role", "required_role": "admin"}});
502        assert_eq!(Refusal::of(&role), Refusal::Role);
503        // a company-reserved action names another role: its own words stay
504        let company = json!({"error": {"code": "forbidden", "message": "only a Company admin does this", "required_role": "company_admin"}});
505        assert_eq!(
506            Refusal::of(&company),
507            Refusal::Other(Some("only a Company admin does this".into()))
508        );
509        // another code keeps the server's message, made safe for a terminal
510        let other =
511            json!({"error": {"code": "sso_required", "message": "sign in\u{1b}[31m with SSO"}});
512        assert_eq!(
513            Refusal::of(&other),
514            Refusal::Other(Some("sign in [31m with SSO".into()))
515        );
516        // no role named, no body: no reason is made up
517        let bare = json!({"error": {"code": "forbidden"}});
518        assert_eq!(Refusal::of(&bare), Refusal::Other(None));
519        assert_eq!(Refusal::of(&Value::Null), Refusal::Other(None));
520    }
521
522    #[test]
523    fn a_person_without_a_team_reads_as_not_available_not_as_an_error() {
524        // local-read-v1 §31: no team → Cloud answers 503 not_configured → available:false.
525        let no_team = json!({"error": {"code": "not_configured", "message": "no team"}});
526        assert_eq!(classify(503, &no_team).expect("not available"), None);
527    }
528
529    #[test]
530    fn at_most_64_agent_rows_per_period_are_kept() {
531        let rows: Vec<Value> = (0..100)
532            .map(
533                |i| json!({"agent": format!("a{i}"), "cost_usd_micros": 1, "accepted_outcomes": 1}),
534            )
535            .collect();
536        let raw = json!({"schema": CPAO_SCHEMA, "periods": [
537            {"period": "7d", "cost_usd_micros": 100, "accepted_outcomes": 100,
538             "cpao_usd_micros": 1, "by_agent": rows}
539        ]});
540        let cpao = decode(&raw).expect("decoded");
541        let agents = cpao.periods[0].by_agent.as_ref().expect("agents");
542        assert_eq!(agents.len(), MAX_AGENTS);
543        assert_eq!(agents[0].agent, "a0");
544        assert_eq!(agents[MAX_AGENTS - 1].agent, "a63");
545    }
546
547    #[test]
548    fn an_older_server_gets_no_request() {
549        let dir = tempfile::tempdir().expect("dir");
550        let store = CloudStore::at(dir.path().join("config"), dir.path().join("cloud"));
551        let now = UtcDateTime::parse_from_rfc3339("2026-11-18T12:00:00Z").expect("time");
552        assert_eq!(
553            read(&store, &CloudConfig::default(), now).expect("read"),
554            None
555        );
556        assert!(!store.data_dir().join(CPAO_FILE).exists());
557    }
558}