lean-ctx-cloud 3.12.9

The LeanCTX Cloud connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
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
// SPDX-License-Identifier: Apache-2.0
//! How Cloud helped in a project (X4), per Cloud project and UTC day, as
//! engine metrics v2 sample it: counts and durations only.
//! `<data>/cloud/metrics/cloud-use.json`, 0600, the last
//! `KEEP_DAYS` days.
//!
//! - M1 `knowledge_hits_referenced`: Cloud facts an agent asked for and got
//!   (a recall that delivered facts pulled from a Cloud vault).
//! - M2 `task_usage`: what the project's host sessions recorded (tokens,
//!   list price) while this machine held a task's claim, from the claim to
//!   its release, result or loss, per UTC minute; a minute in which several
//!   claims were held is shared among them, so no usage counts twice.
//! - M5 `first_context_ms`: per session, the time from its start to the
//!   first Cloud knowledge it delivered.
//!
//! Recording never fails a caller: a write that does not happen is a count
//! that is missing, never an error in a tool.

use std::collections::{BTreeMap, HashSet};
use std::path::Path;
use std::sync::Mutex;

use lean_ctx_time::UtcDateTime;
use serde::{Deserialize, Serialize};

use crate::state::{CloudStore, write_private};
use lean_ctx_protocol::cloud::telemetry::MetricsTaskUsageV1;

const FILE: &str = "cloud-use.json";
/// Serializes the read-modify-write of [`FILE`] across processes.
const LOCK_FILE: &str = "cloud-use.lock";
/// Days kept; an upload never reaches further back.
const KEEP_DAYS: i64 = 62;
/// First-context samples kept per project and day.
const MAX_SAMPLES: usize = 256;

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
struct DayUse {
    #[serde(default)]
    hits: u64,
    #[serde(default)]
    first_context_ms: Vec<u64>,
}

/// One claim this machine held: `[from, to]`, open while held.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct ClaimWindow {
    /// On disk as `project_id` (pre-VA name) for downgrades and mixed-version teams.
    #[serde(rename = "project_id", alias = "vault_id")]
    vault_id: String,
    number: u64,
    from: UtcDateTime,
    #[serde(default)]
    to: Option<UtcDateTime>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
struct CloudUse {
    /// day → project id → use.
    #[serde(default)]
    days: BTreeMap<String, BTreeMap<String, DayUse>>,
    #[serde(default)]
    claims: Vec<ClaimWindow>,
}

static LOCK: Mutex<()> = Mutex::new(());

fn dir(data_dir: &Path) -> std::path::PathBuf {
    data_dir.join("metrics")
}

fn load(data_dir: &Path) -> CloudUse {
    std::fs::read(dir(data_dir).join(FILE))
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or_default()
}

fn change(data_dir: &Path, now: UtcDateTime, edit: impl FnOnce(&mut CloudUse)) {
    let _guard = LOCK
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    // Every MCP server and CLI of this machine records here: without the
    // file lock two of them would drop each other's counts.
    if std::fs::create_dir_all(dir(data_dir)).is_err() {
        return;
    }
    let Ok(_file_lock) = lean_ctx::core::agents::FileLock::acquire(&dir(data_dir).join(LOCK_FILE))
    else {
        return;
    };
    let mut state = load(data_dir);
    edit(&mut state);
    let oldest = (now - lean_ctx_time::Duration::days(KEEP_DAYS))
        .date_naive()
        .to_string();
    state.days.retain(|day, _| *day >= oldest);
    let cutoff = now - lean_ctx_time::Duration::days(KEEP_DAYS);
    state
        .claims
        .retain(|claim| claim.to.is_none_or(|to| to >= cutoff));
    if let Ok(bytes) = serde_json::to_vec(&state) {
        let _ = write_private(&dir(data_dir), FILE, &bytes);
    }
}

fn day_of(at: UtcDateTime) -> String {
    at.date_naive().to_string()
}

/// The Cloud project of a local root, when it is linked.
fn project_of(store: &CloudStore, project_root: &str) -> Option<String> {
    // An unlinked folder counts nothing for the vault, also not through its
    // main checkout's record (bd 40060).
    let map = crate::vault::VaultMap::load(store.data_dir());
    crate::unlinked::shared_record(store.data_dir(), &map, project_root).map(|p| p.vault_id.clone())
}

pub use lean_ctx::core::knowledge::import_tag::is_cloud_fact;

/// Sessions whose first Cloud context is recorded (once per session).
fn first_seen() -> &'static Mutex<HashSet<String>> {
    static SEEN: std::sync::OnceLock<Mutex<HashSet<String>>> = std::sync::OnceLock::new();
    SEEN.get_or_init(|| Mutex::new(HashSet::new()))
}

