Skip to main content

borg/
stats.rs

1//! What Borg did, counted: the collective's usage statistics.
2//!
3//! Two files per collective store:
4//! - `stats/events.jsonl` (local, never synced): one line per event, written by the hook or command
5//!   where it happened (`record`). It holds session ids and repos, so it stays on this machine.
6//! - `stats.jsonl` (synced by the mesh, `borg-mesh` lines.rs `SYNCED`): one rollup per (node, engineer,
7//!   UTC day), folded from the local events (`rollup`). A bucket is a versioned record (`id` +
8//!   `version`), so the mesh's `settle` keeps its latest version on every machine with no merge logic
9//!   of its own. Only the node that owns a bucket writes it, so buckets never conflict. A rollup carries
10//!   counts, cost and lesson ids, never prompts or sessions.
11//!
12//! Recording fails open and costs one append: a broken store never disturbs the drone.
13
14use std::collections::BTreeMap;
15use std::io::Write;
16use std::path::{Path, PathBuf};
17
18use serde::{Deserialize, Serialize};
19
20/// A turn end the conscience saw (one per Stop that was not the rework after its own block).
21pub const TURN_END: &str = "turn_end";
22/// The free gate skipped the model call (`why`: the score, or `noedit`).
23pub const GATE_SKIP: &str = "gate_skip";
24/// One turn-end model call (`n`: lessons shown, `usd`, `dur_ms`; `why: "failed"` when it gave no answer).
25pub const CHECK: &str = "check";
26/// A block: one extra round of agent work (`n`: questions, `lessons`: the asked ids).
27pub const BLOCK: &str = "block";
28/// Live mode (live.rs): one model call during the turn (`n`, `usd`, `dur_ms`, `why: "failed"`, as `check`).
29pub const LIVE_CHECK: &str = "live_check";
30/// Live mode: grade-3 lessons a live check asked, delivered with the next prompt or tool call (`n`,
31/// `lessons`). Never an extra round: the drone answers as it works.
32pub const LIVE_ASK: &str = "live_ask";
33/// Lessons handed over free at a prompt or touch (`n`, `lessons`).
34pub const EARLY: &str = "early";
35/// Grade-2 and grade-1 lessons queued to arrive free at the next prompt (`n`, `lessons`).
36pub const QUEUED_FREE: &str = "queued_free";
37/// Outcomes of asked lessons (outcome.rs): used, ignored, corrected anyway, not corrected.
38pub const CHANGED: &str = "changed";
39pub const IGNORED: &str = "ignored";
40pub const CORRECTED: &str = "corrected";
41pub const NOT_CORRECTED: &str = "not_corrected";
42/// A later fix, or a review finding, counted against a lesson asked before the decision (outcome.rs
43/// `regretted`; `lessons`: the blamed lesson).
44pub const REGRETTED: &str = "regretted";
45/// `borg learn` credited a lesson asked before the session's own tests went green (outcome.rs `tested`;
46/// `lessons`: that lesson).
47pub const TESTED: &str = "tested";
48/// The engineer corrected the drone (an episode): `why` is `rejected_tool` or `pushback`, `text` a snippet.
49pub const CORRECTION: &str = "correction";
50/// The engineer said no (`borg no`, veto.rs): `lessons` the lessons shown so far (credited `vetoed`),
51/// `n` their number, `why` `cli`, `prompt` or `mesh`, `text` the reason.
52pub const VETO: &str = "veto";
53/// `borg learn` merged a veto into a lesson an earlier veto made: the same "no" said twice, dated when
54/// that veto was said (its episode's ms), so it falls in the week of its own `veto`.
55pub const VETO_REPEAT: &str = "veto_repeat";
56/// A lesson written (`why`: its source, session/import/queen/veto) or merged into an existing one.
57pub const LESSON_NEW: &str = "lesson_new";
58pub const LESSON_MERGED: &str = "lesson_merged";
59/// A review step's finding that a fix step fixed before any commit, recorded as an episode
60/// (review_fix.rs; `why`: its severity, `text`: its redacted title, for this machine's feed only).
61pub const REVIEW_FINDING: &str = "review_finding";
62/// `borg learn` judged an episode not to be a lesson.
63pub const NOT_A_LESSON: &str = "not_a_lesson";
64/// A model call outside the turn end (`why`: learn, assimilate, facets, expert; `usd`, `dur_ms`).
65pub const MODEL_CALL: &str = "model_call";
66/// Steering: a directive issued, shown to a drone (`why`: say/pause/resume), refused on receipt
67/// (`why`: the reason), and a tool call refused because the drone was paused (`why`: the tool).
68pub const STEER_ISSUED: &str = "steer_issued";
69pub const STEER_DELIVERED: &str = "steer_delivered";
70pub const STEER_DROPPED: &str = "steer_dropped";
71pub const PAUSE_REFUSED: &str = "pause_refused";
72/// Messages between sessions (msg.rs): one sent (`why`: tell/ask), shown to a session (`why`: its kind),
73/// and dropped (`why`: `window`, the sender's window to its recipient was full, msg.rs `window_for`;
74/// events before 0.6.0 say `rate`; `bounds`, `n` lines the log's bound, msg.rs `MEMBER_BYTES`, cut).
75pub const MSG_SENT: &str = "msg_sent";
76pub const MSG_DELIVERED: &str = "msg_delivered";
77pub const MSG_DROPPED: &str = "msg_dropped";
78/// The queen's queue: a question queued, handed to a drone, answered (`dur_ms`: time to answer),
79/// skipped, dismissed.
80pub const QUEEN_QUEUED: &str = "queen_queued";
81pub const QUEEN_DELIVERED: &str = "queen_delivered";
82pub const QUEEN_ANSWERED: &str = "queen_answered";
83pub const QUEEN_SKIPPED: &str = "queen_skipped";
84pub const QUEEN_DISMISSED: &str = "queen_dismissed";
85/// The queen's attention reward (escalation.rs), once per event: an escalation answered by changing
86/// course, one answered "yes, fine", and a "no" after merge from a session never escalated (`why`: the
87/// kind, or `veto`/`regret`; `text` starts with the question, episode or link id).
88pub const QUEEN_NO: &str = "queen_no";
89pub const QUEEN_STAMP: &str = "queen_stamp";
90pub const QUEEN_MISSED: &str = "queen_missed";
91/// One imported chunk of team documents (`n`: lessons, `usd`).
92pub const ASSIMILATED: &str = "assimilated";
93
94#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
95pub struct Event {
96    pub ms: i64,
97    pub kind: String,
98    #[serde(default, skip_serializing_if = "String::is_empty")]
99    pub session: String,
100    #[serde(default, skip_serializing_if = "String::is_empty")]
101    pub engineer: String,
102    #[serde(default, skip_serializing_if = "String::is_empty")]
103    pub repo: String,
104    #[serde(default, skip_serializing_if = "Vec::is_empty")]
105    pub lessons: Vec<String>,
106    #[serde(default, skip_serializing_if = "is_zero")]
107    pub n: u64,
108    #[serde(default, skip_serializing_if = "is_zero_f")]
109    pub usd: f64,
110    #[serde(default, skip_serializing_if = "is_zero")]
111    pub dur_ms: u64,
112    #[serde(default, skip_serializing_if = "String::is_empty")]
113    pub why: String,
114    /// A short excerpt for this machine's own feed (a correction's words). Never folded into a rollup.
115    #[serde(default, skip_serializing_if = "String::is_empty")]
116    pub text: String,
117    /// The delivery mode the hook ran in (live.rs: `hook` or `live`); empty outside a hook.
118    #[serde(default, skip_serializing_if = "String::is_empty")]
119    pub mode: String,
120    /// How an asked lesson reached the drone: `stop` (a block), `live` (a live check), `early`, `queued`.
121    /// On asks and on their results (`changed`, `ignored`).
122    #[serde(default, skip_serializing_if = "String::is_empty")]
123    pub channel: String,
124}
125
126fn is_zero(v: &u64) -> bool {
127    *v == 0
128}
129
130fn is_zero_f(v: &f64) -> bool {
131    *v == 0.0
132}
133
134impl Event {
135    /// An event now, in the delivery mode of this process (the hook exports `BORG_MODE`, main.rs).
136    pub fn new(kind: &str, ms: i64) -> Self {
137        let mode = std::env::var("BORG_MODE").map(|_| crate::live::current().name().to_string()).unwrap_or_default();
138        Event { kind: kind.into(), ms, mode, ..Default::default() }
139    }
140}
141
142/// One node's counts for one engineer on one UTC day: a line of `stats.jsonl`.
143#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
144pub struct Bucket {
145    pub id: String,
146    pub version: u64,
147    pub day: String,
148    pub node: String,
149    pub engineer: String,
150    /// Events per kind; `<kind>_n` sums their `n` (questions asked, lessons shown).
151    pub counts: BTreeMap<String, u64>,
152    pub usd: f64,
153    /// Cost per kind (turn-end checks, other model calls, imports).
154    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
155    pub usd_by: BTreeMap<String, f64>,
156    pub dur_ms: u64,
157    /// Events per kind for each lesson they named.
158    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
159    pub lessons: BTreeMap<String, BTreeMap<String, u64>>,
160    /// The conscience's model cost (`check` and `live_check`) per delivery mode (`hook`, `live`). A
161    /// split of part of `usd`, so never stacked with `usd_by`.
162    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
163    pub usd_mode: BTreeMap<String, f64>,
164    /// Events per `<kind>@<channel>` for events that name a channel (`block@stop`, `changed@live`).
165    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
166    pub channels: BTreeMap<String, u64>,
167}
168
169impl Bucket {
170    /// Equal counts, cost and lessons: nothing to publish (`id` and `version` aside).
171    fn same(&self, other: &Bucket) -> bool {
172        self.counts == other.counts
173            && self.lessons == other.lessons
174            && self.channels == other.channels
175            && self.dur_ms == other.dur_ms
176            && (self.usd - other.usd).abs() < 1e-9
177    }
178
179    /// Adds `other`'s counts (team totals across nodes and engineers).
180    pub fn add(&mut self, other: &Bucket) {
181        for (k, v) in &other.counts {
182            *self.counts.entry(k.clone()).or_default() += v;
183        }
184        for (id, kinds) in &other.lessons {
185            let mine = self.lessons.entry(id.clone()).or_default();
186            for (k, v) in kinds {
187                *mine.entry(k.clone()).or_default() += v;
188            }
189        }
190        for (k, v) in &other.usd_by {
191            *self.usd_by.entry(k.clone()).or_default() += v;
192        }
193        for (k, v) in &other.usd_mode {
194            *self.usd_mode.entry(k.clone()).or_default() += v;
195        }
196        for (k, v) in &other.channels {
197            *self.channels.entry(k.clone()).or_default() += v;
198        }
199        self.usd += other.usd;
200        self.dur_ms += other.dur_ms;
201    }
202}
203
204pub fn events_path(home: &Path) -> PathBuf {
205    home.join("stats").join("events.jsonl")
206}
207
208pub fn rollups_path(home: &Path) -> PathBuf {
209    home.join("stats.jsonl")
210}
211
212/// Appends `ev` to the local event log. Fails open; records nothing with BORG_LEARN=off (eval drones).
213pub fn record(home: &Path, ev: &Event) {
214    if !crate::learn::learning() {
215        return;
216    }
217    let _ = crate::learn::append_jsonl(&events_path(home), ev);
218}
219
220/// Records one event in the store `home` now; `fill` adds the details. The engineer defaults to the
221/// one presence.rs recorded for the session, so callers need not ask git again.
222pub fn count(home: &Path, kind: &str, session: &str, fill: impl FnOnce(&mut Event)) {
223    let mut ev = Event::new(kind, crate::learn::now_ms());
224    ev.session = session.into();
225    fill(&mut ev);
226    if ev.engineer.is_empty() && !session.is_empty() {
227        ev.engineer = crate::presence::read(home, session).map(|p| p.engineer).unwrap_or_default();
228    }
229    record(home, &ev);
230}
231
232/// Display: the characters of a feed excerpt (`excerpt`): one line of borg web's activity feed.
233pub const FEED_CHARS: usize = 160;
234
235/// The first `max` characters of `text` on one line (a feed excerpt, `FEED_CHARS`).
236pub fn excerpt(text: &str, max: usize) -> String {
237    let one = text.split_whitespace().collect::<Vec<_>>().join(" ");
238    match one.char_indices().nth(max) {
239        Some((i, _)) => format!("{}…", &one[..i]),
240        None => one,
241    }
242}
243
244static PURPOSE: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
245
246/// What this process's model calls are for (learn, assimilate, facets), set once by the command.
247pub fn set_purpose(purpose: &'static str) {
248    let _ = PURPOSE.set(purpose);
249}
250
251pub fn purpose() -> &'static str {
252    PURPOSE.get().copied().unwrap_or("model")
253}
254
255fn read_events(path: &Path) -> Vec<Event> {
256    std::fs::read_to_string(path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
257}
258
259/// Every local event: the history derived once from the older logs (`backfill`) and the live ones.
260pub fn events(home: &Path) -> Vec<Event> {
261    let mut all = read_events(&backfill_path(home));
262    all.extend(read_events(&events_path(home)));
263    all
264}
265
266/// The live events only (stats/events.jsonl), without the derived history.
267pub fn live(home: &Path) -> Vec<Event> {
268    read_events(&events_path(home))
269}
270
271/// When live counting began in `home`: its first live event (None: none yet). A repeated veto is
272/// dated when it was said, earlier than its line, so it never marks the start. What `backfill`
273/// derives is before it; a series backfill cannot derive (merges, repeated vetoes) is unknown there.
274pub fn live_since(home: &Path) -> Option<i64> {
275    live(home).iter().filter(|e| e.kind != VETO_REPEAT).map(|e| e.ms).min()
276}
277
278pub fn backfill_path(home: &Path) -> PathBuf {
279    home.join("stats").join("backfill.jsonl")
280}
281
282fn lines(path: &Path) -> Vec<serde_json::Value> {
283    std::fs::read_to_string(path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
284}
285
286/// Derives, once per store, the events that happened before live counting began from the logs Borg
287/// kept anyway: corrections (episodes), outcomes, lessons, the queen's queue, imports, expert and
288/// facet calls, steering drops, and the turn ends recorded in the session state (dated by the state
289/// file's time). Only what happened before the first live event counts, so nothing is counted twice.
290/// Returns how many events it wrote; 0 when it ran before.
291pub fn backfill(home: &Path) -> usize {
292    let path = backfill_path(home);
293    if path.exists() {
294        return 0;
295    }
296    let cutoff = live_since(home).unwrap_or_else(crate::learn::now_ms);
297    let mut out = derive_history(home);
298    out.retain(|e| e.ms > 0 && e.ms < cutoff);
299    out.sort_by_key(|e| e.ms);
300    let text: String = out.iter().map(|e| serde_json::to_string(e).unwrap_or_default() + "\n").collect();
301    if std::fs::create_dir_all(path.parent().unwrap_or(home)).is_err() || std::fs::write(&path, text).is_err() {
302        return 0;
303    }
304    out.len()
305}
306
307fn derive_history(home: &Path) -> Vec<Event> {
308    use serde_json::Value;
309    let s = |v: &Value, k: &str| v[k].as_str().unwrap_or_default().to_string();
310    let ms = |v: &Value, k: &str| v[k].as_i64().unwrap_or(0);
311    let ids = |v: &Value, k: &str| v[k].as_array().into_iter().flatten().filter_map(Value::as_str).map(String::from).collect::<Vec<_>>();
312    let mut out = Vec::new();
313    // Who worked in which session: corrections name their engineer; outcomes do not.
314    let mut who: std::collections::HashMap<String, String> = std::collections::HashMap::new();
315    for e in lines(&home.join("episodes.jsonl")) {
316        let tool = s(&e, "rejected_tool");
317        if !s(&e, "engineer").is_empty() {
318            who.insert(s(&e, "session"), s(&e, "engineer"));
319        }
320        let snippet = excerpt(&s(&e, "correction"), FEED_CHARS);
321        // A veto (veto.rs) is counted as one, never as a correction.
322        if s(&e, "kind") == crate::veto::KIND {
323            out.push(Event {
324                ms: ms(&e, "ms"),
325                kind: VETO.into(),
326                session: s(&e, "session"),
327                engineer: s(&e, "engineer"),
328                repo: s(&e, "repo"),
329                text: snippet,
330                ..Default::default()
331            });
332            continue;
333        }
334        out.push(Event {
335            ms: ms(&e, "ms"),
336            kind: CORRECTION.into(),
337            session: s(&e, "session"),
338            engineer: s(&e, "engineer"),
339            repo: s(&e, "repo"),
340            why: if tool.is_empty() { "pushback".into() } else { "rejected_tool".into() },
341            text: if tool.is_empty() { snippet } else { format!("{tool}: {snippet}") },
342            ..Default::default()
343        });
344    }
345    let engineer = |session: &str| who.get(session).cloned().unwrap_or_default();
346    // One call writes one record per routing check (a stop's block, a live ask, the judge's verdicts of
347    // a kind) and counts them live as one event: such records of one session, kind, channel and stamp
348    // are one event here too, their lessons joined.
349    let mut call: std::collections::HashMap<(String, &str, String, i64), usize> = std::collections::HashMap::new();
350    for o in lines(&home.join("outcomes.jsonl")) {
351        // A placebo's result is no result (outcome.rs `is_result`), as live counting leaves it out.
352        if o["channel"] == crate::outcome::PLACEBO {
353            continue;
354        }
355        let live = o["channel"] == "live";
356        let kind = match o["kind"].as_str().unwrap_or_default() {
357            // A free delivery counts once, as its own event (`early`, `queued_free`), never as a block.
358            crate::outcome::ASKED if o["channel"] == "early" || o["channel"] == "queued" => continue,
359            crate::outcome::ASKED if live => LIVE_ASK,
360            crate::outcome::ASKED => BLOCK,
361            crate::outcome::CHANGED => CHANGED,
362            crate::outcome::IGNORED => IGNORED,
363            crate::outcome::CORRECTED => CORRECTED,
364            crate::outcome::NOT_CORRECTED => NOT_CORRECTED,
365            crate::outcome::REGRETTED => REGRETTED,
366            crate::outcome::TESTED => TESTED,
367            _ => continue,
368        };
369        let lessons = ids(&o, "lessons");
370        let session = s(&o, "session");
371        let asks = kind == BLOCK || kind == LIVE_ASK;
372        let key = (session.clone(), kind, s(&o, "channel"), ms(&o, "ms"));
373        let merges = [BLOCK, LIVE_ASK, CHANGED, IGNORED].contains(&kind);
374        if merges
375            && let Some(&i) = call.get(&key)
376            && let Some(e) = out.get_mut(i)
377        {
378            e.n += if asks { lessons.len() as u64 } else { 0 };
379            e.lessons.extend(lessons);
380            continue;
381        }
382        if merges {
383            call.insert(key, out.len());
384        }
385        out.push(Event {
386            ms: ms(&o, "ms"),
387            kind: kind.into(),
388            engineer: engineer(&session),
389            session,
390            repo: s(&o, "repo"),
391            n: if asks { lessons.len() as u64 } else { 0 },
392            lessons,
393            channel: s(&o, "channel"),
394            ..Default::default()
395        });
396    }
397    // A lesson's first version is when it was learned; later versions carry no time of their own.
398    let mut seen = std::collections::HashSet::new();
399    for l in lines(&home.join("lessons.jsonl")) {
400        let id = s(&l, "id");
401        if id.is_empty() || !seen.insert(id.clone()) {
402            continue;
403        }
404        let source = Some(s(&l, "source")).filter(|x| !x.is_empty()).unwrap_or_else(|| "session".into());
405        out.push(Event {
406            ms: ms(&l, "origin_ms"),
407            kind: LESSON_NEW.into(),
408            engineer: ids(&l, "engineers").into_iter().next().unwrap_or_default(),
409            repo: s(&l, "repo"),
410            lessons: vec![id],
411            why: source,
412            ..Default::default()
413        });
414    }
415    let mut queen: BTreeMap<String, Value> = BTreeMap::new();
416    for q in lines(&home.join("queen").join("queue.jsonl")) {
417        queen.insert(s(&q, "id"), q);
418    }
419    for q in queen.values() {
420        let base = || Event { engineer: s(q, "engineer"), session: s(q, "session"), repo: s(q, "repo"), lessons: vec![s(q, "id")], ..Default::default() };
421        out.push(Event { ms: ms(q, "ms"), kind: QUEEN_QUEUED.into(), text: excerpt(&s(q, "question"), FEED_CHARS), ..base() });
422        if let Some(at) = q["answered_ms"].as_i64() {
423            let dur = u64::try_from(at - ms(q, "ms")).unwrap_or(0);
424            out.push(Event {
425                ms: at,
426                kind: QUEEN_ANSWERED.into(),
427                dur_ms: dur,
428                engineer: s(q, "answered_by"),
429                text: excerpt(&s(q, "answer"), FEED_CHARS),
430                ..base()
431            });
432        }
433        if let Some(at) = q["dismissed_ms"].as_i64() {
434            out.push(Event { ms: at, kind: QUEEN_DISMISSED.into(), text: s(q, "dismissed"), ..base() });
435        }
436    }
437    for (file, kind) in [("delivered.jsonl", QUEEN_DELIVERED), ("skips.jsonl", QUEEN_SKIPPED)] {
438        for m in lines(&home.join("queen").join(file)) {
439            let session = s(&m, "session");
440            out.push(Event { ms: ms(&m, "ms"), kind: kind.into(), engineer: engineer(&session), session, lessons: vec![s(&m, "id")], ..Default::default() });
441        }
442    }
443    for a in lines(&home.join("assimilated.jsonl")) {
444        out.push(Event {
445            ms: ms(&a, "ms"),
446            kind: ASSIMILATED.into(),
447            repo: s(&a, "source"),
448            n: ids(&a, "lessons").len() as u64,
449            usd: a["cost_usd"].as_f64().unwrap_or(0.0),
450            ..Default::default()
451        });
452    }
453    for (file, why) in [("experts.jsonl", "expert"), ("facets.jsonl", "facets")] {
454        for c in lines(&home.join(file)) {
455            let session = s(&c, "session");
456            out.push(Event {
457                ms: ms(&c, "ms"),
458                kind: MODEL_CALL.into(),
459                engineer: engineer(&session),
460                session,
461                repo: s(&c, "repo"),
462                usd: c["cost_usd"].as_f64().unwrap_or(0.0),
463                why: why.into(),
464                ..Default::default()
465            });
466        }
467    }
468    // History: an older store's directives (the mesh outbox, the steer inbox). Nothing writes these
469    // files any more; steering now counts as it happens (msg.rs `send`, `deliver`).
470    for (file, kind) in [(home.join("mesh").join("directives.jsonl"), STEER_ISSUED), (home.join("steer").join("inbox.jsonl"), STEER_DELIVERED)] {
471        for d in lines(&file) {
472            out.push(Event {
473                ms: ms(&d, "ms"),
474                kind: kind.into(),
475                engineer: s(&d, "engineer"),
476                why: s(&d, "kind"),
477                text: excerpt(&s(&d, "text"), FEED_CHARS),
478                ..Default::default()
479            });
480        }
481    }
482    for d in lines(&crate::steer::dropped_path(home)) {
483        out.push(Event { ms: ms(&d, "ms"), kind: STEER_DROPPED.into(), engineer: s(&d, "engineer"), why: s(&d, "why"), ..Default::default() });
484    }
485    out.extend(turns_from_state(&home.join("state"), &who));
486    out
487}
488
489/// Turn ends, gate skips and model checks from the per-session state markers, dated by the state
490/// file's last change (the markers carry no time of their own).
491fn turns_from_state(dir: &Path, who: &std::collections::HashMap<String, String>) -> Vec<Event> {
492    let mut out = Vec::new();
493    let Ok(rd) = std::fs::read_dir(dir) else { return out };
494    for f in rd.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ctx")) {
495        let Some(at) = std::fs::metadata(&f).ok().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) else {
496            continue;
497        };
498        let session = f.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
499        let base =
500            || Event { ms: at.as_millis() as i64, session: session.clone(), engineer: who.get(&session).cloned().unwrap_or_default(), ..Default::default() };
501        for line in std::fs::read_to_string(&f).unwrap_or_default().lines() {
502            if let Some(score) = line.strip_prefix("#borg-skip ") {
503                out.push(Event { kind: TURN_END.into(), ..base() });
504                out.push(Event { kind: GATE_SKIP.into(), why: score.trim().into(), ..base() });
505            } else if let Some(cost) = line.strip_prefix("#borg-predict-cost ") {
506                out.push(Event { kind: TURN_END.into(), ..base() });
507                out.push(Event { kind: CHECK.into(), usd: cost.trim().parse().unwrap_or(0.0), ..base() });
508            }
509        }
510    }
511    out
512}
513
514/// This machine's id in the collective's statistics, created once (`stats/node`). Not the mesh key:
515/// stats work in local collectives too, and nothing here should need the member key.
516pub fn node(home: &Path) -> String {
517    let path = home.join("stats").join("node");
518    if let Ok(id) = std::fs::read_to_string(&path)
519        && !id.trim().is_empty()
520    {
521        return id.trim().to_string();
522    }
523    // Created whole and only once: the id is written to a file of its own, then hard-linked into
524    // place, which fails when another process got there first; its id wins. A plain write could hand
525    // two first callers two ids, and a reader an empty file between its truncate and write.
526    let id = fresh_id();
527    let _ = std::fs::create_dir_all(path.parent().unwrap_or(home));
528    let tmp = path.with_extension(format!("{id}.tmp"));
529    let linked = std::fs::write(&tmp, &id).and_then(|()| std::fs::hard_link(&tmp, &path));
530    let _ = std::fs::remove_file(&tmp);
531    match linked {
532        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
533            std::fs::read_to_string(&path).map(|s| s.trim().to_string()).ok().filter(|s| !s.is_empty()).unwrap_or(id)
534        }
535        _ => id,
536    }
537}
538
539fn fresh_id() -> String {
540    let mut bytes = [0u8; 8];
541    if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
542        use std::io::Read;
543        let _ = f.read_exact(&mut bytes);
544    }
545    if bytes == [0; 8] {
546        use std::hash::{BuildHasher, Hasher};
547        let mut h = std::collections::hash_map::RandomState::new().build_hasher();
548        h.write_i64(crate::learn::now_ms());
549        h.write_u32(std::process::id());
550        bytes = h.finish().to_le_bytes();
551    }
552    bytes.iter().map(|b| format!("{b:02x}")).collect()
553}
554
555/// `YYYY-MM-DD` (UTC) of an epoch-ms time.
556pub fn day(ms: i64) -> String {
557    let s = crate::install::utc(ms);
558    format!("{}-{}-{}", &s[0..4], &s[4..6], &s[6..8])
559}
560
561/// Every `YYYY-MM-DD` from `first` to `last` (UTC), both included; empty if either is malformed.
562pub fn days_between(first: &str, last: &str) -> Vec<String> {
563    let (Some(a), Some(b)) = (day_number(first), day_number(last)) else { return Vec::new() };
564    (a..=b).map(|d| day(d * crate::clock::DAY_MS)).collect()
565}
566
567/// Days since 1970-01-01 of a `YYYY-MM-DD` date (clock.rs `days_from_civil`).
568fn day_number(date: &str) -> Option<i64> {
569    let mut it = date.split('-').map(|p| p.parse::<i64>().ok());
570    let (y, m, d) = (it.next()??, it.next()??, it.next()??);
571    Some(crate::clock::days_from_civil(y, m, d))
572}
573
574/// One session's corrections and vetoes (`per_session`).
575#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
576pub struct Said {
577    /// The engineer's corrections: a rejected tool call or a pushback (`CORRECTION`, a regret aside:
578    /// a regret is a later fix, counted in the session that fixed, not by the engineer in this one).
579    pub corrections: u64,
580    /// `borg no` vetoes (`VETO`).
581    pub vetoes: u64,
582}
583
584/// Per session, what the engineer said against its work: every correction and veto, whether or not
585/// `borg learn` merged it into a lesson (a merge is what outcome.rs sees; most corrections merge
586/// into none). The denominator for how often a mistake was seen at all, beside the results.
587pub fn per_session(events: &[Event]) -> BTreeMap<String, Said> {
588    let mut out: BTreeMap<String, Said> = BTreeMap::new();
589    for e in events.iter().filter(|e| !e.session.is_empty()) {
590        match e.kind.as_str() {
591            CORRECTION if e.why != "regret" => out.entry(e.session.clone()).or_default().corrections += 1,
592            VETO => out.entry(e.session.clone()).or_default().vetoes += 1,
593            _ => {}
594        }
595    }
596    out
597}
598
599/// The local events folded into this node's buckets, keyed by bucket id (version 0).
600pub fn fold(node: &str, events: &[Event]) -> BTreeMap<String, Bucket> {
601    let mut out: BTreeMap<String, Bucket> = BTreeMap::new();
602    for e in events {
603        let day = day(e.ms);
604        let id = format!("stat:{node}:{}:{day}", e.engineer);
605        let b = out.entry(id.clone()).or_insert_with(|| Bucket { id, day, node: node.into(), engineer: e.engineer.clone(), ..Default::default() });
606        *b.counts.entry(e.kind.clone()).or_default() += 1;
607        if e.n > 0 {
608            *b.counts.entry(format!("{}_n", e.kind)).or_default() += e.n;
609        }
610        b.usd += e.usd;
611        if e.usd > 0.0 {
612            *b.usd_by.entry(e.kind.clone()).or_default() += e.usd;
613        }
614        // Checks from before modes existed were all turn-end checks: hook mode.
615        if e.usd > 0.0 && (e.kind == CHECK || e.kind == LIVE_CHECK) {
616            let mode = if e.mode.is_empty() { "hook" } else { e.mode.as_str() };
617            *b.usd_mode.entry(mode.into()).or_default() += e.usd;
618        }
619        if !e.channel.is_empty() {
620            *b.channels.entry(format!("{}@{}", e.kind, e.channel)).or_default() += 1;
621        }
622        b.dur_ms += e.dur_ms;
623        for l in &e.lessons {
624            *b.lessons.entry(l.clone()).or_default().entry(e.kind.clone()).or_default() += 1;
625        }
626    }
627    out
628}
629
630/// The latest version of every bucket in `stats.jsonl` (every node's, after the mesh merged them). Two
631/// lines of one version (two rollups at once) are ranked as borg-mesh lines.rs `settle` ranks them, by
632/// the line's blake3 hash, so every node shows the same one whatever order the lines arrived in.
633pub fn rollups(home: &Path) -> BTreeMap<String, Bucket> {
634    let mut out: BTreeMap<String, (Bucket, [u8; 32])> = BTreeMap::new();
635    for l in std::fs::read_to_string(rollups_path(home)).unwrap_or_default().lines() {
636        let Ok(b) = serde_json::from_str::<Bucket>(l) else { continue };
637        let h = *blake3::hash(l.as_bytes()).as_bytes();
638        if out.get(&b.id).is_none_or(|(old, oh)| (b.version, h) > (old.version, *oh)) {
639            out.insert(b.id.clone(), (b, h));
640        }
641    }
642    out.into_iter().map(|(id, (b, _))| (id, b)).collect()
643}
644
645/// Publishes this node's buckets whose counts changed since their last line in `stats.jsonl`, each
646/// with the next version. Returns how many lines it appended (0 when nothing changed).
647pub fn rollup(home: &Path) -> usize {
648    backfill(home);
649    // No events, nothing to publish: and no node id created in a store that never counted anything.
650    let evs = events(home);
651    if evs.is_empty() {
652        return 0;
653    }
654    let me = node(home);
655    let published = rollups(home);
656    let fresh: Vec<Bucket> = fold(&me, &evs)
657        .into_values()
658        .filter_map(|mut b| {
659            let old = published.get(&b.id);
660            if old.is_some_and(|o| o.same(&b)) {
661                return None;
662            }
663            b.version = old.map_or(1, |o| o.version + 1);
664            Some(b)
665        })
666        .collect();
667    if fresh.is_empty() {
668        return 0;
669    }
670    let lines: String = fresh.iter().map(|b| serde_json::to_string(b).unwrap_or_default() + "\n").collect();
671    let path = rollups_path(home);
672    let ok = std::fs::OpenOptions::new().create(true).append(true).open(&path).and_then(|mut f| f.write_all(lines.as_bytes()));
673    if ok.is_ok() { fresh.len() } else { 0 }
674}
675
676/// Every bucket the page shows: other nodes' published rollups, and this node's own counts folded
677/// fresh from its local events, so local activity shows before the next rollup.
678pub fn current(home: &Path) -> Vec<Bucket> {
679    backfill(home);
680    let me = node(home);
681    let mut all: BTreeMap<String, Bucket> = rollups(home).into_iter().filter(|(_, b)| b.node != me).collect();
682    all.extend(fold(&me, &events(home)));
683    all.into_values().collect()
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689
690    #[test]
691    fn corrections_and_vetoes_count_per_session_merged_or_not() {
692        let ev = |kind: &str, session: &str, why: &str| Event { kind: kind.into(), session: session.into(), why: why.into(), ..Default::default() };
693        let events = [
694            ev(CORRECTION, "a", "pushback"),
695            ev(CORRECTION, "a", "rejected_tool"),
696            ev(CORRECTION, "a", "regret"),
697            ev(VETO, "a", "prompt"),
698            ev(VETO, "b", "cli"),
699            ev(CHANGED, "b", ""),
700            ev(CORRECTION, "", "pushback"),
701        ];
702        let got = per_session(&events);
703        assert_eq!(got["a"], Said { corrections: 2, vetoes: 1 });
704        assert_eq!(got["b"], Said { corrections: 0, vetoes: 1 });
705        assert_eq!(got.len(), 2);
706    }
707
708    #[test]
709    fn concurrent_first_calls_agree_on_one_node() {
710        // The node id stamps the outcomes and stats that sync: two hooks creating it at once must
711        // agree on one.
712        for round in 0..20 {
713            let home = std::env::temp_dir().join(format!("borg-stats-node-{}-{round}", std::process::id()));
714            let _ = std::fs::remove_dir_all(&home);
715            let ids: Vec<String> = std::thread::scope(|s| {
716                let hs: Vec<_> = (0..16).map(|_| s.spawn(|| node(&home))).collect();
717                hs.into_iter().map(|h| h.join().unwrap()).collect()
718            });
719            assert!(ids.iter().all(|id| *id == ids[0] && id.len() == 16), "{ids:?}");
720            assert_eq!(node(&home), ids[0]);
721            let _ = std::fs::remove_dir_all(&home);
722        }
723    }
724
725    fn tmp(tag: &str) -> PathBuf {
726        let d = std::env::temp_dir().join(format!("borg-stats-{tag}-{}", std::process::id()));
727        let _ = std::fs::remove_dir_all(&d);
728        std::fs::create_dir_all(&d).unwrap();
729        d
730    }
731
732    fn ev(kind: &str, ms: i64, engineer: &str, lessons: &[&str], n: u64) -> Event {
733        Event { engineer: engineer.into(), lessons: lessons.iter().map(|s| s.to_string()).collect(), n, ..Event::new(kind, ms) }
734    }
735
736    /// Derived: one day (clock.rs `DAY_MS`), the tests' unit.
737    const DAY: i64 = crate::clock::DAY_MS;
738
739    #[test]
740    fn days_between_fills_every_day() {
741        assert_eq!(days_between("2026-02-27", "2026-03-02"), ["2026-02-27", "2026-02-28", "2026-03-01", "2026-03-02"]);
742        assert_eq!(days_between("1970-01-01", "1970-01-01"), ["1970-01-01"]);
743        assert!(days_between("x", "1970-01-01").is_empty());
744    }
745
746    #[test]
747    fn day_is_utc_date() {
748        assert_eq!(day(0), "1970-01-01");
749        assert_eq!(day(DAY - 1), "1970-01-01");
750        assert_eq!(day(DAY), "1970-01-02");
751    }
752
753    #[test]
754    fn fold_counts_per_engineer_and_day() {
755        let evs = [
756            ev(TURN_END, 10, "a@x", &[], 0),
757            ev(CHECK, 20, "a@x", &[], 7),
758            ev(BLOCK, 30, "a@x", &["L1", "L2"], 2),
759            ev(TURN_END, DAY + 5, "a@x", &[], 0),
760            ev(TURN_END, 40, "b@x", &[], 0),
761        ];
762        let b = fold("n1", &evs);
763        assert_eq!(b.len(), 3, "two days for a, one for b");
764        let a = &b["stat:n1:a@x:1970-01-01"];
765        assert_eq!((a.counts[TURN_END], a.counts[CHECK], a.counts["check_n"], a.counts["block_n"]), (1, 1, 7, 2));
766        assert_eq!(a.lessons["L1"][BLOCK], 1);
767    }
768
769    #[test]
770    fn fold_splits_check_cost_by_mode_and_asks_by_channel() {
771        let with = |kind: &str, usd: f64, mode: &str, channel: &str| Event { usd, mode: mode.into(), channel: channel.into(), ..ev(kind, 10, "a@x", &[], 0) };
772        let evs = [
773            with(CHECK, 0.05, "", ""),
774            with(CHECK, 0.04, "live", ""),
775            with(LIVE_CHECK, 0.03, "live", ""),
776            with(MODEL_CALL, 0.5, "live", ""),
777            with(BLOCK, 0.0, "live", "stop"),
778            with(LIVE_ASK, 0.0, "live", "live"),
779            with(CHANGED, 0.0, "", "live"),
780        ];
781        let b = &fold("n1", &evs)["stat:n1:a@x:1970-01-01"];
782        assert!((b.usd_mode["hook"] - 0.05).abs() < 1e-9 && (b.usd_mode["live"] - 0.07).abs() < 1e-9, "{:?}", b.usd_mode);
783        assert_eq!(b.usd_mode.len(), 2, "only the conscience's checks: {:?}", b.usd_mode);
784        assert_eq!((b.channels["block@stop"], b.channels["live_ask@live"], b.channels["changed@live"]), (1, 1, 1));
785        assert_eq!((b.counts[CHECK], b.counts[LIVE_CHECK]), (2, 1), "live checks are counted apart from turn-end checks");
786    }
787
788    #[test]
789    fn rollup_versions_only_on_change_and_is_idempotent() {
790        let home = tmp("rollup");
791        record(&home, &ev(TURN_END, 10, "a@x", &[], 0));
792        assert_eq!(rollup(&home), 1);
793        assert_eq!(rollup(&home), 0, "nothing changed: nothing appended");
794        record(&home, &ev(GATE_SKIP, 11, "a@x", &[], 0));
795        assert_eq!(rollup(&home), 1);
796        let r = rollups(&home);
797        let b = r.values().next().unwrap();
798        assert_eq!((b.version, b.counts[TURN_END], b.counts[GATE_SKIP]), (2, 1, 1));
799        let text = std::fs::read_to_string(rollups_path(&home)).unwrap();
800        assert!(!text.contains("session"), "no session ids leave the machine");
801    }
802
803    #[test]
804    fn current_prefers_own_fresh_counts_and_keeps_peers() {
805        let home = tmp("current");
806        record(&home, &ev(TURN_END, 10, "a@x", &[], 0));
807        rollup(&home);
808        record(&home, &ev(TURN_END, 12, "a@x", &[], 0));
809        let peer = Bucket {
810            id: "stat:other:b@x:1970-01-01".into(),
811            version: 3,
812            day: "1970-01-01".into(),
813            node: "other".into(),
814            engineer: "b@x".into(),
815            ..Default::default()
816        };
817        let mut f = std::fs::OpenOptions::new().append(true).open(rollups_path(&home)).unwrap();
818        writeln!(f, "{}", serde_json::to_string(&peer).unwrap()).unwrap();
819        let cur = current(&home);
820        assert_eq!(cur.len(), 2);
821        let mine = cur.iter().find(|b| b.engineer == "a@x").unwrap();
822        assert_eq!(mine.counts[TURN_END], 2, "own counts are folded fresh, not the stale rollup");
823    }
824
825    /// Two v+1 lines of one bucket (two rollups at once) reach peers in either order: every node shows
826    /// the same one, the one mesh `settle` makes last (higher hash).
827    #[test]
828    fn rollups_break_version_ties_by_hash_whatever_the_order() {
829        let bucket = |n: u64| {
830            let mut b = Bucket { id: "stat:n:a@x:1970-01-01".into(), version: 2, ..Default::default() };
831            b.counts.insert(TURN_END.into(), n);
832            serde_json::to_string(&b).unwrap()
833        };
834        let (a, b) = (bucket(1), bucket(2));
835        let shown = |name: &str, first: &str, second: &str| {
836            let home = tmp(name);
837            std::fs::write(rollups_path(&home), format!("{first}\n{second}\n")).unwrap();
838            rollups(&home).into_values().next().unwrap().counts[TURN_END]
839        };
840        assert_eq!(shown("ties-ab", &a, &b), shown("ties-ba", &b, &a));
841    }
842
843    #[test]
844    fn record_fails_open() {
845        let home = tmp("open");
846        std::fs::write(home.join("stats"), "a file where the directory should be").unwrap();
847        record(&home, &ev(TURN_END, 1, "a@x", &[], 0));
848        assert!(events(&home).is_empty());
849    }
850
851    #[test]
852    fn backfill_derives_history_before_live_counting_once() {
853        let home = tmp("backfill");
854        let w = |f: &str, lines: &[serde_json::Value]| {
855            let p = home.join(f);
856            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
857            std::fs::write(p, lines.iter().map(|l| l.to_string() + "\n").collect::<String>()).unwrap();
858        };
859        use serde_json::json;
860        w(
861            "episodes.jsonl",
862            &[
863                json!({"id":"e1","ms":100,"repo":"app","session":"s1","task":"t","agent":"a","rejected_tool":"Bash","correction":"no, not like that","engineer":"a@x"}),
864                json!({"id":"e2","ms":5000,"repo":"app","session":"s2","task":"t","agent":"a","rejected_tool":null,"correction":"after live counting began","engineer":"a@x"}),
865            ],
866        );
867        w(
868            "outcomes.jsonl",
869            &[
870                json!({"kind":"asked","session":"s1","lessons":["L1","L2"],"ms":110,"repo":"app"}),
871                // Free deliveries are counted live as `early` and `queued_free`: never a block here.
872                json!({"kind":"asked","session":"s1","lessons":["L3"],"ms":112,"repo":"app","channel":"early"}),
873                json!({"kind":"asked","session":"s1","lessons":["L4"],"ms":114,"repo":"app","channel":"queued"}),
874                json!({"kind":"asked_then_changed","session":"s1","lessons":["L1"],"ms":120,"repo":"app"}),
875            ],
876        );
877        w(
878            "lessons.jsonl",
879            &[json!({"id":"L1","origin_ms":90,"question":"q","version":1,"engineers":["a@x"]}), json!({"id":"L1","origin_ms":90,"question":"q2","version":2})],
880        );
881        w("queen/queue.jsonl", &[json!({"id":"Q1","ms":130,"question":"which?","engineer":"a@x","answered_ms":190,"answer":"this","answered_by":"a@x"})]);
882        record(&home, &ev(TURN_END, 1000, "a@x", &[], 0));
883        let n = backfill(&home);
884        let all = read_events(&backfill_path(&home));
885        assert_eq!(n, all.len());
886        let kinds: Vec<&str> = all.iter().map(|e| e.kind.as_str()).collect();
887        assert_eq!(kinds, [LESSON_NEW, CORRECTION, BLOCK, CHANGED, QUEEN_QUEUED, QUEEN_ANSWERED], "ordered by time, the later correction left out");
888        let c = &all[1];
889        assert_eq!((c.why.as_str(), c.text.as_str(), c.engineer.as_str()), ("rejected_tool", "Bash: no, not like that", "a@x"));
890        assert_eq!(all[3].engineer, "a@x", "outcomes take the session's engineer from its corrections");
891        assert_eq!(all[5].dur_ms, 60, "time to answer");
892        assert_eq!(backfill(&home), 0, "once");
893        assert_eq!(events(&home).len(), all.len() + 1, "history and live events together");
894    }
895
896    /// A stop's block asked lessons that two checks routed, a live ask delivered two checks' questions,
897    /// and the judge's call wrote one verdict record per check: each is one record per check in the log
898    /// and one event live, so one event in the history too, its lessons joined. Records of separate
899    /// calls (another stamp) and results counted per record stay apart.
900    #[test]
901    fn backfill_counts_one_event_per_call_as_live_counting_does() {
902        let home = tmp("backfill-call");
903        use serde_json::json;
904        let rec = |kind: &str, lessons: &[&str], ms: i64, channel: &str, check: &str| json!({"kind": kind, "session": "s1", "lessons": lessons, "ms": ms, "repo": "app", "channel": channel, "check": check});
905        let log = [
906            rec("asked", &["L1", "L2"], 110, "stop", "c1"),
907            rec("asked", &["L3"], 110, "stop", "c2"),
908            rec("asked", &["L4"], 120, "live", "c3"),
909            rec("asked", &["L5"], 120, "live", "c4"),
910            rec("asked_then_changed", &["L1"], 130, "stop", "c1"),
911            rec("asked_then_changed", &["L3"], 130, "stop", "c2"),
912            rec("asked", &["L6"], 140, "stop", "c5"),
913            rec("asked_not_corrected", &["L2"], 150, "stop", "c1"),
914            rec("asked_not_corrected", &["L6"], 150, "stop", "c5"),
915        ];
916        std::fs::write(home.join("outcomes.jsonl"), log.iter().map(|l| l.to_string() + "\n").collect::<String>()).unwrap();
917        record(&home, &ev(TURN_END, 1000, "a@x", &[], 0));
918        backfill(&home);
919        let all: Vec<(String, i64, u64, Vec<String>)> = read_events(&backfill_path(&home)).into_iter().map(|e| (e.kind, e.ms, e.n, e.lessons)).collect();
920        let row = |kind: &str, ms: i64, n: u64, lessons: &[&str]| (kind.to_string(), ms, n, lessons.iter().map(|l| l.to_string()).collect::<Vec<_>>());
921        assert_eq!(
922            all,
923            [
924                row(BLOCK, 110, 3, &["L1", "L2", "L3"]),
925                row(LIVE_ASK, 120, 2, &["L4", "L5"]),
926                row(CHANGED, 130, 0, &["L1", "L3"]),
927                row(BLOCK, 140, 1, &["L6"]),
928                row(NOT_CORRECTED, 150, 0, &["L2"]),
929                row(NOT_CORRECTED, 150, 0, &["L6"]),
930            ]
931        );
932    }
933
934    #[test]
935    fn node_id_is_stable() {
936        let home = tmp("node");
937        let a = node(&home);
938        assert_eq!(a.len(), 16);
939        assert_eq!(node(&home), a);
940    }
941}