ultron-session-core 1.0.0

One session's runtime, shared by every mode through the session worker: the rlm lane (model, provider, system prompt, the single rlm tool), the composition root of its host stack, the format-4 run journal, session naming, Pi read views, and the session actor
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
//! The session's runtime counters (`ultron/session-stats.ts`): what the runtime sees while a session runs and no
//! other session value keeps, for the session report (`/usage`, `ultron usage`). They are the session value
//! `ultron.module/stats`, written as the TypeScript recorder writes it, so either implementation reads the other's.
//!
//! Cells are counted where they run (every lane's `rlm` tool), host requests where the kernels make them, guard
//! outcomes as the file hooks record them, steers as they are queued for the root, refused work as the usage ledger
//! refuses it, merges and subagent models as the delegation host settles them. Nothing here holds code, output,
//! paths or prompts: only counts, API names, task ids and times.
//!
//! Recording never fails and never blocks on the store: changes are counted in memory and saved
//! `flush_ms` (500 ms) after the first unsaved one, and on [`SessionStats::flush`]. A store that cannot be written
//! keeps the counters in memory and the next change tries again; a stored document in a format this build does not
//! know is left as it is.

mod external_root;

use crate::durable_store::{SharedSession, lock as lock_session};
use jsrt::sync;
use serde_json::{Value, json};
use session_journal::Write;
use std::collections::HashMap;
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::time::Duration;
use usage::stats::{SESSION_STATS_MODULE, STATS_VERSION, cell_apis, classify_nudge, stats_lane};

/// Distinct host request types kept (later ones are not added), and task ids kept per map (the newest).
const MAX_KEYS: usize = 200;
/// How long after the first unsaved change the counters are saved.
pub const DEFAULT_FLUSH: Duration = Duration::from_millis(500);

fn count(value: Option<&Value>) -> f64 {
    match value.and_then(Value::as_f64) {
        Some(n) if n.is_finite() && n >= 0.0 => n,
        _ => 0.0,
    }
}

fn empty_cells() -> Value {
    json!({"count": 0, "failed": 0, "apis": {}})
}

fn empty_guard() -> Value {
    json!({"checks": 0, "blocked": 0, "unchecked": 0, "afterChecks": 0, "afterFindings": 0, "ms": 0})
}

/// `emptySessionStats(root, now)`.
pub fn empty_session_stats(root: &str, now: u64) -> Value {
    json!({
        "version": STATS_VERSION,
        "root": root,
        "since": now,
        "updatedAt": now,
        "cells": {"root": empty_cells(), "subagents": empty_cells(), "other": empty_cells()},
        "hostCalls": {},
        "secretsMasked": 0,
        "guards": {},
        "nudges": {"toolRounds": 0, "wait": 0, "skill": 0},
        "usageLimitBlocks": 0,
        "merges": {},
        "childModels": {},
        "externalTurns": {"count": 0, "wallMs": 0},
    })
}

/// `parseSessionStats`: a stored document with every field present, or None when `saved` is not one (not an object,
/// or another version). Unknown fields are dropped and malformed counters read as zero.
pub fn parse_session_stats(saved: &Value) -> Option<Value> {
    usage::stats::parse_session_stats(Some(saved)).map(|stats| stats.to_json())
}

/// What the store holds, read as `readVersioned` reads it.
pub enum Stored {
    /// Nothing usable (no value, or not a stats document): count from zero.
    Fresh,
    /// A stats document (an unversioned one reads as version 1).
    Document(Value),
    /// A document in a format version this build does not know: counted in memory, never overwritten.
    Foreign,
}

/// `parseSessionStats(readVersioned("ultron.module/stats", saved))`.
pub fn read_stored(saved: Option<&Value>) -> Stored {
    let Some(Value::Object(document)) = saved else {
        return Stored::Fresh;
    };
    let mut document = document.clone();
    match document.get("version") {
        None => {
            document.insert("version".into(), json!(STATS_VERSION));
        }
        Some(version) if version.as_f64() == Some(STATS_VERSION as f64) && version.is_number() => {}
        Some(_) => return Stored::Foreign,
    }
    parse_session_stats(&Value::Object(document)).map_or(Stored::Fresh, Stored::Document)
}

