lean-ctx 3.12.12

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
// SPDX-License-Identifier: Apache-2.0
//! `lean-ctx session stats|cost --json --session ID`: one app session as a
//! local reader (Cloud Desktop) sees it. The app names its sessions with
//! `LEAN_CTX_SESSION_ID` (and the proxy header `x-leanctx-session-id`);
//! `--session` takes that id or a LeanCTX session id.
//!
//! `session.stats`: the LeanCTX sessions attributed to the id, their token
//! counters, what was kept out of the context (security counts), and waste
//! signals from the activity stream (files read again, failing commands).
//! `session.cost`: the proxy's measured spend of the id.

use std::collections::BTreeMap;

use serde::Serialize;

use lean_ctx::core::activity::{Event, Filter, Kind, Outcome};
use lean_ctx::core::security_events::SecurityCounts;
use lean_ctx::core::session::SessionState;
use lean_ctx_proxy::usage_meter::{self, ModelSpend};

use super::{Code, Failure, rfc3339};

/// Rows of each waste list.
const TOP: usize = 10;

#[derive(Debug, Serialize, PartialEq)]
pub(crate) struct SessionStatsDoc {
    pub session_id: String,
    pub lean_sessions: Vec<String>,
    pub project_root: Option<String>,
    pub started_at: Option<String>,
    pub updated_at: Option<String>,
    pub tokens: Tokens,
    pub tools: Tools,
    pub knowledge: Knowledge,
    pub kept_out: KeptOut,
    pub waste: Waste,
}

#[derive(Debug, Default, Serialize, PartialEq, Eq)]
pub(crate) struct Tokens {
    pub input: u64,
    pub saved: u64,
    pub tool_calls: u64,
    pub cache_hits: u64,
    pub files_read: u64,
    pub commands_run: u64,
}

/// Tool use of the session: `compose` is its `ctx_compose` calls, including
/// those routed through `ctx_call`. The app's Compose share is
/// `tools.compose / tokens.tool_calls`.
#[derive(Debug, Default, Serialize, PartialEq, Eq)]
pub(crate) struct Tools {
    pub compose: u64,
}

/// Knowledge the session wrote: `written` counts its successful
/// `ctx_knowledge` remembers.
#[derive(Debug, Default, Serialize, PartialEq, Eq)]
pub(crate) struct Knowledge {
    pub written: u64,
}

#[derive(Debug, Default, Serialize, PartialEq, Eq)]
pub(crate) struct KeptOut {
    pub total: u64,
    pub secrets_redacted: u64,
    pub pii_redacted: u64,
    pub content_withheld: u64,
    pub shell_blocked: u64,
    pub path_blocked: u64,
    pub injection_flagged: u64,
    pub coverage_incomplete: u64,
}

impl KeptOut {
    fn add(&mut self, c: &SecurityCounts) {
        self.secrets_redacted += c.secrets_redacted;
        self.pii_redacted += c.pii_redacted;
        self.content_withheld += c.content_withheld;
        self.shell_blocked += c.shell_blocked;
        self.path_blocked += c.path_blocked;
        self.injection_flagged += c.injection_flagged;
        self.coverage_incomplete += c.coverage_incomplete;
        self.total = self.secrets_redacted
            + self.pii_redacted
            + self.content_withheld
            + self.shell_blocked
            + self.path_blocked
            + self.injection_flagged
            + self.coverage_incomplete;
    }
}

#[derive(Debug, Default, Serialize, PartialEq, Eq)]
pub(crate) struct Waste {
    pub repeated_reads: RepeatedReads,
    pub failing_commands: FailingCommands,
}

#[derive(Debug, Default, Serialize, PartialEq, Eq)]
pub(crate) struct RepeatedReads {
    pub files: usize,
    pub extra_reads: u64,
    pub top: Vec<ReadRow>,
}

#[derive(Debug, Serialize, PartialEq, Eq)]
pub(crate) struct ReadRow {
    pub path: String,
    pub reads: u64,
}

#[derive(Debug, Default, Serialize, PartialEq, Eq)]
pub(crate) struct FailingCommands {
    pub failures: u64,
    pub top: Vec<CommandRow>,
}

#[derive(Debug, Serialize, PartialEq, Eq)]
pub(crate) struct CommandRow {
    pub command: String,
    pub failures: u64,
    pub last_at: String,
}

