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