/// Where the counters are kept (`HostModuleStore`).
pub trait StatsStore: Send + Sync {
    fn read(&self) -> Result<Option<Value>, String>;
    fn write(&self, document: &Value) -> Result<(), String>;
}

/// The session value `ultron.module/stats` of a session journal (`createSessionModuleStore(session, "stats")`).
pub struct SessionStore(pub SharedSession);

impl StatsStore for SessionStore {
    fn read(&self) -> Result<Option<Value>, String> {
        Ok(lock_session(&self.0)
            .value(session_journal::ns::MODULE, SESSION_STATS_MODULE)
            .cloned())
    }

    fn write(&self, document: &Value) -> Result<(), String> {
        lock_session(&self.0)
            .commit(&[Write::set(
                session_journal::ns::MODULE,
                SESSION_STATS_MODULE,
                document.clone(),
            )])
            .map(|_| ())
    }
}

/// Milliseconds since the epoch (tests: a fake clock).
pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;

/// One guard outcome (`GuardRecord`, the fields counted here).
pub struct GuardOutcome<'a> {
    pub guard: &'a str,
    /// `before_write`, `before_shell` or `after_cell`.
    pub phase: &'a str,
    /// `allowed`, `blocked`, `unchecked`, `clean`, `advisory` or `findings`.
    pub outcome: &'a str,
    pub ms: f64,
}

type Change = Box<dyn Fn(&mut Value) + Send>;

struct State {
    document: Value,
    store: Option<Arc<dyn StatsStore>>,
    /// Changes made before the stored document was read; applied on top of it once it is.
    early: Option<Vec<Change>>,
    dirty: bool,
    /// A save is scheduled (`#timer`).
    timer: bool,
    closed: bool,
    foreign: bool,
    open_turns: HashMap<String, u64>,
}

struct Shared {
    state: Mutex<State>,
    /// Wakes the scheduled save early (a flush or close took its place).
    wake: Condvar,
    /// Saves run one at a time, in order.
    writes: Mutex<()>,
    now: Clock,
    flush_after: Duration,
}

/// `SessionStatsRecorder`: counts in memory and saves the document shortly after a change.
pub struct SessionStats {
    shared: Arc<Shared>,
}

impl Drop for SessionStats {
    fn drop(&mut self) {
        // A scheduled save of a recorder nobody holds is not waited for.
        sync::lock(&self.shared.state).timer = false;
        self.shared.wake.notify_all();
    }
}

fn add(value: &mut Value, n: f64) {
    *value = jsrt::json::number(count(Some(value)) + n);
}

/// `keep(map, key, value)`: `key` as the newest entry of a bounded map (the oldest past [`MAX_KEYS`] are dropped).
fn keep(map: &mut Value, key: &str, value: &str) {
    let Some(map) = map.as_object_mut() else {
        return;
    };
    map.shift_remove(key);
    map.insert(key.to_string(), json!(value));
    let excess = map.len().saturating_sub(MAX_KEYS);
    let old: Vec<String> = map.keys().take(excess).cloned().collect();
    for key in old {
        map.shift_remove(&key);
    }
}

impl SessionStats {
    /// A recorder for a session whose root is `root` (`lane`, or `external` for Claude Code over MCP), counting
    /// from `now()`; it saves to nothing until [`SessionStats::attach`] gives it its store.
    pub fn new(root: &str, now: Clock, flush_after: Duration) -> SessionStats {
        let document = empty_session_stats(root, now());
        SessionStats {
            shared: Arc::new(Shared {
                state: Mutex::new(State {
                    document,
                    store: None,
                    early: Some(Vec::new()),
                    dirty: false,
                    timer: false,
                    closed: false,
                    foreign: false,
                    open_turns: HashMap::new(),
                }),
                wake: Condvar::new(),
                writes: Mutex::new(()),
                now,
                flush_after,
            }),
        }
    }