/// Files read more than once: per path the larger of LeanCTX's own count
/// (`files_touched`) and the activity stream's `file_read` events.
fn repeated_reads(sessions: &[SessionState], events: &[Event]) -> RepeatedReads {
    let mut lean: BTreeMap<&str, u64> = BTreeMap::new();
    for file in sessions.iter().flat_map(|s| &s.files_touched) {
        *lean.entry(file.path.as_str()).or_default() += u64::from(file.read_count);
    }
    let mut seen: BTreeMap<&str, u64> = BTreeMap::new();
    for event in events.iter().filter(|e| e.kind == Kind::FileRead) {
        if let Some(path) = event.target.as_deref() {
            *seen.entry(path).or_default() += 1;
        }
    }
    for (path, n) in lean {
        let slot = seen.entry(path).or_default();
        *slot = (*slot).max(n);
    }
    let mut rows: Vec<ReadRow> = seen
        .into_iter()
        .filter(|(_, reads)| *reads > 1)
        .map(|(path, reads)| ReadRow {
            path: path.to_owned(),
            reads,
        })
        .collect();
    let files = rows.len();
    let extra_reads = rows.iter().map(|r| r.reads - 1).sum();
    rows.sort_by(|a, b| b.reads.cmp(&a.reads).then_with(|| a.path.cmp(&b.path)));
    rows.truncate(TOP);
    RepeatedReads {
        files,
        extra_reads,
        top: rows,
    }
}

/// Shell events that ended in an error, grouped by command.
fn failing_commands(events: &[Event]) -> FailingCommands {
    let mut by_command: BTreeMap<&str, (u64, &str)> = BTreeMap::new();
    for event in events
        .iter()
        .filter(|e| e.kind == Kind::Shell && e.outcome == Some(Outcome::Error))
    {
        let Some(command) = event.target.as_deref() else {
            continue;
        };
        let slot = by_command.entry(command).or_insert((0, ""));
        slot.0 += 1;
        if event.at.as_str() > slot.1 {
            slot.1 = event.at.as_str();
        }
    }
    let failures = by_command.values().map(|(n, _)| n).sum();
    let mut top: Vec<CommandRow> = by_command
        .into_iter()
        .map(|(command, (failures, last_at))| CommandRow {
            command: command.to_owned(),
            failures,
            last_at: last_at.to_owned(),
        })
        .collect();
    top.sort_by(|a, b| {
        b.failures
            .cmp(&a.failures)
            .then_with(|| b.last_at.cmp(&a.last_at))
            .then_with(|| a.command.cmp(&b.command))
    });
    top.truncate(TOP);
    FailingCommands { failures, top }
}

/// The `session.stats` body of `id` from its sessions (oldest first) and
/// its activity events; `not_found` when neither knows the id.
pub(crate) fn stats_of(
    id: &str,
    sessions: &[SessionState],
    events: &[Event],
) -> Result<SessionStatsDoc, Failure> {
    if sessions.is_empty() && events.is_empty() {
        return Err(Failure::new(
            Code::NotFound,
            format!("no session is known as {id}"),
        ));
    }
    let mut tokens = Tokens::default();
    let mut tools = Tools::default();
    let mut knowledge = Knowledge::default();
    let mut kept_out = KeptOut::default();
    for s in sessions {
        tools.compose += s.stats.compose_calls;
        knowledge.written += s.stats.knowledge_written;
        tokens.input += s.stats.total_tokens_input;
        tokens.saved += s.stats.total_tokens_saved;
        tokens.tool_calls += u64::from(s.stats.total_tool_calls);
        tokens.cache_hits += u64::from(s.stats.cache_hits);
        tokens.files_read += u64::from(s.stats.files_read);
        tokens.commands_run += u64::from(s.stats.commands_run);
        kept_out.add(&s.stats.security);
    }
    let mut lean_sessions: Vec<String> = sessions.iter().map(|s| s.id.clone()).collect();
    lean_sessions.sort();
    Ok(SessionStatsDoc {
        session_id: id.to_owned(),
        lean_sessions,
        project_root: sessions
            .iter()
            .rev()
            .find_map(|s| s.project_root.clone())
            .or_else(|| events.last().map(|e| e.project_root.clone())),
        started_at: sessions.first().map(|s| rfc3339(s.started_at)),
        updated_at: sessions.iter().map(|s| s.updated_at).max().map(rfc3339),
        tokens,
        tools,
        knowledge,
        kept_out,
        waste: Waste {
            repeated_reads: repeated_reads(sessions, events),
            failing_commands: failing_commands(events),
        },
    })
}