/// A delivery to an agent in `project_root` handed it `cloud_facts` facts
/// from the Cloud repo. `asked`: the agent asked for knowledge (a recall),
/// which counts as a hit (M1); every delivery may be the session's first
/// Cloud context (M5).
pub fn record_delivery(
    project_root: &str,
    session: Option<(&str, UtcDateTime)>,
    cloud_facts: usize,
    asked: bool,
) {
    if cloud_facts == 0 {
        return;
    }
    let Ok(store) = CloudStore::open() else {
        return;
    };
    if !matches!(store.instance(), Ok(Some(_))) {
        return;
    }
    let Some(vault_id) = project_of(&store, project_root) else {
        return;
    };
    let now = UtcDateTime::now();
    let first = session.and_then(|(id, started)| {
        first_seen()
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(id.to_owned())
            .then(|| u64::try_from((now - started).num_milliseconds()).unwrap_or(0))
    });
    if !asked && first.is_none() {
        return;
    }
    record_at(
        store.data_dir(),
        &vault_id,
        now,
        asked.then_some(cloud_facts),
        first,
    );
}

fn record_at(
    data_dir: &Path,
    vault_id: &str,
    now: UtcDateTime,
    hits: Option<usize>,
    first_context_ms: Option<u64>,
) {
    change(data_dir, now, |state| {
        let day = state
            .days
            .entry(day_of(now))
            .or_default()
            .entry(vault_id.to_owned())
            .or_default();
        if let Some(hits) = hits {
            day.hits = day.hits.saturating_add(hits as u64);
        }
        if let Some(ms) = first_context_ms
            && day.first_context_ms.len() < MAX_SAMPLES
        {
            day.first_context_ms.push(ms);
        }
    });
}

/// This machine claimed task `number` of `vault_id` at `at` (M2).
pub fn claim_started(data_dir: &Path, vault_id: &str, number: u64, at: UtcDateTime) {
    change(data_dir, at, |state| {
        if !state
            .claims
            .iter()
            .any(|c| c.vault_id == vault_id && c.number == number && c.to.is_none())
        {
            state.claims.push(ClaimWindow {
                vault_id: vault_id.to_owned(),
                number,
                from: at,
                to: None,
            });
        }
    });
}

/// The claim on task `number` ended at `at` (released, submitted, lost).
pub fn claim_ended(data_dir: &Path, vault_id: &str, number: u64, at: UtcDateTime) {
    change(data_dir, at, |state| {
        for claim in state
            .claims
            .iter_mut()
            .filter(|c| c.vault_id == vault_id && c.number == number && c.to.is_none())
        {
            claim.to = Some(at);
        }
    });
}

/// M2 rows per task number: the usage of `[start, end)` per minute,
/// shared among the claims held in it.
fn task_rows(
    claims: &[ClaimWindow],
    vault_id: &str,
    start: UtcDateTime,
    end: UtcDateTime,
    now: UtcDateTime,
    usage: &WindowUsage<'_>,
) -> BTreeMap<u64, MetricsTaskUsageV1> {
    let pricing = lean_ctx::core::gain::model_pricing::ModelPricing::load();
    let mut tasks: BTreeMap<u64, MetricsTaskUsageV1> = BTreeMap::new();
    for (from, to, numbers) in segments(claims, vault_id, start, end, now) {
        // `usage` counts whole minutes, both ends included.
        for (model, input, output, write, read) in
            usage(from, to - lean_ctx_time::Duration::minutes(1))
        {
            let usd = pricing
                .quote(Some(model.as_str()))
                .cost
                .estimate_usd(input, output, write, read);
            let micros = (usd * 1_000_000.0).round().max(0.0) as u64;
            let n = numbers.len() as u64;
            for (i, number) in (0u64..).zip(&numbers) {
                let row = tasks.entry(*number).or_insert(MetricsTaskUsageV1 {
                    number: *number,
                    input_tokens: 0,
                    output_tokens: 0,
                    list_usd_micros: 0,
                });
                row.input_tokens = row.input_tokens.saturating_add(share(input + write, n, i));
                row.output_tokens = row.output_tokens.saturating_add(share(output, n, i));
                row.list_usd_micros = row.list_usd_micros.saturating_add(share(micros, n, i));
            }
        }
    }
    tasks
}

/// C9: what the project's host sessions recorded since this machine claimed
/// task `number` (its open claim), at list price: the engine's own measure
/// of a task's cost, so a budget never rests on what an agent reports.
/// `None` while no claim is open or nothing was recorded.
pub(crate) fn claim_usage(
    data_dir: &Path,
    vault_id: &str,
    number: u64,
    now: UtcDateTime,
    usage: &WindowUsage<'_>,
) -> Option<lean_ctx_protocol::cloud::tasks::UsageV1> {
    let state = load(data_dir);
    let from = state
        .claims
        .iter()
        .filter(|c| c.vault_id == vault_id && c.number == number && c.to.is_none())
        .map(|c| c.from)
        .min()?;
    let end = now + lean_ctx_time::Duration::minutes(1);
    let row = task_rows(&state.claims, vault_id, from, end, now, usage).remove(&number)?;
    let tokens = row.input_tokens.saturating_add(row.output_tokens);
    (tokens > 0).then_some(lean_ctx_protocol::cloud::tasks::UsageV1 {
        tokens,
        usd_micros: Some(row.list_usd_micros),
    })
}

