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