#[derive(Debug, Serialize, PartialEq)]
pub(crate) struct SessionCostDoc {
    pub session_id: String,
    pub available: bool,
    pub source: &'static str,
    pub total_usd: f64,
    pub measured_usd: f64,
    pub requests: u64,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_tokens: u64,
    pub cache_write_tokens: u64,
    pub per_model: Vec<CostRow>,
}

#[derive(Debug, Serialize, PartialEq)]
pub(crate) struct CostRow {
    pub model: String,
    pub requests: u64,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_tokens: u64,
    pub cache_write_tokens: u64,
    pub cost_usd: f64,
    pub pricing_estimated: bool,
}

/// USD rounded to 6 decimals, so the same totals print the same bytes.
pub(crate) fn usd(value: f64) -> f64 {
    (value * 1_000_000.0).round() / 1_000_000.0
}

pub(crate) fn cost_row(r: &ModelSpend) -> CostRow {
    CostRow {
        model: r.model.clone(),
        requests: r.requests,
        input_tokens: r.input_tokens,
        output_tokens: r.output_tokens,
        cache_read_tokens: r.cache_read_tokens,
        cache_write_tokens: r.cache_write_tokens,
        cost_usd: usd(r.cost_usd),
        pricing_estimated: r.pricing_estimated,
    }
}

/// The `session.cost` body of `id` from the proxy's rows (`None`: the proxy
/// saw no turn of it). Models sorted by cost desc, then name.
pub(crate) fn cost_of(id: &str, rows: Option<Vec<ModelSpend>>) -> SessionCostDoc {
    let mut rows = rows.unwrap_or_default();
    rows.sort_by(|a, b| {
        b.cost_usd
            .total_cmp(&a.cost_usd)
            .then_with(|| a.model.cmp(&b.model))
    });
    SessionCostDoc {
        session_id: id.to_owned(),
        available: !rows.is_empty(),
        source: "proxy",
        total_usd: usd(rows.iter().map(|r| r.cost_usd).sum()),
        measured_usd: usd(rows.iter().map(|r| r.measured_cost_usd).sum()),
        requests: rows.iter().map(|r| r.requests).sum(),
        input_tokens: rows.iter().map(|r| r.input_tokens).sum(),
        output_tokens: rows.iter().map(|r| r.output_tokens).sum(),
        cache_read_tokens: rows.iter().map(|r| r.cache_read_tokens).sum(),
        cache_write_tokens: rows.iter().map(|r| r.cache_write_tokens).sum(),
        per_model: rows.iter().map(cost_row).collect(),
    }
}

/// `--session ID`, validated like the app's id.
fn session_arg(args: &[String]) -> Result<String, Failure> {
    super::flag(args, "--session")?
        .and_then(lean_ctx::core::activity::session_id)
        .ok_or_else(|| Failure::invalid("--session <id> is required (1-128 of [A-Za-z0-9._:-])"))
}

/// The read and shell events of `ids` (newest kept per id).
fn events_of(ids: &[&str]) -> Vec<Event> {
    let Some(store) = lean_ctx::core::activity::store() else {
        return Vec::new();
    };
    let mut events: Vec<Event> = Vec::new();
    for id in ids {
        let filter = Filter {
            session: Some((*id).to_owned()),
            project_root: None,
            since: None,
            kinds: vec![Kind::FileRead, Kind::Shell],
            limit: lean_ctx::core::activity::MAX_LIMIT,
        };
        if let Ok(listing) = store.list(&filter) {
            events.extend(listing.events);
        }
    }
    events.sort_by(|a, b| a.at.cmp(&b.at).then_with(|| a.seq.cmp(&b.seq)));
    events.dedup();
    events
}

/// `session stats --json --session ID`.
pub(crate) fn build_stats(args: &[String]) -> Result<SessionStatsDoc, Failure> {
    let id = session_arg(args)?;
    let sessions = SessionState::load_attributed(&id);
    let mut ids: Vec<&str> = vec![id.as_str()];
    ids.extend(sessions.iter().map(|s| s.id.as_str()).filter(|s| *s != id));
    let events = events_of(&ids);
    stats_of(&id, &sessions, &events)
}