/// [`WindowUsage`] over the host session files under `roots` in `home`; a
/// session under a deeper root of `others` belongs to that project.
pub(crate) fn host_window<'a>(
    home: &'a Path,
    roots: &'a [String],
    others: &'a [String],
    now: UtcDateTime,
) -> impl Fn(UtcDateTime, UtcDateTime) -> Vec<(String, u64, u64, u64, u64)> + 'a {
    move |from, to| {
        lean_ctx_apps::core::dashboard_pro::host_usage::usage_between(
            home, roots, others, now, from, to,
        )
        .into_iter()
        .map(|(model, c)| {
            let n = |v: i64| u64::try_from(v).unwrap_or(0);
            (
                model,
                n(c.input),
                n(c.output),
                n(c.cache_write),
                n(c.cache_read),
            )
        })
        .collect()
    }
}

/// The `i`-th of `n` shares of `total`; the shares add up to `total`.
fn share(total: u64, n: u64, i: u64) -> u64 {
    total / n + u64::from(i < total % n)
}

/// The claims of `vault_id` cut into minute segments of `[start, end)`:
/// `(from, to, claims held)` with `to` exclusive and at least one claim.
/// A claim covers the minutes from that of its start through that of its
/// end (`now` while held); two claims that meet in a minute share it.
fn segments(
    claims: &[ClaimWindow],
    vault_id: &str,
    start: UtcDateTime,
    end: UtcDateTime,
    now: UtcDateTime,
) -> Vec<(UtcDateTime, UtcDateTime, Vec<u64>)> {
    use lean_ctx_time::UtcDateTime;
    let minute = lean_ctx_time::Duration::minutes(1);
    let floor = |t: UtcDateTime| t.duration_trunc(minute).unwrap_or(t);
    let windows: Vec<(u64, UtcDateTime, UtcDateTime)> = claims
        .iter()
        .filter(|c| c.vault_id == vault_id)
        .map(|c| {
            (
                c.number,
                floor(c.from).max(start),
                (floor(c.to.unwrap_or(now)) + minute).min(end),
            )
        })
        .filter(|(_, from, to)| from < to)
        .collect();
    let mut edges: Vec<UtcDateTime> = windows.iter().flat_map(|w| [w.1, w.2]).collect();
    edges.sort_unstable();
    edges.dedup();
    edges
        .windows(2)
        .filter_map(|pair| {
            let (from, to) = (pair[0], pair[1]);
            let mut held: Vec<u64> = windows
                .iter()
                .filter(|(_, a, b)| *a <= from && to <= *b)
                .map(|(number, _, _)| *number)
                .collect();
            held.sort_unstable();
            held.dedup();
            (!held.is_empty()).then_some((from, to, held))
        })
        .collect()
}

/// Usage per model in a window: `(model, input, output, cache_write, cache_read)`.
pub(crate) type WindowUsage<'a> =
    dyn Fn(UtcDateTime, UtcDateTime) -> Vec<(String, u64, u64, u64, u64)> + 'a;

/// The day's cumulative Cloud use of `vault_id` (engine metrics v2 samples
/// it hourly): facts used and the first-context samples so far.
pub(crate) fn day_counters(cloud_data: &Path, vault_id: &str, date: &str) -> (u64, Vec<u64>) {
    load(cloud_data)
        .days
        .get(date)
        .and_then(|projects| projects.get(vault_id))
        .map(|day| (day.hits, day.first_context_ms.clone()))
        .unwrap_or_default()
}

/// Ledger usage per held task of `vault_id` in `[start, end)` (engine
/// metrics v2, one hour), sorted by number, tasks with usage only.
pub(crate) fn window_tasks(
    cloud_data: &Path,
    vault_id: &str,
    start: UtcDateTime,
    end: UtcDateTime,
    now: UtcDateTime,
    usage: &WindowUsage<'_>,
) -> Vec<MetricsTaskUsageV1> {
    let state = load(cloud_data);
    task_rows(&state.claims, vault_id, start, end, now, usage)
        .into_values()
        .filter(|row| row.input_tokens + row.output_tokens > 0)
        .collect()
}

#[cfg(test)]
#[path = "cloud_use_tests.rs"]
mod tests;

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

    /// `ClaimWindow` of the engine before the VA rename.
    #[derive(Deserialize)]
    #[allow(dead_code)]
    struct PreVaClaimWindow {
        project_id: String,
        number: u64,
        from: UtcDateTime,
        #[serde(default)]
        to: Option<UtcDateTime>,
    }

    #[test]
    fn claim_windows_keep_pre_va_names() {
        let old = r#"{"project_id":"v1","number":7,"from":"2026-10-22T10:00:00Z"}"#;
        let read = crate::vault::assert_pre_va_round_trip::<ClaimWindow, PreVaClaimWindow>(
            old,
            "project_id",
            "vault_id",
        );
        assert_eq!((read.vault_id.as_str(), read.number), ("v1", 7));
    }
}