    /// A recorder on the system clock that saves 500 ms after a change.
    pub fn system(root: &str) -> SessionStats {
        SessionStats::new(root, Arc::new(|| jsrt::date::now_ms() as u64), DEFAULT_FLUSH)
    }

    /// Read the stored counters from `store` and keep counting on top of them (`#load`); changes made before are
    /// applied to what was stored. The session keeps the kind of root it has now.
    pub fn attach(&self, store: Arc<dyn StatsStore>) {
        let read = store.read();
        let mut state = sync::lock(&self.shared.state);
        if state.store.is_some() || state.early.is_none() {
            return;
        }
        match read.map(|saved| read_stored(saved.as_ref())) {
            Ok(Stored::Document(mut stored)) => {
                stored["root"] = state.document["root"].clone();
                state.document = stored;
            }
            // A store that could not be read is not overwritten either: its saved totals may be fine.
            Ok(Stored::Foreign) | Err(_) => state.foreign = true,
            Ok(Stored::Fresh) => {}
        }
        state.store = Some(store);
        let early = state.early.take().unwrap_or_default();
        let changed = !early.is_empty();
        for change in &early {
            change(&mut state.document);
        }
        if changed {
            self.schedule(&mut state);
        }
    }

    fn change(&self, change: impl Fn(&mut Value) + Send + 'static) {
        let mut state = sync::lock(&self.shared.state);
        if state.closed {
            return;
        }
        if let Some(early) = &mut state.early {
            early.push(Box::new(change));
            return;
        }
        change(&mut state.document);
        self.schedule(&mut state);
    }

    fn schedule(&self, state: &mut State) {
        state.dirty = true;
        state.document["updatedAt"] = json!((self.shared.now)());
        if state.timer || state.closed {
            return;
        }
        state.timer = true;
        let shared = self.shared.clone();
        std::thread::spawn(move || {
            let state = sync::lock(&shared.state);
            let (mut state, _) = shared
                .wake
                .wait_timeout_while(state, shared.flush_after, |s| s.timer)
                .unwrap_or_else(PoisonError::into_inner);
            // A flush or close that came first took the save over.
            if !state.timer {
                return;
            }
            state.timer = false;
            drop(state);
            save(&shared);
        });
    }

    /// Something ran in the session: its counters are saved even while they are all zero.
    pub fn touch(&self) {
        self.change(|_| {});
    }

    /// One cell ran on `lane`: whether it failed, and how many secrets were masked in its output.
    pub fn cell(&self, lane: &str, code: &str, failed: bool, masked: usize) {
        let (apis, cells) = (cell_apis(code), stats_lane(lane));
        self.change(move |document| {
            let cells = &mut document["cells"][cells];
            add(&mut cells["count"], 1.0);
            if failed {
                add(&mut cells["failed"], 1.0);
            }
            for api in &apis {
                let entry = &mut cells["apis"][*api];
                add(entry, 1.0);
            }
            add(&mut document["secretsMasked"], masked as f64);
        });
    }

    /// A kernel made a host request of this type.
    pub fn host_call(&self, kind: &str) {
        let kind = kind.to_string();
        self.change(move |document| {
            let Some(calls) = document["hostCalls"].as_object_mut() else {
                return;
            };
            if !calls.contains_key(&kind) && calls.len() >= MAX_KEYS {
                return;
            }
            let entry = calls.entry(kind.clone()).or_insert(json!(0));
            add(entry, 1.0);
        });
    }