/// `session cost --json --session ID`.
pub(crate) fn build_cost(args: &[String]) -> Result<SessionCostDoc, Failure> {
    let id = session_arg(args)?;
    lean_ctx::core::gain::live_pricing::ensure_loaded();
    Ok(cost_of(&id, usage_meter::persisted_session(&id)))
}

/// `session stats|cost --json …`.
pub(crate) fn run(action: &str, args: &[String]) {
    let kind = if action == "cost" {
        "session.cost"
    } else {
        "session.stats"
    };
    super::kinds::run(kind, args);
}
#[cfg(test)]
mod tests {
    use super::*;
    use lean_ctx::core::activity::Source;

    fn event(kind: Kind, target: &str, outcome: Option<Outcome>, at: &str) -> Event {
        Event {
            seq: 1,
            at: at.into(),
            session_id: "app-1".into(),
            agent: "claude".into(),
            project_root: "/p".into(),
            kind,
            source: Source::Hook,
            tool: None,
            target: Some(target.into()),
            outcome,
            text: None,
            truncated: false,
        }
    }

    #[test]
    fn stats_sum_sessions_and_derive_waste_from_activity() {
        let mut a = SessionState::new();
        a.id = "lean-b".into();
        a.project_root = Some("/p".into());
        a.stats.total_tokens_input = 100;
        a.stats.total_tokens_saved = 60;
        a.stats.security.secrets_redacted = 2;
        a.files_touched.push(lean_ctx::core::session::FileTouched {
            path: "src/a.rs".into(),
            file_ref: None,
            read_count: 3,
            modified: false,
            last_mode: "full".into(),
            tokens: 0,
            stale: false,
            context_item_id: None,
            summary: None,
        });
        let mut b = SessionState::new();
        b.id = "lean-a".into();
        b.stats.total_tokens_input = 50;
        b.stats.security.content_withheld = 1;
        let events = vec![
            event(
                Kind::FileRead,
                "src/a.rs",
                Some(Outcome::Ok),
                "2026-11-04T09:00:00.000Z",
            ),
            event(
                Kind::FileRead,
                "src/b.rs",
                Some(Outcome::Ok),
                "2026-11-04T09:00:01.000Z",
            ),
            event(
                Kind::FileRead,
                "src/b.rs",
                Some(Outcome::Ok),
                "2026-11-04T09:00:02.000Z",
            ),
            event(
                Kind::Shell,
                "cargo test",
                Some(Outcome::Error),
                "2026-11-04T09:01:00.000Z",
            ),
            event(
                Kind::Shell,
                "cargo test",
                Some(Outcome::Error),
                "2026-11-04T09:02:00.000Z",
            ),
            event(
                Kind::Shell,
                "ls",
                Some(Outcome::Ok),
                "2026-11-04T09:03:00.000Z",
            ),
        ];
        let doc = stats_of("app-1", &[a, b], &events).expect("known");
        assert_eq!(doc.lean_sessions, ["lean-a", "lean-b"]);
        assert_eq!((doc.tokens.input, doc.tokens.saved), (150, 60));
        assert_eq!((doc.kept_out.total, doc.kept_out.content_withheld), (3, 1));
        assert_eq!(doc.project_root.as_deref(), Some("/p"));
        let reads = &doc.waste.repeated_reads;
        assert_eq!((reads.files, reads.extra_reads), (2, 3));
        assert_eq!(
            reads.top[0],
            ReadRow {
                path: "src/a.rs".into(),
                reads: 3
            }
        );
        let failing = &doc.waste.failing_commands;
        assert_eq!(failing.failures, 2);
        assert_eq!(failing.top[0].last_at, "2026-11-04T09:02:00.000Z");
        assert_eq!(
            stats_of("nobody", &[], &[]).map(|_| ()).unwrap_err().code,
            Code::NotFound
        );
    }

    #[test]
    fn cost_without_proxy_turns_is_unavailable_and_zero() {
        let doc = cost_of("app-1", None);
        assert!(!doc.available);
        assert_eq!((doc.total_usd, doc.requests), (0.0, 0));
        assert!(doc.per_model.is_empty());
    }
}

#[cfg(test)]
mod session_stats_tests {
    //! rel12 WP2: `session.stats` carries `tools.compose` and
    //! `knowledge.written` per app session, additively.
    use super::*;
    use serde_json::{Value, json};

    /// A session record whose stats come from JSON, the way a saved session
    /// is read back (a record from before the counters has none).
    fn session(id: &str, app: &str, stats: Value) -> SessionState {
        let mut s = SessionState::new();
        s.id = id.into();
        s.app_session_id = Some(app.into());
        s.stats = serde_json::from_value(stats).expect("session stats");
        s
    }

    #[test]
    fn the_doc_adds_compose_calls_and_knowledge_writes_beside_tokens() {
        let a = session(
            "lean-a",
            "app-1",
            json!({"total_tool_calls": 8, "compose_calls": 3, "knowledge_written": 2}),
        );
        let b = session(
            "lean-b",
            "app-1",
            json!({"total_tool_calls": 4, "compose_calls": 1}),
        );
        let doc = serde_json::to_value(stats_of("app-1", &[a, b], &[]).expect("known")).unwrap();
        assert_eq!(doc["tools"], json!({"compose": 4}), "{doc}");
        assert_eq!(doc["knowledge"], json!({"written": 2}), "{doc}");
        // Additive: every earlier field keeps its name and place.
        let mut tokens: Vec<&str> = doc["tokens"]
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        tokens.sort_unstable();
        assert_eq!(
            tokens,
            [
                "cache_hits",
                "commands_run",
                "files_read",
                "input",
                "saved",
                "tool_calls"
            ]
        );
        assert_eq!(doc["tokens"]["tool_calls"], 12);
        assert!(
            doc["tools"]["compose"].as_u64() <= doc["tokens"]["tool_calls"].as_u64(),
            "tools.compose is a subset of tokens.tool_calls: {doc}"
        );
        for field in [
            "session_id",
            "lean_sessions",
            "project_root",
            "started_at",
            "updated_at",
            "kept_out",
            "waste",
        ] {
            assert!(doc.get(field).is_some(), "{field} missing: {doc}");
        }
    }

    #[test]
    fn a_session_saved_before_the_counters_counts_zero_and_keeps_its_bytes() {
        let old = json!({"total_tool_calls": 5, "files_read": 2});
        let record = session("lean-old", "app-old", old);
        // Read back and written again, an old record gains no field.
        let again = serde_json::to_value(&record.stats).unwrap();
        assert!(again.get("compose_calls").is_none(), "{again}");
        assert!(again.get("knowledge_written").is_none(), "{again}");
        let doc =
            serde_json::to_value(stats_of("app-old", &[record], &[]).expect("known")).unwrap();
        assert_eq!(doc["tools"]["compose"], 0, "{doc}");
        assert_eq!(doc["knowledge"]["written"], 0, "{doc}");
        // A counted record keeps its counters through a save.
        let counted = session(
            "lean-new",
            "app-new",
            json!({"compose_calls": 2, "knowledge_written": 1}),
        );
        let again = serde_json::to_value(&counted.stats).unwrap();
        assert_eq!(again["compose_calls"], 2, "{again}");
        assert_eq!(again["knowledge_written"], 1, "{again}");
    }

    #[test]
    fn each_app_session_including_an_acp_one_reads_only_its_own_counters() {
        let _data = lean_ctx::core::data_dir::isolated_data_dir();
        let project = tempfile::tempdir().unwrap();
        let root = project
            .path()
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .into_owned();
        let cases = [
            ("lean-cli-1", "app-1", 3, 1),
            ("lean-cli-2", "app-2", 7, 0),
            ("lean-acp-1", "acp:claude.sess-1", 2, 4),
        ];
        for (id, app, compose, written) in cases {
            let mut s = session(
                id,
                app,
                json!({"total_tool_calls": 10, "compose_calls": compose,
                       "knowledge_written": written}),
            );
            s.project_root = Some(root.clone());
            s.save().expect("session saved");
        }
        for (id, app, compose, written) in cases {
            let args = ["--session".to_owned(), app.to_owned()];
            let doc = serde_json::to_value(build_stats(&args).expect("known")).unwrap();
            assert_eq!(doc["lean_sessions"], json!([id]), "{app}: {doc}");
            assert_eq!(doc["tools"], json!({"compose": compose}), "{app}: {doc}");
            assert_eq!(
                doc["knowledge"],
                json!({"written": written}),
                "{app}: {doc}"
            );
        }
    }
}