    /// One guard outcome (Loki, extensions).
    pub fn guard(&self, record: &GuardOutcome<'_>) {
        let (name, ms) = (record.guard.to_string(), record.ms);
        // A shell command checked before it runs counts as a before-write check: it is one.
        let before = matches!(record.phase, "before_write" | "before_shell");
        let (blocked, unchecked) = (record.outcome == "blocked", record.outcome == "unchecked");
        // Advisory-only reports are not findings to fix.
        let findings = matches!(record.outcome, "findings" | "unchecked");
        self.change(move |document| {
            let Some(guards) = document["guards"].as_object_mut() else {
                return;
            };
            let guard = guards.entry(name.clone()).or_insert_with(empty_guard);
            add(&mut guard["ms"], count(Some(&json!(ms))));
            if before {
                add(&mut guard["checks"], 1.0);
                if blocked {
                    add(&mut guard["blocked"], 1.0);
                }
                if unchecked {
                    add(&mut guard["unchecked"], 1.0);
                }
            } else {
                add(&mut guard["afterChecks"], 1.0);
                if findings {
                    add(&mut guard["afterFindings"], 1.0);
                }
            }
        });
    }

    /// A steer sent to the root; text that is not one of the known steers is not counted.
    pub fn nudge(&self, message: &str) {
        let Some(kind) = classify_nudge(message) else {
            return;
        };
        self.change(move |document| add(&mut document["nudges"][kind], 1.0));
    }

    /// A tool call, model request or admission refused because a root's limit was hit.
    pub fn usage_limit_block(&self) {
        self.change(|document| add(&mut document["usageLimitBlocks"], 1.0));
    }

    /// How `rlm.merge` ended for a worktree child.
    pub fn merge(&self, task_id: &str, status: &str) {
        let (task_id, status) = (task_id.to_string(), status.to_string());
        self.change(move |document| keep(&mut document["merges"], &task_id, &status));
    }

    /// The model an `rlm.spawn` subagent ran on.
    pub fn child_model(&self, task_id: &str, model: &str) {
        let (task_id, model) = (task_id.to_string(), model.to_string());
        self.change(move |document| keep(&mut document["childModels"], &task_id, &model));
    }

    /// A turn of an external root began (Claude Code's UserPromptSubmit, or its first cell).
    pub fn external_turn_started(&self, turn: &str) {
        {
            let mut state = sync::lock(&self.shared.state);
            if state.open_turns.contains_key(turn) {
                return;
            }
            let now = (self.shared.now)();
            state.open_turns.insert(turn.to_string(), now);
        }
        self.change(|document| add(&mut document["externalTurns"]["count"], 1.0));
    }

    pub fn external_turn_ended(&self, turn: &str) {
        let elapsed = {
            let mut state = sync::lock(&self.shared.state);
            let Some(started) = state.open_turns.remove(turn) else {
                return;
            };
            (self.shared.now)().saturating_sub(started)
        };
        self.change(move |document| add(&mut document["externalTurns"]["wallMs"], elapsed as f64));
    }

    /// The counters as they are now, saved or not.
    pub fn snapshot(&self) -> Value {
        let state = sync::lock(&self.shared.state);
        let mut document = state.document.clone();
        for change in state.early.iter().flatten() {
            change(&mut document);
        }
        document
    }

    /// Save unsaved changes now. Never fails: a store that refuses the write leaves them for the next change.
    pub fn flush(&self) {
        {
            let mut state = sync::lock(&self.shared.state);
            state.timer = false;
        }
        self.shared.wake.notify_all();
        save(&self.shared);
    }

    /// Save and stop recording (open external turns end now).
    pub fn close(&self) {
        let open: Vec<String> = sync::lock(&self.shared.state).open_turns.keys().cloned().collect();
        for turn in open {
            self.external_turn_ended(&turn);
        }
        self.flush();
        let mut state = sync::lock(&self.shared.state);
        state.closed = true;
        state.timer = false;
        drop(state);
        self.shared.wake.notify_all();
    }
}

fn save(shared: &Shared) {
    let _one_at_a_time = sync::lock(&shared.writes);
    let (store, document) = {
        let mut state = sync::lock(&shared.state);
        let Some(store) = state.store.clone() else {
            return;
        };
        if !state.dirty || state.foreign {
            return;
        }
        state.dirty = false;
        (store, state.document.clone())
    };
    if store.write(&document).is_err() {
        sync::lock(&shared.state).dirty = true;
    }
}