Skip to main content

borg/
outcome.rs

1//! What happened after the conscience asked a lesson: the signal for down-weighting lessons
2//! that are generic or do not help, and for trust per engineer × area (trust.rs).
3//!
4//! `$BORG_HOME/outcomes.jsonl` is append-only and deterministic, one record per line:
5//! - `asked`: the conscience asked these lessons at a stop or live, or delivered them as context (early,
6//!   or a graded check's 2s and 1s handed over free; hook, 0 tokens);
7//! - `asked_then_corrected`: after lesson X was asked, the engineer still made a correction in the
8//!   same session that `borg learn` merged into X (same concern): asking did not prevent it;
9//! - `asked_not_corrected`: the session ended, or has been idle for `IDLE_MS`, and no later
10//!   correction was merged into X. The idle rule keeps both kinds coming from every `borg learn`
11//!   run: without it, a session whose `end` hook never ran could only ever add corrected counts.
12//!
13//! A correction that contradicts a lesson asked earlier in the session (`supersedes`) also marks that
14//! lesson `asked_then_corrected`; when the conscience rendered asked lessons as a disagreement (the
15//! `asked` record's `groups`), a correction siding with one of them marks the other sides, not the
16//! one it agreed with (`contradicted`).
17//!
18//! - `asked_then_changed` (hook, no extra call): at a later Stop of the session, the consequence model's
19//!   call (predict.rs) also judged, by meaning, that the drone changed its work on the lesson's point
20//!   and that the change avoids the consequence: a use, the deposit that keeps a lesson active
21//!   (memory.rs). The drone's `<id>: applies|skip` is evidence in that prompt, never a label alone;
22//! - `asked_ignored` (hook): the same judge found the lesson's point came up and the drone changed
23//!   nothing on it.
24//! - `asked_not_arisen` (hook, 0.7.5 on): the same judge found the lesson's point never came up in the
25//!   work: nothing to change, so nothing about the lesson. It settles the delivery (no further try),
26//!   is censored for beliefs, trust, the statistics and the team (`is_result`), and the selection model
27//!   reads it as "nothing in the work" (select/summary.rs `Label::NotArisen`).
28//! - `asked_consequence_remains` (hook, 0.7.5 on): the drone changed its work on the point, but the work
29//!   still leads to the consequence. As an unclear verdict: measured, never a result, pending for another
30//!   try. Before 0.7.5 such a verdict was written as `asked_unclear`, which therefore mixes both there.
31//!
32//! Every judge result (0.7.5 on) carries the judge's short reason per lesson (`reasons`, redacted,
33//! predict.rs `JUDGE_REASON_CHARS`). Local: never shared.
34//! - `vetoed` (`borg no`, veto.rs, 0 tokens): the engineer said no to the session's work; every lesson
35//!   shown in the session before it is credited, the strongest negative result.
36//!
37//! - `regretted` (`borg learn`, 0 tokens): a regret episode (a later fix of a decision, or a review finding;
38//!   learn/regret.rs) generalised into a lesson blames the lessons asked in the deciding session before the
39//!   decision (`regretted`): asking did not prevent it. `credit` carries each lesson's share of the blame;
40//!   memory.rs weighs it below a correction. Deliberately not read by trust.rs (`sessions`), by `weight`
41//!   (the legacy single-number view) or by attention.rs: a regret is about a lesson, not about an
42//!   engineer following it.
43//!
44//! - `tested` (`borg learn`, 0 tokens): the session's own test runs (hook.rs `capture_test`) ended green
45//!   after a lesson was asked as a question (a free delivery is none): a failed run after the ask, then a
46//!   pass, or a pass after the drone changed its work on the lesson's point (`asked_then_changed`); never
47//!   for a question the drone ignored (`asked_then_ignored`). A
48//!   weak credit (memory.rs `TESTED_W`), once per (session, lesson) (`tested`). It is about the work,
49//!   not about an engineer following a lesson: never a use, and not read by trust.rs, `weight` or
50//!   attention.rs.
51//!
52//! An unclear verdict (`asked_unclear`, measured, never a result), a remaining consequence
53//! (`asked_consequence_remains`, the same), or a session whose later turn ends
54//! never reach the model (the prefilter skipped them, or BORG_MATCH=bm25), leaves the lesson pending:
55//! `settle` turns it into `asked_not_corrected` with the reason it had no verdict (`reason`). That is
56//! censored for beliefs (memory.rs): no correction followed, but whether the drone acted on the lesson
57//! is unknown.
58//!
59//! - `delivery` (hook, local): per graded check and lesson, the route delivery actually took (`route`:
60//!   asked, free, placebo, dropped because done or over the character budget, never delivered) and why,
61//!   so what a check decided (`graded`) and what reached the drone never disagree unseen.
62//! - A placebo (hook.rs `#borg-placebo`): an apply the check routed nowhere, judged blindly where a free
63//!   delivery would be. Its results carry channel `placebo` (`PLACEBO`): the judge's floor, no result for
64//!   any reader that learns from results (`is_result`), never shared. One the judge never gave a verdict
65//!   settles as `asked_not_corrected` on that channel with its reason (`settle_with`), as an unjudged ask
66//!   does: the selection summary censors it (select/summary.rs `settled`).
67//!
68//! `asked` and `graded` records carry `p`, each lesson's probability of being asked under the policy in
69//! force at that check (its propensity), for off-policy evaluation of another policy from this log. An
70//! `asked` record from a Thompson slot draw (the bm25 and non-graded paths) also carries that draw's
71//! pool (`pool`, `base`, `scoped`): every competitor with its score before the usefulness factor, so
72//! `borg debug ope` (ope.rs) can recompute the propensity under other belief weights. Local only: the team
73//! projection drops them.
74//!
75//! **Team outcomes.** The raw log stays on this machine (it holds session ids and repos). `publish`
76//! appends a redacted, deterministic projection of the results the team may see (`SHARED_KINDS`) to
77//! `outcomes-team.jsonl` (`TEAM_FILE`), which the mesh syncs (borg-mesh lines.rs `SYNCED`): kind,
78//! lesson ids, time, propensity, channel, the hashed session and repo (`tag`), a regret's hashed cause
79//! and credit, and the node, never raw sessions, repos, causes, groups, grades or text. Only the belief readers opt in to the team view
80//! (`read_team`): memory and trust in the conscience (conscience.rs `load_as`), `borg trust`, `borg
81//! memory` and borg-web's lessons. learn.rs (it would settle remote sessions), attention.rs (labels and
82//! the explore counter are this node's policy), stats.rs (rollups sync their own counts), install.rs and
83//! the hook's pending/judge read this machine's log only. BORG_SHARE_OUTCOMES=off publishes and reads
84//! nothing of the team's.
85//!
86//! A session counts once per lesson. If a resumed session gets both results, corrected wins.
87//! memory.rs derives activation and the usefulness belief from these results; `weight` below is the
88//! earlier, single-number view (kept for reporting and for comparison in the R1 replay).
89
90use std::collections::HashMap;
91use std::path::Path;
92
93use serde::{Deserialize, Serialize};
94
95pub const ASKED: &str = "asked";
96pub const CORRECTED: &str = "asked_then_corrected";
97pub const NOT_CORRECTED: &str = "asked_not_corrected";
98pub const CHANGED: &str = "asked_then_changed";
99pub const IGNORED: &str = "asked_ignored";
100/// One graded check: every lesson the model graded as applying (`lessons`, in its order, with
101/// `grades` and `ranks`), and which of them the check chose to ask (`chosen`). The denominator for
102/// learning how many to ask: a lesson that applied but was not chosen can still turn out needed.
103pub const GRADED: &str = "graded";
104/// A lesson a graded check of the session found applying but did not ask, which a later correction
105/// in that session then merged into or superseded: a question that was needed and not asked (`missed`).
106pub const MISSED: &str = "applied_then_corrected";
107/// The engineer vetoed the session's work (`borg no`, veto.rs): every lesson shown in the session
108/// before it is credited. The strongest negative result.
109pub const VETOED: &str = "vetoed";
110/// A lesson asked in a session before a decision that a later fix (or a review finding) showed was
111/// wrong (learn.rs `credit_regrets`): asking did not prevent it. `cause` names the regret episode and
112/// `credit` carries the share of the blame, (0, 1]. Weaker than a correction (memory.rs `REGRET`).
113pub const REGRETTED: &str = "regretted";
114
115/// The session's own tests went green after the lesson was asked (`tested`): red then green, or green
116/// after a change on the lesson's point. Once per (session, lesson), dated at that pass.
117pub const TESTED: &str = "tested";
118
119/// The judge saw the lesson's delivery but could not tell (an `unclear` verdict): the lesson stays
120/// pending for another try. A label-health measurement only: no belief, trust, statistic, team line or
121/// off-policy decision reads it (`counts`). Before 0.7.5 a change that still leads to the consequence
122/// was written as this kind too (now `REMAINS`), so an older record means either.
123pub const UNCLEAR: &str = "asked_unclear";
124
125/// The judge found the lesson's point never came up in the work since its delivery (`not_arisen`,
126/// predict.rs `Verdict::NotArisen`): a verdict that settles the delivery (`settles`), but no evidence
127/// about the lesson's usefulness, so no result (`is_result`) for beliefs, trust, the statistics, the
128/// team file or the off-policy log. The selection summary reads it as "nothing in the work": no change
129/// on the lesson's point (select/summary.rs `Label::NotArisen`).
130pub const NOT_ARISEN: &str = "asked_not_arisen";
131
132/// The judge found the drone changed its work on the lesson's point but the work still leads to the
133/// consequence (`consequence_remains`): `UNCLEAR`'s semantics (pending for another try, a measurement
134/// only, no result), kept apart so the pure unclear share is measured.
135pub const REMAINS: &str = "asked_consequence_remains";
136
137/// A judge result's `at` when the session-end judge gave it (hook.rs `judge_session`, at `borg learn
138/// --session`): with the whole session's work in view, after every check of the session. Protocol: empty
139/// for a check's verdict (a stop or a live check), so its records stay as before.
140pub const AT_END: &str = "end";
141
142/// Whether a judge result of `kind` settles its delivery: a use (`CHANGED`), an ignore (`IGNORED`) or
143/// nothing to judge (`NOT_ARISEN`). An unclear verdict and a remaining consequence leave it pending.
144#[must_use]
145pub fn settles(kind: &str) -> bool {
146    matches!(kind, CHANGED | IGNORED | NOT_ARISEN)
147}
148
149/// What delivery did with a graded check's decision, per check and lesson (hook.rs): `route` (one of
150/// `ROUTES`), `reason`, `check` the check that decided it. The latest record per (check, lesson) is
151/// the route it took (a session that ends with a lesson queued gets `never_delivered`; resumed, its
152/// later delivery supersedes that). Local and never a result: the denominator of what each route led
153/// to, read by the selection replay (select.rs), not by beliefs.
154pub const DELIVERY: &str = "delivery";
155
156/// The session's end hook ran (hook.rs `on_end`), after its `never_delivered` records: one per end, a
157/// resumed session's again at its next. Local and never a result: where the selection summary counts a
158/// session's delivery tallies (select/summary.rs), whatever else the session logged, so a session with
159/// nothing queued and no ask left open counts too.
160pub const ENDED: &str = "ended";
161
162/// The channel of a placebo's judge results (`asked_then_changed`, `asked_ignored`, `asked_unclear`, and
163/// from 0.7.5 `asked_not_arisen`, `asked_consequence_remains`): a
164/// graded apply never delivered, judged blindly where a free delivery would be (hook.rs `#borg-placebo`).
165/// Its "changed" rate is the judge's own false positives plus what the drone would have done anyway, so
166/// it is never a result about the lesson (`is_result`).
167pub const PLACEBO: &str = "placebo";
168
169/// Whether `o` is evidence about its lessons for the readers that learn from results (memory.rs, trust.rs,
170/// the statistics, the team file): not a placebo's result (`PLACEBO`), not an unclear verdict
171/// (`UNCLEAR`), not a change that leaves the consequence (`REMAINS`) and not a point that never came up
172/// (`NOT_ARISEN`, censored).
173#[must_use]
174pub fn is_result(o: &Outcome) -> bool {
175    o.channel != PLACEBO && !matches!(o.kind.as_str(), UNCLEAR | REMAINS | NOT_ARISEN)
176}
177
178/// Why a lesson settled as `asked_not_corrected` had no verdict (`reason`, `settle_why`). Protocol: the
179/// judge gave one (`UNJUDGED_NONE`, the settle only says no correction followed); its tries ran out on
180/// unclear or missing verdicts (hook.rs `MAX_JUDGE_TRIES`); a fuller judge call left it out
181/// (hook.rs `MAX_PENDING`); its last judge call failed; no model call came after its delivery; or (a
182/// placebo) a later delivery of the lesson in the session took its place in the judge's queue
183/// (`UNJUDGED_LATER`, hook.rs `pending`).
184pub const UNJUDGED_NONE: &str = "judged";
185pub const UNJUDGED_TRIES: &str = "tries";
186pub const UNJUDGED_SLOTS: &str = "slots";
187pub const UNJUDGED_FAILED: &str = "failed";
188pub const UNJUDGED_NO_CALL: &str = "no_call";
189pub const UNJUDGED_LATER: &str = "later";
190
191/// Why a `graded` record's check took the fixed rule instead of the learned policy in force (`reason`;
192/// empty when it decided by the policy in force, hook.rs `decide`). Protocol: another check held the
193/// store's decision lock past hook.rs `DECIDE_WAIT`, the lock could not be taken at all, or the learned
194/// decision's record would not or did not land in the log its gate is folded from (learning off, a
195/// `BORG_CONSCIENCE` outside the store the hook records to, a failed append), so its gate would never be
196/// debited for it. Only the learned policy reads the gate and takes the lock; such a record carries
197/// `policy` fixed and is replayed as the fixed rule.
198pub const DECIDED_BUSY: &str = "lock_busy";
199pub const DECIDED_NO_LOCK: &str = "lock_failed";
200pub const DECIDED_NO_RECORD: &str = "unrecorded";
201
202/// What one correction adds against a lesson, in units of an ignore: a correction of the same concern
203/// right after asking is strong evidence the question did not help, a session without one weak evidence
204/// (the engineer may not have looked). Baseline: design-chosen (no evaluation behind the 2), used by
205/// `weight` and memory.rs `Memory::beta_with` alike; `borg debug ope` (ope.rs) estimates other belief
206/// weights offline, never applies them. Fixed by dated decision (2026-10-31): 1–2 corrections after an
207/// ask per store, and `borg debug ope` finds 0 usable decisions.
208pub const CORRECTED_W: u32 = 2;
209
210/// A session without asks or episodes for this long is treated as ended (24h). Guard: a session whose
211/// `end` hook never ran would otherwise never settle; its state file must be as quiet (learn.rs).
212pub const IDLE_MS: i64 = crate::clock::DAY_MS;
213
214#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
215pub struct Outcome {
216    pub kind: String,
217    pub session: String,
218    pub lessons: Vec<String>,
219    pub ms: i64,
220    pub repo: String,
221    /// `asked` only: the asked lessons rendered as one disagreement (conscience.rs `disagreements`).
222    #[serde(default, skip_serializing_if = "Vec::is_empty")]
223    pub groups: Vec<Vec<String>>,
224    /// How the lessons were asked (`asked` and the judge's results): `stop` (a turn-end block), `live`
225    /// (a live check during the turn, live.rs), `early` (early delivery, conscience.rs `early`),
226    /// `queued` (a graded check's 2s and 1s, handed over free) or `placebo` (`PLACEBO`: never shown,
227    /// judged blindly where a free delivery would be). Empty in records from before delivery modes.
228    #[serde(default, skip_serializing_if = "String::is_empty")]
229    pub channel: String,
230    /// `graded` and `asked`: each lesson's grade (3 certain, 2 likely, 1 worth a thought) and its rank in
231    /// the model's applies (0 first), aligned with `lessons`, and how many lessons the check graded as
232    /// applying; on `asked`, 0 where no check of the session graded the lesson. For learning how many to
233    /// ask (attention.rs reads them from `graded`).
234    #[serde(default, skip_serializing_if = "Vec::is_empty")]
235    pub grades: Vec<u8>,
236    #[serde(default, skip_serializing_if = "Vec::is_empty")]
237    pub ranks: Vec<u16>,
238    #[serde(default, skip_serializing_if = "is_zero")]
239    pub applied: u16,
240    /// `graded` only: the lessons the check chose to ask.
241    #[serde(default, skip_serializing_if = "Vec::is_empty")]
242    pub chosen: Vec<String>,
243    /// `graded` only: the check explored, asking every apply up to `attention::RAIL` whatever the cut,
244    /// so its outcomes label the cut (attention.rs).
245    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
246    pub explore: bool,
247    /// `regretted`: the regret episode (`R…`/`V…` id). The idempotence key with the lesson.
248    #[serde(default, skip_serializing_if = "String::is_empty")]
249    pub cause: String,
250    /// `regretted` only: the lesson's share of the regret, (0, 1].
251    #[serde(default, skip_serializing_if = "is_zero_f")]
252    pub credit: f64,
253    /// `asked` and `graded`: per lesson (aligned with `lessons`), the probability that the policy in force
254    /// at that check asked it: 1 or 0 under the fixed graded rule, the explore mixture under the learned
255    /// cut (attention.rs `propensities`), the share of Thompson draws that give it a slot in
256    /// `budget`/`widen` (conscience.rs `propensity`), the share that delivers it early (conscience.rs
257    /// `early_propensity`), 1 for a free hand-over of a graded check's 2s and 1s. Rounded to 4 decimals
258    /// (`round_p`). Empty in records from before propensities and when unknown (BORG_ONLY, a state file
259    /// from an older binary). For off-policy evaluation (ope.rs).
260    #[serde(default, skip_serializing_if = "Vec::is_empty")]
261    pub p: Vec<f64>,
262    /// `asked` from a Thompson slot draw only (conscience.rs `budget_pool`/`widen_pool`, hook.rs
263    /// `#borg-pool`): the pool the check drew from, in ranking order, the asked lessons included; each
264    /// one's score without its usefulness factor (conscience.rs `pool_base`, unrounded so a replay is
265    /// exact); and whether it is scoped. Aligned with each other, not with `lessons`. Empty for graded
266    /// and live asks and free deliveries. Local: never shared (`share`). For `borg debug ope` (ope.rs).
267    #[serde(default, skip_serializing_if = "Vec::is_empty")]
268    pub pool: Vec<String>,
269    #[serde(default, skip_serializing_if = "Vec::is_empty")]
270    pub base: Vec<f64>,
271    #[serde(default, skip_serializing_if = "Vec::is_empty")]
272    pub scoped: Vec<bool>,
273    // The selection fields (select.rs). Every one is left out when empty, so a record without them
274    // writes the line an older binary wrote, and an older line reads with them empty. Local: `share`
275    // copies none of them.
276    /// The graded check (select.rs `check_id`): on `graded`, and on every record of a lesson that check
277    /// routed (its delivery, the judge's result, a placebo's), so a result joins the decision that made
278    /// it. Empty in records from before checks had ids.
279    #[serde(default, skip_serializing_if = "String::is_empty")]
280    pub check: String,
281    /// `graded`: the selection policy in force (select.rs `Policy::name`: fixed, cap, attention,
282    /// learned). Empty in records from before select.rs, which read as the fixed rule (`policy_of`).
283    #[serde(default, skip_serializing_if = "String::is_empty")]
284    pub policy: String,
285    /// `graded`: the fit the policy decided with (select/policy.rs `Fit::key`); empty for the prior.
286    #[serde(default, skip_serializing_if = "String::is_empty")]
287    pub fit: String,
288    /// `graded`: the selection summary the decision read (select/summary.rs `Summary::key`: the bytes
289    /// folded and their hash), and what set its routes (select.rs `Log::source`). A learned check reads
290    /// the summary again under the store's decision lock after its model call (hook.rs `decide`), so
291    /// every learned decision recorded before it is in it; a check by a policy that reads no gate, and
292    /// one that fell back to the fixed rule (`reason`), names the summary it read at its start, which
293    /// records of checks that decided meanwhile may follow. Records other than decisions (a delivery, a
294    /// verdict) may still land between that read and this record; `borg debug select` P1 replays from
295    /// the logged state.
296    /// Empty in older records and for a failed call.
297    #[serde(default, skip_serializing_if = "String::is_empty")]
298    pub seen: String,
299    #[serde(default, skip_serializing_if = "String::is_empty")]
300    pub source: String,
301    /// `graded`: the lessons the check handed over free, in delivery order (`free_of` for older records).
302    #[serde(default, skip_serializing_if = "Vec::is_empty")]
303    pub free: Vec<String>,
304    /// `graded`: per lesson (aligned with `lessons`), its probability of being handed over free under
305    /// the policy in force, as `p` is of being asked; rounded like `p`. Empty in older records, where
306    /// a free lesson's was 1 under the fixed rule.
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub pf: Vec<f64>,
309    /// `graded`: the applies the check did not deliver and drew for the placebo arm (judged blindly
310    /// where a free delivery would be, never shown), and each undelivered apply's chance of that draw.
311    #[serde(default, skip_serializing_if = "Vec::is_empty")]
312    pub placebo: Vec<String>,
313    #[serde(default, skip_serializing_if = "is_default")]
314    pub psi: f64,
315    /// `graded`: the graded applies that could not go free at this check because the session already
316    /// had them delivered (select.rs `Ctx::had`, conscience.rs `graded_without`), in the applies' order:
317    /// the applies among the session's deliveries when the check decided, and among the lessons waiting
318    /// in its queue to be asked or handed over by another check (hook.rs `decide`, `waiting_in`), so the
319    /// record alone holds every `had` that bears on its decision.
320    #[serde(default, skip_serializing_if = "Vec::is_empty")]
321    pub nofree: Vec<String>,
322    /// `graded`, a check of the randomised question-count test (select/policy.rs `Decision::xk`,
323    /// sources `experiment`, `experiment_control` and `gate`): `xk` the fixed rule's delivered non-3
324    /// lessons that may go free (k), `xs` how many of them it asked (s, drawn uniformly in 0..=k; 0 is
325    /// logged). None on every other record, so older lines and checks outside the test write back
326    /// unchanged. Local like the rest of a graded record (`share`).
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub xk: Option<u32>,
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub xs: Option<u32>,
331    /// `graded`: the collective's tolerance the check was decided under (select.rs `Log::alpha`, its
332    /// `risk`), so a replay decides under it whatever the config says then; None at the default
333    /// (select/policy.rs `ALPHA`), so older lines and default collectives write back unchanged.
334    #[serde(default, skip_serializing_if = "Option::is_none")]
335    pub alpha: Option<f64>,
336    /// `graded`: the lessons the pool budget dropped from the model call that a tail sample showed
337    /// anyway (whole.rs `tail`, under every policy), and each one's chance of being sampled (one chance
338    /// for all of the check's tail: k drawn uniformly of the `eligible` − `shown` dropped, unrounded).
339    /// Not in `shown` or `tokens`; each has its place past the budget's in `fill`, after the applies'
340    /// (and, if it applies, among them too), so every place from `shown` to `eligible` − 1 is one
341    /// dropped lesson, shown with chance `pt`.
342    #[serde(default, skip_serializing_if = "Vec::is_empty")]
343    pub tail: Vec<String>,
344    #[serde(default, skip_serializing_if = "is_default")]
345    pub pt: f64,
346    /// An early delivery's record: per lesson (aligned with `lessons`), its score as a share of the best
347    /// on-topic match, done or not (conscience.rs `early_pool`, the share `RELATIVE` bars; hook.rs
348    /// `early_rel`), rounded as `p` is, for a learned early rule. A standing lesson has one too, though
349    /// no score gates it; empty when no plain lesson was on topic to scale by.
350    #[serde(default, skip_serializing_if = "Vec::is_empty")]
351    pub rel: Vec<f64>,
352    /// A delivery's actual route for every lesson of the record (one of `ROUTES`), and why: a drop's
353    /// cause, or why a delivered lesson stayed unjudged (no later call, the judge's slots, its tries);
354    /// on `graded`, why its check fell back to the fixed rule (`DECIDED_BUSY`, `DECIDED_NO_LOCK`,
355    /// `DECIDED_NO_RECORD`).
356    #[serde(default, skip_serializing_if = "String::is_empty")]
357    pub route: String,
358    #[serde(default, skip_serializing_if = "String::is_empty")]
359    pub reason: String,
360    /// `graded`, the pool the model graded: lessons eligible for it, lessons its budget showed, their
361    /// size in tokens (the tail sample beside them in `tail`), and per lesson (aligned with `lessons`)
362    /// its fill position among the shown (0 first), so the yield of each position can be learned from
363    /// every check, a check without applies included; then, past the applies', one position per tail
364    /// lesson (aligned with `tail`), so the yield past the budget is learned from the lessons a tail
365    /// showed that did not apply too (select/summary.rs `tail_of`). A tail lesson's position goes on
366    /// past the budget's: `shown` + its place among the lessons the budget dropped, in the order the
367    /// fill met them (whole.rs `Filled::dropped`), so it is never below `shown`.
368    #[serde(default, skip_serializing_if = "is_default")]
369    pub eligible: u32,
370    #[serde(default, skip_serializing_if = "is_default")]
371    pub shown: u32,
372    #[serde(default, skip_serializing_if = "is_default")]
373    pub tokens: u32,
374    /// `graded`, the pool's token budget its check filled to (hook.rs `check`: `BORG_STOP_POOL_TOKENS`,
375    /// else select.rs `pool_tokens`), so a check at a budget other than the baseline shows. 0: not
376    /// logged (a record from before 0.7.3, or a check without the whole pool).
377    #[serde(default, skip_serializing_if = "is_default")]
378    pub budget: u32,
379    #[serde(default, skip_serializing_if = "Vec::is_empty")]
380    pub fill: Vec<u16>,
381    /// `graded`, the model call: the model (empty: the CLI's default), a hash of the prompt template,
382    /// the harness, borg's version, the call's duration, and whether it failed (the check then asked
383    /// nothing: fail open); then its cost (`usd`).
384    #[serde(default, skip_serializing_if = "String::is_empty")]
385    pub model: String,
386    #[serde(default, skip_serializing_if = "String::is_empty")]
387    pub prompt_hash: String,
388    #[serde(default, skip_serializing_if = "String::is_empty")]
389    pub harness: String,
390    #[serde(default, skip_serializing_if = "String::is_empty")]
391    pub version: String,
392    #[serde(default, skip_serializing_if = "is_default")]
393    pub dur_ms: u64,
394    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
395    pub failed: bool,
396    /// `graded`: the call's cost in dollars as the harness's CLI reported it (0: it reported none).
397    /// Measured and shown (`borg debug select` P3), never a limit.
398    #[serde(default, skip_serializing_if = "is_default")]
399    pub usd: f64,
400    /// The judge's results (`asked_then_changed`, `asked_ignored`): the judge template's version, 0 for
401    /// the template before versions were logged; and whether the judge saw the question without the
402    /// drone's `<id>: applies|skip` declaration (a random half are, to measure what it adds).
403    #[serde(default, skip_serializing_if = "is_default")]
404    pub judge: u8,
405    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
406    pub stripped: bool,
407    /// The judge's results (0.7.5 on): per lesson (aligned with `lessons`), the judge's short reason for
408    /// its verdict, redacted and at most predict.rs `JUDGE_REASON_CHARS`; empty where it gave none.
409    /// Empty in older records. Local: never shared (`share`), never read as a result.
410    #[serde(default, skip_serializing_if = "Vec::is_empty")]
411    pub reasons: Vec<String>,
412    /// The judge's results (0.7.5 on): where the verdict was given, `AT_END` at the session-end judge
413    /// (hook.rs `judge_session`); empty at a check (a stop or a live check) and in older records. Local.
414    #[serde(default, skip_serializing_if = "String::is_empty")]
415    pub at: String,
416}
417
418/// `route` values. Protocol: what a check decided for a lesson, then what delivery did with it.
419/// Asked, handed over free, or judged as a placebo, as decided; or dropped at delivery because the
420/// session had the lesson already (`ROUTE_DROPPED_DONE`) or the delivery budget was spent
421/// (`ROUTE_DROPPED_CHARS`); or never delivered because the session ended first (`ROUTE_NEVER`).
422pub const ROUTE_ASKED: &str = "asked";
423pub const ROUTE_FREE: &str = "free";
424pub const ROUTE_PLACEBO: &str = "placebo";
425pub const ROUTE_DROPPED_DONE: &str = "dropped_done";
426pub const ROUTE_DROPPED_CHARS: &str = "dropped_chars";
427pub const ROUTE_NEVER: &str = "never_delivered";
428pub const ROUTES: [&str; 6] = [ROUTE_ASKED, ROUTE_FREE, ROUTE_PLACEBO, ROUTE_DROPPED_DONE, ROUTE_DROPPED_CHARS, ROUTE_NEVER];
429
430/// The policy a `graded` record was decided under: its `policy`; for a record from before select.rs,
431/// the fixed rule (`fixed`), unless it shows the one other policy an older binary logged,
432/// `BORG_STOP_ATTENTION=on`'s learned cut (`attention`): it explored, or a propensity lies strictly
433/// between 0 and 1 (attention.rs `propensities`). A learned cut that asked every apply up to its rail
434/// logged only 0s and 1s, and an evaluation's `BORG_STOP_ASK_CAP` logged nothing of its cap: both read
435/// as the fixed rule.
436#[must_use]
437pub fn policy_of(o: &Outcome) -> &str {
438    match o.policy.as_str() {
439        "" if o.explore || o.p.iter().any(|p| *p > 0.0 && *p < 1.0) => "attention",
440        "" => "fixed",
441        p => p,
442    }
443}
444
445/// The lessons a `graded` record handed over free: its `free`; for a record from before select.rs
446/// (`policy` empty), its policy's rule (`policy_of`) replayed on its grades: the fixed rule's 2s, then
447/// 1s, at most `conscience::CAP`, when no lesson is a 3 (conscience.rs `graded_capped`), else none; the
448/// learned cut's lessons after the ones it asked, at most `conscience::CAP` (attention.rs `split`).
449#[must_use]
450pub fn free_of(o: &Outcome) -> Vec<String> {
451    use crate::conscience::{self, Challenge};
452    if !o.policy.is_empty() || o.grades.len() != o.lessons.len() {
453        return o.free.clone();
454    }
455    if o.grades.contains(&3) {
456        return match policy_of(o) {
457            "attention" => o.lessons.iter().filter(|l| !o.chosen.contains(l)).take(conscience::CAP).cloned().collect(),
458            _ => Vec::new(),
459        };
460    }
461    let ls: Vec<Challenge> = o.lessons.iter().map(|id| Challenge { id: id.clone(), ..Default::default() }).collect();
462    let applied: Vec<(&Challenge, u8)> = ls.iter().zip(o.grades.iter().copied()).collect();
463    conscience::graded_capped(&applied, None).1.into_iter().map(|c| c.id.clone()).collect()
464}
465
466fn is_default<T: Default + PartialEq>(v: &T) -> bool {
467    *v == T::default()
468}
469
470/// A propensity rounded to 4 decimals, so lines stay deterministic and short.
471pub fn round_p(p: f64) -> f64 {
472    (p * 1e4).round() / 1e4
473}
474
475fn is_zero(v: &u16) -> bool {
476    *v == 0
477}
478
479fn is_zero_f(v: &f64) -> bool {
480    *v == 0.0
481}
482
483/// The outcomes store next to a lessons file.
484pub fn path_beside(lessons: &Path) -> std::path::PathBuf {
485    lessons.with_file_name("outcomes.jsonl")
486}
487
488/// The redacted outcomes the team sees, at the store root beside `outcomes.jsonl` (module doc).
489pub const TEAM_FILE: &str = "outcomes-team.jsonl";
490/// Beside `TEAM_FILE`, never synced: the length of `outcomes.jsonl` at the last `publish`.
491pub const PUBLISHED: &str = "outcomes-team.published";
492
493/// The kinds `publish` shares. A whitelist: `graded` and any later kind stay local until deliberately
494/// added here.
495///
496/// Closed under memory.rs `derive`: every kind that changes a lesson's result for a session, or its
497/// belief, travels, so a peer folds the same memory. `vetoed` outranks the session's `changed` (shared
498/// alone, a lesson vetoed here would gain a use and spread there); `regretted` carries its `credit` and
499/// its hashed `cause` (`Shared::c`), the key derive dedupes regrets by. `graded` is the asking policy's
500/// denominator, not a result, and never moves the activity clock (`memory::Clock` counts shared kinds).
501///
502/// Unguarded: any member can write a line under any session tag (tags are public in this file), so a
503/// forged `asked_then_corrected` or `vetoed` overrides a teammate's session on every node but that
504/// teammate's, and a few forged `asked_then_changed` with fresh tags and two repo tags consolidate a
505/// lesson. `node` is self-declared. The mesh admits only members' signed lines (borg-mesh origin.rs),
506/// so this is the trusted-member model; the deferred guards (a session tag bound to its first signer,
507/// consolidation from at least two signers) would close it.
508///
509/// `tested` is shared like `asked_then_changed`, the result it is weaker than: memory folds it, so a peer
510/// without it would hold another belief. Both are this node's own reading of its session (the judge's,
511/// the test runner's output), so the trusted-member model above is the same;
512/// `team_view` counts a peer's `tested` line only for lessons the team's records show its session was
513/// given. It never moves the activity clock either.
514pub const SHARED_KINDS: [&str; 9] = [ASKED, CHANGED, IGNORED, CORRECTED, NOT_CORRECTED, MISSED, VETOED, REGRETTED, TESTED];
515
516/// A session or repo as the team sees it: the first 32 hex digits of blake3("borg-outcome-v1\0" + s).
517/// Unsalted on purpose: the same session hashes to the same tag on every node, so a node can drop its
518/// own published copies (`read_team`).
519pub fn tag(s: &str) -> String {
520    let mut h = blake3::Hasher::new();
521    h.update(b"borg-outcome-v1\0");
522    h.update(s.as_bytes());
523    h.finalize().to_hex()[..32].to_string()
524}
525
526/// `tag`, keeping an empty repo empty.
527fn tag_repo(repo: &str) -> String {
528    if repo.is_empty() { String::new() } else { tag(repo) }
529}
530
531/// One line of `TEAM_FILE`. Never carries `id` and `version` together (the mesh would settle it as a
532/// versioned record).
533#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
534pub struct Shared {
535    pub kind: String,
536    /// `tag` of the session.
537    pub s: String,
538    pub lessons: Vec<String>,
539    pub ms: i64,
540    /// The publishing node (stats.rs `node`), self-declared: dedup does not depend on it.
541    pub node: String,
542    #[serde(default, skip_serializing_if = "Vec::is_empty")]
543    pub p: Vec<f64>,
544    #[serde(default, skip_serializing_if = "String::is_empty")]
545    pub channel: String,
546    /// `tag` of the repo: memory.rs counts distinct repos to consolidate a lesson.
547    #[serde(default, skip_serializing_if = "String::is_empty")]
548    pub r: String,
549    /// `tag` of a `regretted` record's cause (the regret episode): memory.rs counts each regret once.
550    #[serde(default, skip_serializing_if = "String::is_empty")]
551    pub c: String,
552    /// A `regretted` record's share of the blame.
553    #[serde(default, skip_serializing_if = "is_zero_f")]
554    pub credit: f64,
555}
556
557/// `o` as the team sees it, or None for a kind not in `SHARED_KINDS` and for a placebo's result
558/// (`is_result`): the judge's floor on this node, never a result a peer folds.
559pub fn share(o: &Outcome, node: &str) -> Option<Shared> {
560    (SHARED_KINDS.contains(&o.kind.as_str()) && is_result(o)).then(|| Shared {
561        kind: o.kind.clone(),
562        s: tag(&o.session),
563        lessons: o.lessons.clone(),
564        ms: o.ms,
565        node: node.into(),
566        p: o.p.clone(),
567        channel: o.channel.clone(),
568        r: tag_repo(&o.repo),
569        c: tag_repo(&o.cause),
570        credit: o.credit,
571    })
572}
573
574/// Team outcomes on: `BORG_SHARE_OUTCOMES` is not `off`.
575pub fn on() -> bool {
576    std::env::var("BORG_SHARE_OUTCOMES").as_deref() != Ok("off")
577}
578
579/// Appends to `TEAM_FILE` in `home` the shared lines of `home`'s `outcomes.jsonl` it lacks; returns
580/// how many. The lines are deterministic, so a re-run appends nothing; two runs at once may append the
581/// same line twice, which the mesh's union and the per-session count make harmless. Nothing when off.
582/// A local log no longer than at the last publish (`PUBLISHED`, its length then) is not read again: the
583/// log only grows, so nothing new can be in it.
584pub fn publish(home: &Path) -> usize {
585    let local = home.join("outcomes.jsonl");
586    let team = home.join(TEAM_FILE);
587    let mark = home.join(PUBLISHED);
588    let len = std::fs::metadata(&local).map_or(0, |m| m.len());
589    if !on() || len == 0 {
590        return 0;
591    }
592    let published = std::fs::read_to_string(&mark).ok().and_then(|t| t.trim().parse::<u64>().ok());
593    if team.exists() && published == Some(len) {
594        return 0;
595    }
596    let mine = std::fs::read_to_string(&local).unwrap_or_default();
597    let node = crate::stats::node(home);
598    let text = std::fs::read_to_string(&team).unwrap_or_default();
599    let mut have: std::collections::HashSet<String> = text.lines().map(str::to_string).collect();
600    let mut out = String::new();
601    // This engineer's personal lessons (reach.rs) are no team's business, not even by id.
602    let personal = crate::reach::personal_ids(home);
603    let records = mine.lines().filter_map(|l| serde_json::from_str::<Outcome>(l).ok()).filter_map(|mut o| {
604        let named = !o.lessons.is_empty();
605        o.lessons.retain(|id| !personal.contains(id));
606        (!named || !o.lessons.is_empty()).then_some(o)
607    });
608    for line in records.filter_map(|o| share(&o, &node)).filter_map(|x| serde_json::to_string(&x).ok()) {
609        if have.insert(line.clone()) {
610            out.push_str(&line);
611            out.push('\n');
612        }
613    }
614    if out.is_empty() {
615        let _ = std::fs::write(&mark, mine.len().to_string());
616        return 0;
617    }
618    use std::io::Write;
619    let open = text.as_bytes().last().is_some_and(|c| *c != b'\n');
620    let written = std::fs::OpenOptions::new()
621        .create(true)
622        .append(true)
623        .open(&team)
624        .and_then(|mut f| f.write_all(format!("{}{out}", if open { "\n" } else { "" }).as_bytes()));
625    if written.is_err() {
626        return 0;
627    }
628    let _ = std::fs::write(&mark, mine.len().to_string());
629    out.lines().count()
630}
631
632/// The belief view of the outcomes beside `lessons`: this machine's log plus, unless
633/// BORG_SHARE_OUTCOMES=off, the team's (`team_view`).
634pub fn read_team(lessons: &Path) -> Vec<Outcome> {
635    team_view(lessons, on())
636}
637
638/// Off: this machine's log as is. On: its records with each repo and cause as its `tag` (memory.rs only
639/// compares them for distinctness, so beliefs are the same and comparable with the team's), then the
640/// team's lines that count (`team_parts`). A remote session then counts once per lesson like a local
641/// one (memory.rs `derive`, `sessions`). learn.rs keys on raw causes: it reads this
642/// machine's log (`read`).
643pub fn team_view(lessons: &Path, on: bool) -> Vec<Outcome> {
644    let (mut out, team) = team_parts(lessons, on);
645    if on {
646        for o in &mut out {
647            o.repo = tag_repo(&o.repo);
648            o.cause = tag_repo(&o.cause);
649        }
650    }
651    out.extend(team);
652    out
653}
654
655/// This machine's records as written, and (on) every `TEAM_FILE` line of a shared kind whose session
656/// is not one of this machine's (that drops this node's own published copies, whatever its node id),
657/// once per (kind, session, lessons, ms, cause): one read of each file, so the two never disagree on
658/// where the local records end (ope.rs reads both). A kind this binary does not share (a newer node's,
659/// or an older one's hive verdict) is ignored, and so is a `tested` line naming a lesson the team's
660/// records do not show its session was given.
661pub fn team_parts(lessons: &Path, on: bool) -> (Vec<Outcome>, Vec<Outcome>) {
662    let local = read(&path_beside(lessons));
663    if !on {
664        return (local, Vec::new());
665    }
666    let mine: std::collections::HashSet<String> = local.iter().map(|o| tag(&o.session)).collect();
667    let text = std::fs::read_to_string(lessons.with_file_name(TEAM_FILE)).unwrap_or_default();
668    let lines: Vec<Shared> = text.lines().filter_map(|l| serde_json::from_str::<Shared>(l).ok()).collect();
669    // The lessons each team session's shared records name: a green run credits only lessons it was given.
670    let mut given: std::collections::HashMap<&str, std::collections::HashSet<&str>> = std::collections::HashMap::new();
671    for x in lines.iter().filter(|x| SHARED_KINDS.contains(&x.kind.as_str()) && x.kind != TESTED) {
672        given.entry(x.s.as_str()).or_default().extend(x.lessons.iter().map(String::as_str));
673    }
674    let mut seen: std::collections::HashSet<(String, String, Vec<String>, i64, String)> = std::collections::HashSet::new();
675    let mut team = Vec::new();
676    for x in lines.iter() {
677        if !SHARED_KINDS.contains(&x.kind.as_str()) || mine.contains(&x.s) || !seen.insert((x.kind.clone(), x.s.clone(), x.lessons.clone(), x.ms, x.c.clone()))
678        {
679            continue;
680        }
681        if x.kind == TESTED && !x.lessons.iter().all(|l| given.get(x.s.as_str()).is_some_and(|g| g.contains(l.as_str()))) {
682            continue;
683        }
684        team.push(Outcome {
685            kind: x.kind.clone(),
686            session: x.s.clone(),
687            lessons: x.lessons.clone(),
688            ms: x.ms,
689            repo: x.r.clone(),
690            p: x.p.clone(),
691            channel: x.channel.clone(),
692            cause: x.c.clone(),
693            credit: x.credit,
694            ..Default::default()
695        });
696    }
697    (local, team)
698}
699
700pub fn read(path: &Path) -> Vec<Outcome> {
701    std::fs::read_to_string(path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
702}
703
704/// Appends `o` in one write (learn.rs `append_line`: concurrent writers never tear a record), and
705/// counts it in the usage statistics (`count_result`).
706pub fn append(path: &Path, o: &Outcome) -> std::io::Result<()> {
707    crate::learn::append_jsonl(path, o)?;
708    if let Some(home) = path.parent() {
709        count_result(home, o);
710    }
711    Ok(())
712}
713
714/// `o` in the usage statistics of the store `home`: one event of its result kind with its lessons and
715/// channel. `asked` is already counted as the Stop's block, a `vetoed` result as the `veto` that
716/// credited it (veto.rs); a placebo's result is no result (`is_result`): its "changed" never joins the
717/// deliveries' counts. The judge (hook.rs) writes one record per routing check but counts the lessons
718/// of a call's channel as one event, as before checks had ids.
719pub fn count_result(home: &Path, o: &Outcome) {
720    if !is_result(o) {
721        return;
722    }
723    let kind = match o.kind.as_str() {
724        CHANGED => crate::stats::CHANGED,
725        IGNORED => crate::stats::IGNORED,
726        CORRECTED => crate::stats::CORRECTED,
727        NOT_CORRECTED => crate::stats::NOT_CORRECTED,
728        REGRETTED => crate::stats::REGRETTED,
729        TESTED => crate::stats::TESTED,
730        // Measurements, never results (`is_result` already turned them away).
731        UNCLEAR | REMAINS | NOT_ARISEN => return,
732        _ => return,
733    };
734    crate::stats::count(home, kind, &o.session, |e| {
735        e.repo = o.repo.clone();
736        e.lessons = o.lessons.clone();
737        e.channel = o.channel.clone();
738    });
739}
740
741/// Did the conscience ask `lesson` in `session` before `ms`?
742pub fn asked_before(outcomes: &[Outcome], session: &str, lesson: &str, ms: i64) -> bool {
743    outcomes.iter().any(|o| o.kind == ASKED && o.session == session && o.ms < ms && o.lessons.iter().any(|l| l == lesson))
744}
745
746/// Is a result (`kind`) already recorded for `lesson` in `session`? Keeps `borg learn` idempotent.
747pub fn has(outcomes: &[Outcome], kind: &str, session: &str, lesson: &str) -> bool {
748    outcomes.iter().any(|o| o.kind == kind && o.session == session && o.lessons.iter().any(|l| l == lesson))
749}
750
751/// The lessons a correction at `ms` in `session` shows were asked in vain, each asked in `session`
752/// before `ms` and not yet recorded as corrected or vetoed there (a veto is the stronger result): the lessons the correction `supersedes`
753/// (it contradicts them), and `target`, the lesson it was merged into (the same concern came up
754/// again). When `target` was asked as one side of a rendered disagreement, the engineer sided with
755/// it: the other sides of that disagreement were corrected, not `target`. Sorted, unique.
756pub fn contradicted(outcomes: &[Outcome], session: &str, ms: i64, target: Option<&str>, supersedes: &[String]) -> Vec<String> {
757    let mut out: Vec<String> = supersedes.to_vec();
758    if let Some(t) = target {
759        let sides: Vec<String> = outcomes
760            .iter()
761            .filter(|o| o.kind == ASKED && o.session == session && o.ms < ms)
762            .flat_map(|o| &o.groups)
763            .filter(|g| g.iter().any(|x| x == t))
764            .flatten()
765            .filter(|x| *x != t)
766            .cloned()
767            .collect();
768        match sides.is_empty() {
769            true => out.push(t.to_string()),
770            false => out.extend(sides),
771        }
772    }
773    out.retain(|l| asked_before(outcomes, session, l, ms) && !has(outcomes, CORRECTED, session, l) && !has(outcomes, VETOED, session, l));
774    out.sort();
775    out.dedup();
776    out
777}
778
779/// Was `o` a free delivery (channel `early` or `queued`): lessons handed over as context, no question?
780pub fn free(o: &Outcome) -> bool {
781    o.channel == "early" || o.channel == "queued"
782}
783
784/// The lessons a correction at `ms` in `session` shows were needed and not asked: of the lessons it
785/// `supersedes` and `target` (the lesson it was merged into), those a graded check of the session found
786/// applying before `ms` without choosing them, never asked as a question in the session before `ms` (a
787/// free delivery asks nothing: a lesson only handed over as context stays a miss for the cut,
788/// attention.rs), and not yet recorded as missed there. Sorted, unique.
789pub fn missed(outcomes: &[Outcome], session: &str, ms: i64, target: Option<&str>, supersedes: &[String]) -> Vec<String> {
790    let mut out: Vec<String> = supersedes.iter().cloned().chain(target.map(str::to_string)).collect();
791    let applied_unchosen = |l: &str| {
792        outcomes.iter().any(|o| o.kind == GRADED && o.session == session && o.ms < ms && o.lessons.iter().any(|x| x == l) && !o.chosen.iter().any(|x| x == l))
793    };
794    let questioned = |l: &str| outcomes.iter().any(|o| o.kind == ASKED && !free(o) && o.session == session && o.ms < ms && o.lessons.iter().any(|x| x == l));
795    out.retain(|l| applied_unchosen(l) && !questioned(l) && !has(outcomes, MISSED, session, l));
796    out.sort();
797    out.dedup();
798    out
799}
800
801/// Has `lesson` been credited for the regret `cause` already (in any session)?
802fn credited(outcomes: &[Outcome], cause: &str, lesson: &str) -> bool {
803    outcomes.iter().any(|o| o.kind == REGRETTED && o.cause == cause && o.lessons.iter().any(|l| l == lesson))
804}
805
806/// The lessons a regret blames: those asked in `session` (the deciding one) before `before_ms`, without
807/// a correction or a veto there already (both outrank regretted, as in memory.rs) and not yet credited
808/// for `cause`. When some of `target` (the lesson the regret was folded into, and the lessons that lesson
809/// supersedes) were asked, they share the blame alone: the same concern came up again, and when all of
810/// them already took a correction or a veto for it, nobody else is blamed. Otherwise every asked lesson
811/// shares it equally (the Shapley value of a symmetric game). A lesson a graded check found applying but
812/// did not ask was never shown, so it is not blamed. One record per lesson, sorted, at `ms`,
813/// with `credit = strength / n`; n counts the blamed lessons before the already-credited ones are left
814/// out, so a re-run writes nothing and the shares never change. Every record's session has an earlier
815/// `asked` record, so it never moves memory.rs's `Clock`.
816#[allow(clippy::too_many_arguments)]
817pub fn regretted(outcomes: &[Outcome], session: &str, before_ms: i64, cause: &str, target: &[String], strength: f64, ms: i64, repo: &str) -> Vec<Outcome> {
818    if session.is_empty() || before_ms <= 0 || strength <= 0.0 {
819        return Vec::new();
820    }
821    let mut asked: Vec<&str> =
822        outcomes.iter().filter(|o| o.kind == ASKED && o.session == session && o.ms < before_ms).flat_map(|o| o.lessons.iter().map(String::as_str)).collect();
823    asked.sort_unstable();
824    asked.dedup();
825    if asked.iter().any(|l| target.iter().any(|t| t == l)) {
826        asked.retain(|l| target.iter().any(|t| t == l));
827    }
828    asked.retain(|l| !has(outcomes, CORRECTED, session, l) && !has(outcomes, VETOED, session, l));
829    let credit = (strength / asked.len().max(1) as f64).min(1.0);
830    asked
831        .into_iter()
832        .filter(|l| !credited(outcomes, cause, l))
833        .map(|l| Outcome {
834            kind: REGRETTED.into(),
835            session: session.into(),
836            lessons: vec![l.into()],
837            ms,
838            repo: repo.into(),
839            cause: cause.into(),
840            credit,
841            ..Default::default()
842        })
843        .collect()
844}
845
846/// The `tested` records a session's own test runs earn (`tests`: its `<state>/<session>.tests`, `fail <ms>`
847/// and `pass <ms>` lines, hook.rs `capture_test`): each lesson asked as a question in `session` (a free
848/// delivery asks nothing, `free`: handed over at every prompt of its scope, it would gain from every
849/// test-first session) whose last test result after its first ask passed, after a failed run since that ask (red, then green) or a change the drone
850/// made on the lesson's point (`asked_then_changed`), and that has no `tested` record there yet, nor a
851/// correction or a veto (the engineer's word outranks a green run), nor `asked_then_ignored` (red, then
852/// green is also how a feature is built: it does not make an ignored question useful), nor
853/// `asked_not_arisen` on a question of it since its first ask without a change (the lesson's point never came up: a green run says nothing of
854/// it, and `tested` would move a belief `asked_not_arisen` is censored for). A pass before the ask says nothing
855/// of the lesson. One record per lesson, sorted, at that last pass. Every record's session has an
856/// earlier `asked` record, so it never moves memory.rs's `Clock`.
857pub fn tested(outcomes: &[Outcome], session: &str, tests: &str) -> Vec<Outcome> {
858    let mut runs: Vec<(i64, bool)> = tests
859        .lines()
860        .filter_map(|l| l.split_once(' '))
861        .filter_map(|(w, m)| Some((m.trim().parse::<i64>().ok()?, matches!(w, "pass" | "fail").then_some(w == "pass")?)))
862        .collect();
863    runs.sort_unstable();
864    // Each lesson's first ask in the session, and its repo.
865    let mut first: HashMap<&str, (i64, &str)> = HashMap::new();
866    for o in outcomes.iter().filter(|o| o.kind == ASKED && !free(o) && o.session == session) {
867        for l in &o.lessons {
868            let e = first.entry(l.as_str()).or_insert((o.ms, o.repo.as_str()));
869            if o.ms < e.0 {
870                *e = (o.ms, o.repo.as_str());
871            }
872        }
873    }
874    // A verdict that the question's point never came up, on a question of the lesson (not a placebo's
875    // or a free delivery's, none before its first ask): only that says the green run is not about it.
876    let not_arisen_on_ask = |l: &str, at: i64| {
877        outcomes
878            .iter()
879            .any(|o| o.kind == NOT_ARISEN && o.session == session && o.channel != PLACEBO && !free(o) && o.ms >= at && o.lessons.iter().any(|x| x == l))
880    };
881    let mut out: Vec<Outcome> = first
882        .into_iter()
883        .filter(|(l, _)| ![TESTED, CORRECTED, VETOED, IGNORED].iter().any(|k| has(outcomes, k, session, l)))
884        .filter(|&(l, (at, _))| !not_arisen_on_ask(l, at) || has(outcomes, CHANGED, session, l))
885        .filter_map(|(l, (at, repo))| {
886            let after = &runs[runs.partition_point(|r| r.0 <= at)..];
887            let &(ms, pass) = after.last()?;
888            (pass && (after.iter().any(|r| !r.1) || has(outcomes, CHANGED, session, l))).then(|| Outcome {
889                kind: TESTED.into(),
890                session: session.into(),
891                lessons: vec![l.into()],
892                ms,
893                repo: repo.into(),
894                ..Default::default()
895            })
896        })
897        .collect();
898    out.sort_by(|a, b| a.lessons.cmp(&b.lessons));
899    out
900}
901
902/// At session end: every lesson asked in `session` that has no result yet was not corrected, and every
903/// placebo of it without a verdict is closed. A vetoed lesson already has its result. `settle_with`,
904/// every unjudged lesson's reason `no_call`.
905pub fn settle(outcomes: &[Outcome], session: &str, ms: i64) -> Vec<Outcome> {
906    settle_with(outcomes, session, ms, &|_| UNJUDGED_NO_CALL)
907}
908
909/// `settle`, each record with its `reason`: `judged` when the judge gave the lesson's latest ask in the
910/// session a verdict that settles it (`settles`: `asked_then_changed`, `asked_ignored`,
911/// `asked_not_arisen`), else `unjudged(lesson)` (one of the
912/// `UNJUDGED_*`, from the session's state file, hook.rs `unjudged`); and its `check`, the check behind
913/// that latest `asked` record. A verdict on an earlier delivery says nothing of a later question: a
914/// stop that judges a lesson handed over free and then asks it writes the verdict first, and no judge
915/// call need follow the answer. Nor does a verdict on a free delivery (`free`) say anything of a
916/// question (or one on a question of a free delivery), whenever it came: an older binary's live check
917/// judged the earlier free delivery of a lesson asked since and not yet answered (hook.rs `pending`),
918/// and its question, never judged, then settles censored instead of staying open in the selection
919/// summary (select/summary.rs `settled`).
920/// Then every placebo of the session (a `delivery` routed `placebo`, which writes no `asked`) that no
921/// verdict and no earlier settle closed (`open_placebos`): `asked_not_corrected` on channel `placebo`
922/// (no result, `is_result`; it ends no ask's wait, `resolves`) with the placebo's check and repo, and
923/// the reason `unjudged(lesson)` when it is the lesson's latest delivery in the session, else
924/// `UNJUDGED_LATER`. So the selection summary censors an unjudged placebo as it does an unjudged ask
925/// (select/summary.rs `settled`), and the judge-missingness fit sees both.
926/// Not a result: memory.rs reads `asked_not_corrected` as censored, so a verdict recorded after it (a
927/// resumed session) counts once, alone.
928/// The asks first, sorted by lesson id, then the placebos by lesson id and check, so the appended lines
929/// are deterministic. A few passes over the session's records, whatever the number of asks.
930pub fn settle_with(outcomes: &[Outcome], session: &str, ms: i64, unjudged: &dyn Fn(&str) -> &'static str) -> Vec<Outcome> {
931    let mine: Vec<&Outcome> = outcomes.iter().filter(|o| o.session == session).collect();
932    let resolved: std::collections::HashSet<&str> = mine.iter().filter(|o| resolves(o)).flat_map(|o| o.lessons.iter().map(String::as_str)).collect();
933    // Per lesson: its verdicts' (ms, check, on a free delivery).
934    let mut verdicts: HashMap<&str, Vec<(i64, &str, bool)>> = HashMap::new();
935    for o in mine.iter().filter(|o| settles(&o.kind) && o.channel != PLACEBO) {
936        for l in &o.lessons {
937            verdicts.entry(l.as_str()).or_default().push((o.ms, o.check.as_str(), free(o)));
938        }
939    }
940    // Per lesson: the first of its asks' repos in sort order (as before checks were kept), and the
941    // ms, check and whether free of its latest ask.
942    let mut asked: std::collections::BTreeMap<&str, (&str, i64, &str, bool)> = std::collections::BTreeMap::new();
943    // Per lesson: the ms of its latest delivery, an `asked` for every one the drone sees and a
944    // placebo's `delivery`.
945    let mut latest: HashMap<&str, i64> = HashMap::new();
946    for o in mine.iter().filter(|o| o.kind == ASKED || is_placebo(o)) {
947        for l in o.lessons.iter().map(String::as_str) {
948            let t = latest.entry(l).or_insert(o.ms);
949            *t = (*t).max(o.ms);
950            if o.kind != ASKED || resolved.contains(l) {
951                continue;
952            }
953            let e = asked.entry(l).or_insert((o.repo.as_str(), o.ms, o.check.as_str(), free(o)));
954            e.0 = e.0.min(o.repo.as_str());
955            if o.ms >= e.1 {
956                (e.1, e.2, e.3) = (o.ms, o.check.as_str(), free(o));
957            }
958        }
959    }
960    // A verdict on the latest ask is on the same kind of delivery (a question, or free) and came after it
961    // (the judge sees a delivery in a later call), or names its check. Time first: an older binary's stop
962    // wrote one `asked` naming the stop's check also for a lesson another check routed (hook.rs
963    // `#borg-routed`), whose verdict names that check; a stop now writes one `asked` per routing check
964    // (hook.rs `stop_ask`).
965    let judged = |l: &str, at: i64, check: &str, as_free: bool| {
966        verdicts.get(l).is_some_and(|v| v.iter().any(|&(t, c, f)| f == as_free && (t > at || (!check.is_empty() && c == check))))
967    };
968    let mut out: Vec<Outcome> = asked
969        .into_iter()
970        .map(|(l, (repo, at, check, as_free))| Outcome {
971            kind: NOT_CORRECTED.into(),
972            session: session.into(),
973            lessons: vec![l.into()],
974            ms,
975            repo: repo.into(),
976            check: check.into(),
977            reason: if judged(l, at, check, as_free) { UNJUDGED_NONE } else { unjudged(l) }.into(),
978            // The binary that settled: from 0.7.3 on, the selection summary closes every delivery of the
979            // lesson the session left without a verdict (select/summary.rs `settled`).
980            version: env!("CARGO_PKG_VERSION").into(),
981            ..Default::default()
982        })
983        .collect();
984    let mut placebos: Vec<Outcome> = open_placebos(&mine)
985        .into_iter()
986        .map(|(l, d)| Outcome {
987            kind: NOT_CORRECTED.into(),
988            session: session.into(),
989            lessons: vec![l.into()],
990            ms,
991            repo: d.repo.clone(),
992            channel: PLACEBO.into(),
993            check: d.check.clone(),
994            // Delivered again later, the lesson's later delivery is the one the judge saw.
995            reason: if latest.get(l).is_some_and(|&t| t > d.ms) { UNJUDGED_LATER } else { unjudged(l) }.into(),
996            ..Default::default()
997        })
998        .collect();
999    placebos.sort_by(|a, b| (&a.lessons, &a.check).cmp(&(&b.lessons, &b.check)));
1000    out.extend(placebos);
1001    out
1002}
1003
1004/// Does `o` end an ask's wait for its result (`settle`)? A placebo's settle record ends none: a
1005/// placebo is never asked, and the lesson may be asked later in the session.
1006fn resolves(o: &Outcome) -> bool {
1007    matches!(o.kind.as_str(), CORRECTED | NOT_CORRECTED | VETOED) && o.channel != PLACEBO
1008}
1009
1010/// A placebo's delivery (`delivery` routed `placebo`, hook.rs `queued`): judged blindly, never shown,
1011/// so it writes no `asked`.
1012fn is_placebo(o: &Outcome) -> bool {
1013    o.kind == DELIVERY && o.route == ROUTE_PLACEBO
1014}
1015
1016/// Does `r`, a placebo channel's verdict that settles (`settles`: `asked_then_changed`, `asked_ignored`,
1017/// `asked_not_arisen`) or settle record (`asked_not_corrected`), close placebo delivery `d` of its
1018/// lesson? A settle record names the placebo's own check, so it closes exactly that one, and settling
1019/// again writes nothing. A verdict names the check it judged (a check routes a lesson once), or, a
1020/// record from before check ids, came after the placebo. An unclear verdict or a remaining consequence
1021/// closes nothing, as it leaves an ask pending.
1022fn closes(r: &Outcome, d: &Outcome) -> bool {
1023    match r.kind.as_str() {
1024        NOT_CORRECTED => r.check == d.check,
1025        k if settles(k) && (r.check.is_empty() || d.check.is_empty()) => r.ms > d.ms,
1026        k if settles(k) => r.check == d.check,
1027        _ => false,
1028    }
1029}
1030
1031/// The open placebos among `mine` (one session's records), in log order: per placebo delivery
1032/// (`is_placebo`) and lesson, none of the session's placebo records `closes` it.
1033fn open_placebos<'a>(mine: &[&'a Outcome]) -> Vec<(&'a str, &'a Outcome)> {
1034    let mut closers: HashMap<&str, Vec<&Outcome>> = HashMap::new();
1035    for &o in mine.iter().filter(|o| o.channel == PLACEBO && !is_placebo(o)) {
1036        for l in &o.lessons {
1037            closers.entry(l.as_str()).or_default().push(o);
1038        }
1039    }
1040    mine.iter()
1041        .copied()
1042        .filter(|o| is_placebo(o))
1043        .flat_map(|d| d.lessons.iter().map(move |l| (l.as_str(), d)))
1044        .filter(|&(l, d)| !closers.get(l).is_some_and(|rs| rs.iter().any(|r| closes(r, d))))
1045        .collect()
1046}
1047
1048/// Sessions with asks or placebos that are idle at `now`: their newest ask or placebo and newest
1049/// episode (`last_episode`, newest episode ms per session) are at least `IDLE_MS` old. Sorted. Only
1050/// sessions with an ask still without its result or an open placebo (`open_placebos`), so `borg learn`
1051/// (under the store lock) settles what is new, not every session it ever settled: one pass over the
1052/// log.
1053pub fn idle_sessions<'a>(outcomes: &'a [Outcome], last_episode: &HashMap<String, i64>, now: i64) -> Vec<&'a str> {
1054    let mut newest: HashMap<&str, i64> = HashMap::new();
1055    let (mut asked, mut resolved) = (std::collections::HashSet::new(), std::collections::HashSet::new());
1056    // Per session, its placebo channel's records: deliveries, verdicts and settles.
1057    let mut placebos: HashMap<&str, Vec<&Outcome>> = HashMap::new();
1058    for o in outcomes {
1059        if o.channel == PLACEBO || is_placebo(o) {
1060            placebos.entry(o.session.as_str()).or_default().push(o);
1061        }
1062        if o.kind == ASKED || is_placebo(o) {
1063            let m = newest.entry(o.session.as_str()).or_insert(o.ms);
1064            *m = (*m).max(o.ms);
1065        }
1066        let into = match o.kind.as_str() {
1067            ASKED => &mut asked,
1068            _ if resolves(o) => &mut resolved,
1069            _ => continue,
1070        };
1071        into.extend(o.lessons.iter().map(|l| (o.session.as_str(), l.as_str())));
1072    }
1073    let mut open: std::collections::HashSet<&str> = asked.difference(&resolved).map(|(s, _)| *s).collect();
1074    open.extend(placebos.iter().filter(|(_, rs)| !open_placebos(rs).is_empty()).map(|(s, _)| *s));
1075    let mut idle: Vec<&str> = newest
1076        .into_iter()
1077        .filter(|&(s, ms)| open.contains(s) && ms.max(last_episode.get(s).copied().unwrap_or(i64::MIN)) <= now - IDLE_MS)
1078        .map(|(s, _)| s)
1079        .collect();
1080    idle.sort();
1081    idle
1082}
1083
1084/// Usefulness of a lesson from its asked outcomes:
1085///
1086/// w = (1 + not_corrected) / (1 + not_corrected + 2 * corrected)
1087///
1088/// The +1 is a neutral prior, so a lesson without outcomes keeps w = 1 and a single bad session
1089/// cannot zero it. A correction of the same concern right after asking is strong evidence the
1090/// question did not help (too generic, or it does not change what the drone does), while a
1091/// session without correction is weak evidence (the engineer may simply not have looked), so a
1092/// correction counts twice. w stays in (0, 1]: outcomes only demote, BM25 relevance still decides
1093/// what is on topic. One corrected session gives 1/3; one corrected and one not gives 1/2.
1094pub fn weight(not_corrected: u32, corrected: u32) -> f64 {
1095    let (n, c) = (not_corrected as f64, corrected as f64);
1096    (1.0 + n) / (1.0 + n + f64::from(CORRECTED_W) * c)
1097}
1098
1099/// The weight of every lesson that has outcomes. Each (session, lesson) counts once; corrected wins.
1100pub fn weights(outcomes: &[Outcome]) -> HashMap<String, f64> {
1101    counts(outcomes).into_iter().map(|(l, (n, c))| (l, weight(n, c))).collect()
1102}
1103
1104/// Per lesson with results: (sessions not corrected, sessions corrected). Each (session, lesson)
1105/// counts once; corrected wins. Used by `weights`.
1106pub fn counts(outcomes: &[Outcome]) -> HashMap<String, (u32, u32)> {
1107    sessions(outcomes).into_iter().map(|(l, ss)| (l.to_string(), tally(ss.values(), i64::MIN))).collect()
1108}
1109
1110/// Per lesson, per session with a result: (corrected, ms of the session's earliest result for the
1111/// lesson). Corrected wins over a later (resumed) settle. trust.rs filters these by when an engineer
1112/// joined the lesson. A veto (`vetoed`) counts as a correction here, so trust and `weight` see it too
1113/// (as heavy as a correction; only memory.rs weighs it above one).
1114pub fn sessions(outcomes: &[Outcome]) -> HashMap<&str, HashMap<&str, (bool, i64)>> {
1115    let mut out: HashMap<&str, HashMap<&str, (bool, i64)>> = HashMap::new();
1116    // A placebo's record is no result (`is_result`).
1117    for o in outcomes.iter().filter(|o| is_result(o)) {
1118        let corrected = match o.kind.as_str() {
1119            CORRECTED | VETOED => true,
1120            NOT_CORRECTED => false,
1121            _ => continue,
1122        };
1123        for l in &o.lessons {
1124            let r = out.entry(l.as_str()).or_default().entry(o.session.as_str()).or_insert((corrected, o.ms));
1125            r.0 |= corrected;
1126            r.1 = r.1.min(o.ms);
1127        }
1128    }
1129    out
1130}
1131
1132/// (sessions not corrected, sessions corrected) among `sessions` results whose earliest result is
1133/// after `since`.
1134pub fn tally<'a>(sessions: impl IntoIterator<Item = &'a (bool, i64)>, since: i64) -> (u32, u32) {
1135    sessions.into_iter().filter(|(_, ms)| *ms > since).fold((0, 0), |(n, c), (corrected, _)| match corrected {
1136        true => (n, c + 1),
1137        false => (n + 1, c),
1138    })
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143    use super::*;
1144
1145    fn o(kind: &str, session: &str, lessons: &[&str], ms: i64) -> Outcome {
1146        Outcome {
1147            kind: kind.into(),
1148            session: session.into(),
1149            lessons: lessons.iter().map(|l| l.to_string()).collect(),
1150            ms,
1151            repo: "r".into(),
1152            ..Default::default()
1153        }
1154    }
1155
1156    #[test]
1157    fn missed_is_an_applied_unasked_lesson_a_later_correction_lands_on() {
1158        let graded = |ms: i64, chosen: &[&str]| Outcome {
1159            kind: GRADED.into(),
1160            session: "s".into(),
1161            lessons: vec!["A".into(), "B".into()],
1162            ms,
1163            chosen: chosen.iter().map(|x| x.to_string()).collect(),
1164            ..Default::default()
1165        };
1166        let none: Vec<String> = Vec::new();
1167        let log = vec![graded(10, &["B"])];
1168        assert_eq!(missed(&log, "s", 20, Some("A"), &none), ["A"]);
1169        assert_eq!(missed(&log, "s", 20, None, &["A".into(), "B".into()]), ["A"], "B was chosen");
1170        assert!(missed(&log, "s", 5, Some("A"), &none).is_empty(), "a correction before the check");
1171        assert!(missed(&log, "t", 20, Some("A"), &none).is_empty(), "another session");
1172        assert!(missed(&log, "s", 20, Some("C"), &none).is_empty(), "never applied");
1173        let mut asked = log.clone();
1174        asked.push(o(ASKED, "s", &["A"], 15));
1175        assert!(missed(&asked, "s", 20, Some("A"), &none).is_empty(), "asked later in the session: not a miss");
1176        let mut free = log.clone();
1177        free.push(Outcome { channel: "queued".into(), ..o(ASKED, "s", &["A"], 15) });
1178        free.push(Outcome { channel: "early".into(), ..o(ASKED, "s", &["A"], 16) });
1179        assert_eq!(missed(&free, "s", 20, Some("A"), &none), ["A"], "handed over free, never asked: still a miss");
1180        let mut done = log.clone();
1181        done.push(o(MISSED, "s", &["A"], 18));
1182        assert!(missed(&done, "s", 20, Some("A"), &none).is_empty(), "recorded once");
1183    }
1184
1185    #[test]
1186    fn weight_formula() {
1187        assert_eq!(weight(0, 0), 1.0);
1188        assert_eq!(weight(5, 0), 1.0);
1189        assert!((weight(0, 1) - 1.0 / 3.0).abs() < 1e-12);
1190        assert_eq!(weight(1, 1), 0.5);
1191        assert!(weight(0, 3) < weight(0, 1));
1192    }
1193
1194    #[test]
1195    fn weights_count_each_session_once_and_corrected_wins() {
1196        let all = vec![
1197            o(ASKED, "s1", &["A", "B"], 10),
1198            o(CORRECTED, "s1", &["A"], 20),
1199            o(CORRECTED, "s1", &["A"], 30),     // second correction in the same session: still one
1200            o(NOT_CORRECTED, "s1", &["A"], 40), // resumed session settled later: corrected wins
1201            o(NOT_CORRECTED, "s1", &["B"], 40),
1202            o(NOT_CORRECTED, "s2", &["A"], 50),
1203        ];
1204        let w = weights(&all);
1205        assert_eq!(w["A"], weight(1, 1));
1206        assert_eq!(w["B"], 1.0);
1207        assert!(!w.contains_key("C"));
1208    }
1209
1210    #[test]
1211    fn a_session_whose_tests_go_green_after_an_ask_credits_it_once() {
1212        let mut log = vec![o(ASKED, "s", &["A", "B"], 10), o(ASKED, "t", &["A"], 10)];
1213        // Red after the ask, then green: one credit per lesson asked, dated at the pass.
1214        let got = tested(&log, "s", "fail 20\npass 30\n");
1215        assert_eq!(got.iter().map(|x| (x.kind.as_str(), x.lessons[0].as_str(), x.ms)).collect::<Vec<_>>(), [(TESTED, "A", 30), (TESTED, "B", 30)]);
1216        // Idempotent: a re-run with the records written writes nothing.
1217        log.extend(got);
1218        assert!(tested(&log, "s", "fail 20\npass 30\n").is_empty());
1219        // Only the session's own asks: t ran no tests.
1220        assert!(tested(&log, "t", "").is_empty(), "no tests file: nothing");
1221    }
1222
1223    #[test]
1224    fn a_green_run_credits_only_after_the_ask_and_with_a_reason() {
1225        let log = vec![o(ASKED, "s", &["A"], 50)];
1226        assert!(tested(&log, "s", "fail 20\npass 30\n").is_empty(), "red and green before the ask");
1227        assert!(tested(&log, "s", "fail 20\npass 60\n").is_empty(), "the failure before the ask: green proves nothing new");
1228        assert!(tested(&log, "s", "fail 60\npass 70\nfail 80\n").is_empty(), "last run red");
1229        assert!(tested(&log, "s", "pass 60\n").is_empty(), "green alone, nothing changed");
1230        assert!(tested(&log, "s", "pass 60\npass 70 \ngarbage\n").is_empty());
1231        let early = [Outcome { channel: "early".into(), ..o(ASKED, "e", &["A"], 10) }];
1232        assert!(tested(&early, "e", "fail 20\npass 30\n").is_empty(), "a free delivery asked nothing");
1233        // Green after the drone changed its work on the lesson: a credit.
1234        let changed = [log.clone(), vec![o(CHANGED, "s", &["A"], 55)]].concat();
1235        assert_eq!(tested(&changed, "s", "pass 60\n").len(), 1);
1236        // A correction or a veto of the lesson in the session outranks a green run; an ignored question
1237        // gains nothing from the drone fixing its own failing test.
1238        for k in [CORRECTED, VETOED, IGNORED] {
1239            let worse = [log.clone(), vec![o(k, "s", &["A"], 55)]].concat();
1240            assert!(tested(&worse, "s", "fail 60\npass 70\n").is_empty(), "{k}");
1241        }
1242        // Lines out of order still find the last run; the first ask decides what is after it.
1243        let twice = [log.clone(), vec![o(ASKED, "s", &["A"], 65)]].concat();
1244        assert_eq!(tested(&twice, "s", "pass 70\nfail 60\n")[0].ms, 70);
1245    }
1246
1247    #[test]
1248    fn settle_marks_only_unresolved_asks_of_this_session() {
1249        let all = vec![o(ASKED, "s1", &["B", "A"], 10), o(ASKED, "s1", &["A", "C"], 15), o(CORRECTED, "s1", &["A"], 20), o(ASKED, "s2", &["D"], 10)];
1250        let settled = settle(&all, "s1", 99);
1251        assert_eq!(settled, vec![unjudged("s1", "B", UNJUDGED_NO_CALL), unjudged("s1", "C", UNJUDGED_NO_CALL)]);
1252        assert!(asked_before(&all, "s1", "A", 11) && !asked_before(&all, "s1", "C", 15) && !asked_before(&all, "s2", "A", 99));
1253    }
1254
1255    /// An ask's settle record, as this binary writes it (`settle_with`: with its version).
1256    fn unjudged(session: &str, lesson: &str, reason: &str) -> Outcome {
1257        Outcome { reason: reason.into(), version: env!("CARGO_PKG_VERSION").into(), ..o(NOT_CORRECTED, session, &[lesson], 99) }
1258    }
1259
1260    #[test]
1261    fn a_settled_lesson_says_why_it_had_no_verdict_and_names_its_latest_check() {
1262        let ask = |lessons: &[&str], ms: i64, check: &str| Outcome { check: check.into(), ..o(ASKED, "s", lessons, ms) };
1263        let placebo = Outcome { channel: PLACEBO.into(), ..o(CHANGED, "s", &["C"], 30) };
1264        let all = vec![ask(&["A", "B", "C"], 10, "c1"), ask(&["B"], 20, "c2"), o(IGNORED, "s", &["A"], 25), placebo];
1265        let why = |l: &str| if l == "B" { UNJUDGED_TRIES } else { UNJUDGED_SLOTS };
1266        let got = settle_with(&all, "s", 99, &why);
1267        let want = |l: &str, reason: &str, check: &str| Outcome { check: check.into(), ..unjudged("s", l, reason) };
1268        assert_eq!(got, vec![want("A", UNJUDGED_NONE, "c1"), want("B", UNJUDGED_TRIES, "c2"), want("C", UNJUDGED_SLOTS, "c1")], "a placebo's verdict is none");
1269    }
1270
1271    /// A verdict on an earlier delivery of the lesson is none for its later question: handed over free,
1272    /// judged ignored by a stop that then asks it, and the session ends after the answer, so no judge
1273    /// saw the question. A verdict after the question, or on its check, is its own.
1274    #[test]
1275    fn a_verdict_on_an_earlier_delivery_leaves_the_later_question_unjudged() {
1276        let ask = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(ASKED, "s", &["L"], ms) };
1277        let verdict = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(IGNORED, "s", &["L"], ms) };
1278        let why = |log: &[Outcome]| settle_with(log, "s", 99, &|_| UNJUDGED_NO_CALL).into_iter().map(|x| (x.reason, x.check)).collect::<Vec<_>>();
1279        let said = |reason: &str, check: &str| vec![(reason.to_string(), check.to_string())];
1280        // The stop writes its verdict on the free delivery, then the question, in the same millisecond.
1281        let free_then_asked = vec![ask("queued", 10, "cF"), verdict("queued", 20, "cF"), ask("stop", 20, "cS")];
1282        assert_eq!(why(&free_then_asked), said(UNJUDGED_NO_CALL, "cS"));
1283        let answered = [free_then_asked, vec![verdict("stop", 30, "cS")]].concat();
1284        assert_eq!(why(&answered), said(UNJUDGED_NONE, "cS"));
1285        // A lesson another check routed, asked at the stop: its verdict names the routing check.
1286        assert_eq!(why(&[ask("stop", 20, "cS"), verdict("stop", 30, "cL")]), said(UNJUDGED_NONE, "cS"));
1287        // On the question's check, though its clock stepped back.
1288        assert_eq!(why(&[ask("stop", 20, "cS"), verdict("stop", 15, "cS")]), said(UNJUDGED_NONE, "cS"));
1289    }
1290
1291    /// An older binary's live check judged a lesson's earlier free delivery after the lesson was asked
1292    /// live and before the answer (hook.rs `pending`); no judge saw the question. The session ends: the
1293    /// free verdict is not the question's, so the question settles censored (an unjudged reason), which
1294    /// the selection summary reads as its label, instead of staying open for good. A free delivery's own
1295    /// verdict still settles it as judged.
1296    #[test]
1297    fn a_free_deliverys_verdict_after_a_later_question_leaves_the_question_unjudged() {
1298        let ask = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(ASKED, "s", &["L"], ms) };
1299        let verdict = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(CHANGED, "s", &["L"], ms) };
1300        let why = |log: &[Outcome]| settle_with(log, "s", 99, &|_| UNJUDGED_TRIES).into_iter().map(|x| (x.reason, x.check)).collect::<Vec<_>>();
1301        let said = |reason: &str, check: &str| vec![(reason.to_string(), check.to_string())];
1302        let stuck = vec![ask("queued", 10, "cA"), ask("live", 20, "cB"), verdict("queued", 30, "cA")];
1303        assert_eq!(why(&stuck), said(UNJUDGED_TRIES, "cB"));
1304        let early = vec![ask("early", 10, "cA"), ask("stop", 20, "cB"), verdict("early", 30, "cA")];
1305        assert_eq!(why(&early), said(UNJUDGED_TRIES, "cB"));
1306        assert_eq!(why(&[stuck.clone(), vec![verdict("live", 40, "cB")]].concat()), said(UNJUDGED_NONE, "cB"), "the question's own verdict");
1307        assert_eq!(why(&[ask("queued", 10, "cA"), verdict("queued", 30, "cA")]), said(UNJUDGED_NONE, "cA"), "a free delivery's own");
1308
1309        // The selection summary labels the stuck question censored once the session settles.
1310        use crate::select::{
1311            Route,
1312            summary::{Label, Summary, fold},
1313        };
1314        let graded = |check: &str, ms: i64, channel: &str| Outcome {
1315            grades: vec![3],
1316            ranks: vec![0],
1317            applied: 1,
1318            channel: channel.into(),
1319            check: check.into(),
1320            ..o(GRADED, "s", &["L"], ms)
1321        };
1322        let mut log = vec![Outcome { free: vec!["L".into()], ..graded("cA", 5, "live") }, Outcome { chosen: vec!["L".into()], ..graded("cB", 15, "live") }];
1323        log.extend(stuck);
1324        log.extend(settle_with(&log, "s", 99, &|_| UNJUDGED_TRIES));
1325        let text: String = log.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1326        let s = fold(&text, Summary::default());
1327        let label = |route: Route| s.applies.iter().find(|a| a.route == route).map(|a| a.label);
1328        assert_eq!(label(Route::Ask), Some(Label::Censored), "{:?}", s.applies);
1329    }
1330
1331    /// The later delivery wins the judge (hook.rs `pending`): handed over free at cA then asked at cB, or
1332    /// asked at cA then handed over free at cB, the lesson is judged on cB alone. Once the session settles
1333    /// (a settle naming its binary), the delivery the judge never got to is censored, never left open,
1334    /// whose reason says "judged".
1335    #[test]
1336    fn a_settle_leaves_no_delivery_of_its_lesson_open() {
1337        use crate::select::{
1338            Route,
1339            summary::{Label, Summary, fold},
1340        };
1341        let graded = |check: &str, ms: i64, ask: bool| Outcome {
1342            grades: vec![2],
1343            ranks: vec![0],
1344            applied: 1,
1345            channel: "live".into(),
1346            check: check.into(),
1347            chosen: if ask { vec!["L".into()] } else { Vec::new() },
1348            free: if ask { Vec::new() } else { vec!["L".into()] },
1349            ..o(GRADED, "s", &["L"], ms)
1350        };
1351        let asked = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(ASKED, "s", &["L"], ms) };
1352        let verdict = |channel: &str, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(CHANGED, "s", &["L"], 40) };
1353        for (first_ask, channels) in [(false, ["queued", "live"]), (true, ["live", "queued"])] {
1354            let mut log = vec![graded("cA", 5, first_ask), asked(channels[0], 10, "cA"), graded("cB", 15, !first_ask), asked(channels[1], 20, "cB")];
1355            log.push(verdict(channels[1], "cB"));
1356            let settled = settle_with(&log, "s", 99, &|_| UNJUDGED_TRIES);
1357            assert_eq!(settled.iter().map(|x| (x.reason.as_str(), x.check.as_str())).collect::<Vec<_>>(), [(UNJUDGED_NONE, "cB")]);
1358            log.extend(settled);
1359            let text: String = log.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1360            let s = fold(&text, Summary::default());
1361            let label = |route: Route| s.applies.iter().find(|a| a.route == route).map(|a| a.label);
1362            let (a, b) = if first_ask { (Route::Ask, Route::Free) } else { (Route::Free, Route::Ask) };
1363            assert_eq!((label(a), label(b)), (Some(Label::Censored), Some(Label::Changed)), "first asked {first_ask}: {:?}", s.applies);
1364        }
1365        // An older binary judged the free delivery while the question waited, and its settle (no
1366        // version) said "judged" for the question: it folds as when its hooks decided on it, the
1367        // question open, so the replay still reproduces those decisions.
1368        let mut log = vec![graded("cA", 5, false), asked("queued", 10, "cA"), graded("cB", 15, true), asked("live", 20, "cB"), verdict("queued", "cA")];
1369        log.push(Outcome { reason: UNJUDGED_NONE.into(), check: "cB".into(), ..o(NOT_CORRECTED, "s", &["L"], 99) });
1370        let text: String = log.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1371        let s = fold(&text, Summary::default());
1372        let labels: Vec<(Route, Label)> = s.applies.iter().map(|a| (a.route, a.label)).collect();
1373        assert_eq!(labels, [(Route::Free, Label::Changed), (Route::Ask, Label::Open)]);
1374    }
1375
1376    fn placebo(lessons: &[&str], check: &str, ms: i64) -> Outcome {
1377        Outcome { channel: PLACEBO.into(), check: check.into(), route: ROUTE_PLACEBO.into(), ..o(DELIVERY, "s", lessons, ms) }
1378    }
1379
1380    /// A placebo writes no `asked`, only its `delivery`: one the judge gave no verdict settles too, on the
1381    /// placebo channel (no result, and no ask's end), with its own check and reason. Delivered again
1382    /// later, the later delivery took its place in the judge's queue.
1383    #[test]
1384    fn an_unjudged_placebo_settles_on_its_own_channel() {
1385        let on = |kind: &str, lesson: &str, check: &str, ms: i64| Outcome { channel: PLACEBO.into(), check: check.into(), ..o(kind, "s", &[lesson], ms) };
1386        let log = vec![
1387            placebo(&["A", "B"], "p1", 10),
1388            on(IGNORED, "A", "p1", 15),
1389            on(UNCLEAR, "B", "p1", 15),
1390            placebo(&["C"], "p2", 20),
1391            Outcome { channel: "queued".into(), check: "c3".into(), ..o(ASKED, "s", &["C"], 30) },
1392            Outcome { route: ROUTE_DROPPED_DONE.into(), ..placebo(&["D"], "p4", 40) },
1393        ];
1394        let why = |l: &str| if l == "B" { UNJUDGED_TRIES } else { UNJUDGED_NO_CALL };
1395        let got = settle_with(&log, "s", 99, &why);
1396        let closed =
1397            |l: &str, check: &str, reason: &str| Outcome { channel: PLACEBO.into(), check: check.into(), version: String::new(), ..unjudged("s", l, reason) };
1398        let asked = Outcome { check: "c3".into(), ..unjudged("s", "C", UNJUDGED_NO_CALL) };
1399        let want = vec![asked, closed("B", "p1", UNJUDGED_TRIES), closed("C", "p2", UNJUDGED_LATER)];
1400        assert_eq!(got, want, "A has its verdict; D never reached the judge's queue");
1401        assert!(got[1..].iter().all(|x| !is_result(x) && share(x, "n1").is_none()), "no result, never shared");
1402        // Settled once: the same records close their placebos, so settling again writes nothing.
1403        let mut resumed = [log, got].concat();
1404        assert!(settle_with(&resumed, "s", 120, &why).is_empty());
1405        // Resumed: B asked, E a new placebo. B's placebo settle ended no ask's wait.
1406        resumed.extend([Outcome { channel: "stop".into(), check: "c5".into(), ..o(ASKED, "s", &["B"], 110) }, placebo(&["E"], "p6", 111)]);
1407        let again: Vec<(String, String, String)> =
1408            settle_with(&resumed, "s", 120, &why).into_iter().map(|x| (x.lessons.join(","), x.channel, x.check)).collect();
1409        assert_eq!(again, [("B".to_string(), String::new(), "c5".to_string()), ("E".to_string(), PLACEBO.to_string(), "p6".to_string())]);
1410    }
1411
1412    /// Judge v3 (0.7.5): `asked_not_arisen` settles its delivery (a question's settle says "judged", a
1413    /// placebo is closed) while staying no result and never shared; `asked_consequence_remains` leaves
1414    /// it pending as `asked_unclear` does. The selection summary labels each apart, an older
1415    /// `asked_unclear` still `Unclear`, and a pending verdict never overwrites a settling one.
1416    #[test]
1417    fn not_arisen_settles_its_delivery_and_a_remaining_consequence_leaves_it_pending() {
1418        use crate::select::{
1419            Route,
1420            summary::{Label, Summary, fold},
1421        };
1422        let ask = |l: &str, check: &str| Outcome { channel: "stop".into(), check: check.into(), ..o(ASKED, "s", &[l], 10) };
1423        let on = |kind: &str, l: &str, check: &str, channel: &str| Outcome {
1424            channel: channel.into(),
1425            check: check.into(),
1426            judge: 3,
1427            reasons: vec!["only the docs changed".into()],
1428            ..o(kind, "s", &[l], 20)
1429        };
1430        let log = vec![
1431            ask("A", "cA"),
1432            on(NOT_ARISEN, "A", "cA", "stop"),
1433            ask("B", "cB"),
1434            on(REMAINS, "B", "cB", "stop"),
1435            placebo(&["P"], "pP", 10),
1436            on(NOT_ARISEN, "P", "pP", PLACEBO),
1437            placebo(&["Q"], "pQ", 10),
1438            on(REMAINS, "Q", "pQ", PLACEBO),
1439        ];
1440        assert!(log.iter().filter(|x| x.kind == NOT_ARISEN || x.kind == REMAINS).all(|x| !is_result(x) && share(x, "n1").is_none()));
1441        assert!(settles(NOT_ARISEN) && settles(CHANGED) && settles(IGNORED) && !settles(REMAINS) && !settles(UNCLEAR));
1442        let got: Vec<(String, String, String)> =
1443            settle_with(&log, "s", 99, &|_| UNJUDGED_TRIES).into_iter().map(|x| (x.lessons.join(","), x.channel, x.reason)).collect();
1444        let row = |l: &str, channel: &str, reason: &str| (l.to_string(), channel.to_string(), reason.to_string());
1445        assert_eq!(got, [row("A", "", UNJUDGED_NONE), row("B", "", UNJUDGED_TRIES), row("Q", PLACEBO, UNJUDGED_TRIES)], "P closed by its verdict");
1446        // The reason travels on the record and reads back; an older line without it reads empty.
1447        let line = serde_json::to_string(&log[1]).unwrap();
1448        assert!(line.contains(r#""reasons":["only the docs changed"]"#), "{line}");
1449        assert_eq!(serde_json::from_str::<Outcome>(&line).unwrap(), log[1]);
1450        let old: Outcome = serde_json::from_str(r#"{"kind":"asked_unclear","session":"s","lessons":["A"],"ms":1,"repo":"r","channel":"stop"}"#).unwrap();
1451        assert!(old.reasons.is_empty() && !is_result(&old) && !settles(&old.kind));
1452
1453        // The summary: each graded apply its own label.
1454        let graded = |l: &str, check: &str, ask: bool, placebo: bool| Outcome {
1455            grades: vec![3],
1456            ranks: vec![0],
1457            applied: 1,
1458            channel: "stop".into(),
1459            check: check.into(),
1460            chosen: if ask { vec![l.into()] } else { Vec::new() },
1461            placebo: if placebo { vec![l.into()] } else { Vec::new() },
1462            psi: if placebo { 0.5 } else { 0.0 },
1463            ..o(GRADED, "s", &[l], 5)
1464        };
1465        let mut all = vec![graded("A", "cA", true, false), graded("B", "cB", true, false), graded("C", "cC", true, false)];
1466        all.push(graded("P", "pP", false, true));
1467        all.extend(log);
1468        all.extend([ask("C", "cC"), on(UNCLEAR, "C", "cC", "stop")]);
1469        // A later pending verdict does not undo a settling one; a later settling one replaces a pending one.
1470        all.extend([on(UNCLEAR, "A", "cA", "stop"), on(CHANGED, "B", "cB", "stop")]);
1471        let text: String = all.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1472        let s = fold(&text, Summary::default());
1473        let label = |l: &str| {
1474            let i = s.lessons.iter().position(|x| x == l).unwrap() as u32;
1475            s.applies.iter().find(|a| a.lesson == i).map(|a| (a.route, a.label, a.judge.is_some()))
1476        };
1477        assert_eq!(label("A"), Some((Route::Ask, Label::NotArisen, true)), "{:?}", s.applies);
1478        assert_eq!(label("B"), Some((Route::Ask, Label::Changed, true)));
1479        assert_eq!(label("C"), Some((Route::Ask, Label::Unclear, false)), "an older kind keeps its label");
1480        assert_eq!(label("P"), Some((Route::Placebo, Label::NotArisen, true)));
1481        // Before the later change, B's remaining consequence is its own pending label.
1482        let first: String = all[..all.len() - 1].iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1483        let s = fold(&first, Summary::default());
1484        let b = s.lessons.iter().position(|x| x == "B").unwrap() as u32;
1485        let a = s.applies.iter().find(|a| a.lesson == b).unwrap();
1486        assert_eq!((a.label, a.judge, a.jv), (Label::Remains, None, 3), "a pending label keeps its judge's version");
1487        assert!(a.label.pending() && !a.label.verdict() && Label::NotArisen.verdict() && !Label::NotArisen.pending());
1488        // The session-end judge is a judge level of its own; a check's verdict keeps the level it had.
1489        let end = [&all[..], &[graded("E", "cE", true, false), ask("E", "cE"), Outcome { at: AT_END.into(), ..on(CHANGED, "E", "cE", "stop") }]].concat();
1490        let text: String = end.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1491        let s = fold(&text, Summary::default());
1492        assert!(s.judges.iter().any(|j| j.starts_with("v3|")) && s.judges.iter().any(|j| j.starts_with("v3@end|")), "{:?}", s.judges);
1493    }
1494
1495    /// An open placebo keeps its session waiting to settle when its `end` hook never ran, as an open ask
1496    /// does; its settle closes it.
1497    #[test]
1498    fn idle_sessions_wait_for_open_placebos() {
1499        let only = vec![placebo(&["A"], "p1", 0)];
1500        assert_eq!(idle_sessions(&only, &HashMap::new(), IDLE_MS + 10), ["s"]);
1501        assert!(idle_sessions(&only, &HashMap::new(), IDLE_MS - 10).is_empty(), "the placebo is the session's newest activity");
1502        let settled = [only.clone(), settle(&only, "s", 5)].concat();
1503        assert!(idle_sessions(&settled, &HashMap::new(), IDLE_MS + 10).is_empty());
1504    }
1505
1506    /// The selection summary reads a placebo's settle as its censoring (select/summary.rs `settled`), so
1507    /// the judge-missingness fit (select/policy.rs `judged`) counts the placebo as not judged instead of
1508    /// leaving it out.
1509    #[test]
1510    fn the_selection_summary_censors_a_settled_placebo() {
1511        use crate::select::summary::{Label, Summary, fold};
1512        let graded = Outcome {
1513            grades: vec![1, 1],
1514            ranks: vec![0, 1],
1515            applied: 2,
1516            channel: "stop".into(),
1517            check: "p1".into(),
1518            policy: "learned".into(),
1519            placebo: vec!["A".into(), "B".into()],
1520            ..o(GRADED, "s", &["A", "B"], 5)
1521        };
1522        let mut log = vec![graded, placebo(&["A", "B"], "p1", 10), Outcome { channel: PLACEBO.into(), check: "p1".into(), ..o(IGNORED, "s", &["A"], 15) }];
1523        log.extend(settle(&log, "s", 99));
1524        let text: String = log.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1525        let s = fold(&text, Summary::default());
1526        let label = |l: &str| s.applies.iter().find(|a| s.lessons[a.lesson as usize] == l).map(|a| a.label);
1527        assert_eq!((label("A"), label("B")), (Some(Label::Ignored), Some(Label::Censored)));
1528    }
1529
1530    #[test]
1531    fn contradicted_marks_superseded_asks_and_the_other_sides_of_a_disagreement() {
1532        let mut ask = o(ASKED, "s1", &["A", "B", "C", "D"], 10);
1533        ask.groups = vec![vec!["A".into(), "B".into()]];
1534        let all = vec![ask, o(ASKED, "s1", &["E"], 30), o(CORRECTED, "s1", &["D"], 15)];
1535        let ids = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1536        // A plain merge into C: C was asked in vain.
1537        assert_eq!(contradicted(&all, "s1", 20, Some("C"), &[]), ["C"]);
1538        // A correction that sides with A in the rendered A/B disagreement: B was wrong, A was right.
1539        assert_eq!(contradicted(&all, "s1", 20, Some("A"), &[]), ["B"]);
1540        // A new lesson superseding C and E: only C was asked before it; D is already corrected.
1541        assert_eq!(contradicted(&all, "s1", 20, None, &ids(&["C", "E", "D", "Z"])), ["C"]);
1542        assert!(contradicted(&all, "s2", 20, Some("C"), &ids(&["A"])).is_empty(), "another session asked nothing");
1543        let mut vetoed = all.clone();
1544        vetoed.push(o(VETOED, "s1", &["C"], 12));
1545        assert!(contradicted(&vetoed, "s1", 20, Some("C"), &[]).is_empty(), "a vetoed lesson already has the stronger result");
1546    }
1547
1548    #[test]
1549    fn a_placebo_or_unclear_result_is_no_result_for_any_reader() {
1550        let placebo = |kind: &str| Outcome { channel: PLACEBO.into(), ..o(kind, "s", &["A"], 5) };
1551        let unclear = Outcome { channel: "stop".into(), ..o(UNCLEAR, "s", &["A"], 5) };
1552        for x in [placebo(CHANGED), placebo(IGNORED), placebo(UNCLEAR), unclear.clone()] {
1553            assert!(!is_result(&x), "{x:?}");
1554            assert!(share(&x, "n1").is_none(), "never shared: {x:?}");
1555        }
1556        assert!(is_result(&Outcome { channel: "queued".into(), ..o(CHANGED, "s", &["A"], 5) }));
1557        assert!(!SHARED_KINDS.contains(&UNCLEAR) && !SHARED_KINDS.contains(&DELIVERY));
1558        // trust's view (`sessions`): a placebo result moves nothing, whatever its kind.
1559        let all = [placebo(CORRECTED), placebo(NOT_CORRECTED), o(NOT_CORRECTED, "t", &["A"], 6)];
1560        assert_eq!(tally(sessions(&all)["A"].values(), i64::MIN), (1, 0));
1561        // The statistics count no placebo result (`append`).
1562        let d = tmp("placebo-stats");
1563        append(&d.join("outcomes.jsonl"), &placebo(CHANGED)).unwrap();
1564        append(&d.join("outcomes.jsonl"), &unclear).unwrap();
1565        append(&d.join("outcomes.jsonl"), &Outcome { channel: "stop".into(), ..o(CHANGED, "s", &["B"], 7) }).unwrap();
1566        let kinds: Vec<String> = crate::stats::events(&d).into_iter().map(|e| e.kind).collect();
1567        assert_eq!(kinds, [crate::stats::CHANGED], "{kinds:?}");
1568        let _ = std::fs::remove_dir_all(d);
1569    }
1570
1571    #[test]
1572    fn a_vetoed_lesson_is_not_settled_and_counts_as_corrected() {
1573        let all = vec![o(ASKED, "s1", &["A", "B"], 10), o(VETOED, "s1", &["A"], 20)];
1574        assert_eq!(settle(&all, "s1", 99), vec![unjudged("s1", "B", UNJUDGED_NO_CALL)]);
1575        assert_eq!(sessions(&all)["A"]["s1"], (true, 20));
1576        assert_eq!(weights(&all)["A"], weight(0, 1));
1577    }
1578
1579    #[test]
1580    fn sessions_keep_the_earliest_result_and_tally_filters_by_it() {
1581        let all =
1582            vec![o(NOT_CORRECTED, "s1", &["A"], 10), o(CORRECTED, "s2", &["A"], 20), o(NOT_CORRECTED, "s2", &["A"], 25), o(NOT_CORRECTED, "s3", &["A"], 30)];
1583        let s = sessions(&all);
1584        assert_eq!(s["A"]["s2"], (true, 20));
1585        assert_eq!(tally(s["A"].values(), i64::MIN), (2, 1));
1586        assert_eq!(tally(s["A"].values(), 20), (1, 0));
1587    }
1588
1589    #[test]
1590    fn idle_sessions_need_old_asks_and_old_episodes() {
1591        let all = vec![o(ASKED, "old", &["A"], 0), o(ASKED, "busy", &["A"], 0), o(ASKED, "fresh", &["A"], 50), o(CORRECTED, "x", &["A"], 0)];
1592        let episodes = HashMap::from([("busy".to_string(), 60)]);
1593        assert_eq!(idle_sessions(&all, &episodes, IDLE_MS + 10), ["old"]);
1594        assert_eq!(idle_sessions(&all, &episodes, IDLE_MS + 60), ["busy", "fresh", "old"]);
1595    }
1596
1597    #[test]
1598    fn idle_sessions_skip_settled_ones() {
1599        let all = vec![
1600            o(ASKED, "done", &["A", "B"], 0),
1601            o(NOT_CORRECTED, "done", &["A"], 1),
1602            o(CORRECTED, "done", &["B"], 1),
1603            o(ASKED, "vetoed", &["A"], 0),
1604            o(VETOED, "vetoed", &["A"], 1),
1605            o(ASKED, "half", &["A", "B"], 0),
1606            o(NOT_CORRECTED, "half", &["A"], 1),
1607        ];
1608        assert_eq!(idle_sessions(&all, &HashMap::new(), IDLE_MS + 10), ["half"], "every ask of the others has its result");
1609    }
1610
1611    #[test]
1612    fn regretted_blames_asks_before_the_decision_shared_or_by_target() {
1613        let mut graded = o(GRADED, "s", &["G"], 5);
1614        graded.chosen = vec![];
1615        let log = vec![graded, o(ASKED, "s", &["B", "A"], 10), o(ASKED, "s", &["C"], 30), o(ASKED, "t", &["D"], 10)];
1616        let ids = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1617        let blame = |log: &[Outcome], target: &[String]| regretted(log, "s", 20, "R1", target, 0.5, 99, "r");
1618        let got = blame(&log, &[]);
1619        let want = |l: &str, credit: f64| Outcome { cause: "R1".into(), credit, ..o(REGRETTED, "s", &[l], 99) };
1620        assert_eq!(got, vec![want("A", 0.25), want("B", 0.25)], "shared; C was asked after the decision, G never shown");
1621        assert_eq!(blame(&log, &ids(&["B", "Z"])), vec![want("B", 0.5)], "the merge target takes it all");
1622        assert_eq!(blame(&log, &ids(&["Z"])), got, "a target not asked: shared");
1623        let mut corrected = log.clone();
1624        corrected.push(o(CORRECTED, "s", &["B"], 15));
1625        assert_eq!(blame(&corrected, &[]), vec![want("A", 0.5)], "corrected outranks regretted");
1626        let mut vetoed = log.clone();
1627        vetoed.push(o(VETOED, "s", &["B"], 15));
1628        assert_eq!(blame(&vetoed, &[]), vec![want("A", 0.5)], "vetoed outranks regretted");
1629        assert!(blame(&corrected, &ids(&["B"])).is_empty(), "the target took it as a correction: nobody else is blamed");
1630        assert!(blame(&vetoed, &ids(&["B", "Z"])).is_empty(), "the target took it as a veto: nobody else is blamed");
1631        assert_eq!(blame(&corrected, &ids(&["A", "B"])), vec![want("A", 0.5)], "the uncorrected target keeps its share");
1632        let mut again = log.clone();
1633        again.extend(got.clone());
1634        assert!(blame(&again, &[]).is_empty(), "credited once per cause");
1635        let mut half = log.clone();
1636        half.push(got[0].clone());
1637        assert_eq!(blame(&half, &[]), vec![want("B", 0.25)], "a partial run completes with the same share");
1638        assert_eq!(regretted(&again, "s", 20, "R2", &[], 0.5, 99, "r").len(), 2, "another regret blames again");
1639        assert!(regretted(&log, "u", 20, "R1", &[], 0.5, 99, "r").is_empty(), "another session asked nothing");
1640        assert!(regretted(&log, "", 20, "R1", &[], 0.5, 99, "r").is_empty());
1641        assert!(regretted(&log, "s", 0, "R1", &[], 0.5, 99, "r").is_empty(), "no decision time");
1642        assert!(regretted(&log, "s", 20, "R1", &[], 0.0, 99, "r").is_empty(), "not strong");
1643        // An old line without cause and credit still reads; a regretted line round-trips.
1644        let old: Outcome = serde_json::from_str(r#"{"kind":"asked","session":"s","lessons":["A"],"ms":1,"repo":"r"}"#).unwrap();
1645        assert_eq!(old, o(ASKED, "s", &["A"], 1));
1646        assert!(!serde_json::to_string(&old).unwrap().contains("credit"));
1647        let line = serde_json::to_string(&got[0]).unwrap();
1648        assert!(line.contains(r#""cause":"R1","credit":0.25"#), "{line}");
1649        assert_eq!(serde_json::from_str::<Outcome>(&line).unwrap(), got[0]);
1650    }
1651
1652    #[test]
1653    fn a_line_from_before_propensities_reads_and_writes_back_unchanged() {
1654        let line = r#"{"kind":"asked","session":"s","lessons":["A","B"],"ms":1,"repo":"r","channel":"stop","grades":[3,1],"ranks":[0,1],"applied":2}"#;
1655        let o: Outcome = serde_json::from_str(line).unwrap();
1656        assert!(o.p.is_empty());
1657        assert_eq!(serde_json::to_string(&o).unwrap(), line);
1658        let with = Outcome { p: vec![round_p(1.0), round_p(1.0 / 3.0)], ..o };
1659        assert!(serde_json::to_string(&with).unwrap().ends_with(r#""applied":2,"p":[1.0,0.3333]}"#));
1660    }
1661
1662    #[test]
1663    fn a_graded_line_from_before_select_reads_and_writes_back_unchanged() {
1664        let line = r#"{"kind":"graded","session":"s","lessons":["A","B"],"ms":1,"repo":"r","channel":"live","grades":[3,1],"ranks":[0,1],"applied":2,"chosen":["A","B"],"explore":true,"p":[1.0,0.1]}"#;
1665        let o: Outcome = serde_json::from_str(line).unwrap();
1666        assert!(o.check.is_empty() && o.policy.is_empty() && o.free.is_empty() && o.pf.is_empty() && o.judge == 0 && !o.failed);
1667        assert!(o.nofree.is_empty() && o.tail.is_empty() && o.pt == 0.0 && o.rel.is_empty());
1668        assert_eq!(serde_json::to_string(&o).unwrap(), line);
1669        // A 0.6.0 graded line and an early delivery's from before `nofree`, `tail`, `pt` and `rel`.
1670        for line in [
1671            r#"{"kind":"graded","session":"s","lessons":["A","B","C"],"ms":1,"repo":"r","channel":"stop","grades":[2,1,1],"ranks":[0,1,2],"applied":3,"p":[0.0,0.0,0.0],"check":"0123456789ab","policy":"learned","fit":"120-ab12","seen":"9-abcdef01","source":"fixed","free":["A","B"],"pf":[1.0,1.0,0.0],"placebo":["C"],"psi":1.0,"eligible":40,"shown":30,"tokens":12000,"fill":[0,4,7],"model":"m","version":"0.6.0","dur_ms":9000,"usd":0.01}"#,
1672            r#"{"kind":"asked","session":"s","lessons":["A","B"],"ms":2,"repo":"r","channel":"early","p":[1.0,0.5],"route":"asked"}"#,
1673        ] {
1674            let o: Outcome = serde_json::from_str(line).unwrap();
1675            assert!(o.nofree.is_empty() && o.tail.is_empty() && o.pt == 0.0 && o.rel.is_empty(), "{line}");
1676            assert_eq!((o.xk, o.xs), (None, None), "{line}");
1677            assert_eq!(serde_json::to_string(&o).unwrap(), line);
1678        }
1679    }
1680
1681    #[test]
1682    fn the_selection_fields_round_trip_and_stay_local() {
1683        let g = Outcome {
1684            check: "0123456789ab".into(),
1685            policy: "learned".into(),
1686            fit: "120-ab12".into(),
1687            free: vec!["B".into()],
1688            pf: vec![0.0, 1.0, 0.0],
1689            placebo: vec!["C".into()],
1690            psi: 0.5,
1691            nofree: vec!["N9".into()],
1692            xk: Some(2),
1693            xs: Some(0),
1694            tail: vec!["T9".into()],
1695            pt: 0.125,
1696            eligible: 40,
1697            shown: 30,
1698            tokens: 12_000,
1699            fill: vec![0, 4, 7],
1700            model: "m".into(),
1701            prompt_hash: "ph".into(),
1702            harness: "claude".into(),
1703            version: "0.6.0".into(),
1704            dur_ms: 9_000,
1705            failed: true,
1706            ..o(GRADED, "s", &["A", "B", "C"], 5)
1707        };
1708        let delivered = Outcome { check: "0123456789ab".into(), route: ROUTE_DROPPED_CHARS.into(), reason: "budget".into(), ..o(ASKED, "s", &["B"], 6) };
1709        let judged = Outcome { check: "0123456789ab".into(), judge: 2, stripped: true, ..o(CHANGED, "s", &["A"], 7) };
1710        let early = Outcome { channel: "early".into(), rel: vec![0.75], ..o(ASKED, "s", &["D"], 8) };
1711        // Shareable kinds carrying every per-check field, so `share` is put to the test on each.
1712        let carried = Outcome { nofree: g.nofree.clone(), xk: g.xk, xs: g.xs, tail: g.tail.clone(), pt: g.pt, rel: vec![0.75], ..judged.clone() };
1713        for x in [&g, &delivered, &judged, &early, &carried] {
1714            let line = serde_json::to_string(x).unwrap();
1715            assert_eq!(&serde_json::from_str::<Outcome>(&line).unwrap(), x, "round trip");
1716        }
1717        // The test's s = 0 is logged, not skipped: it is a draw, not an absent field.
1718        assert!(serde_json::to_string(&g).unwrap().contains(r#""xk":2,"xs":0"#));
1719        assert!(share(&g, "n1").is_none(), "graded stays local");
1720        for x in [&delivered, &judged, &early, &carried] {
1721            let shared = serde_json::to_string(&share(x, "n1").unwrap()).unwrap();
1722            for field in
1723                ["check", "0123456789ab", "route", "reason", "judge", "stripped", "nofree", "N9", "xk", "xs", "tail", "T9", "pt", "0.125", "rel", "0.75"]
1724            {
1725                assert!(!shared.contains(field), "{field}: {shared}");
1726            }
1727        }
1728        assert!(ROUTES.iter().all(|r| !r.is_empty() && !r.contains(' ')), "one word each");
1729    }
1730
1731    #[test]
1732    fn an_older_graded_record_is_the_fixed_rule_unless_it_shows_the_cut() {
1733        let graded = |grades: &[u8], chosen: &[&str], p: &[f64]| Outcome {
1734            lessons: (0..grades.len()).map(|i| format!("L{i:02}")).collect(),
1735            grades: grades.to_vec(),
1736            chosen: chosen.iter().map(|c| c.to_string()).collect(),
1737            p: p.to_vec(),
1738            ..o(GRADED, "s", &[], 1)
1739        };
1740        // No 3: the fixed rule hands over the 2s, then the 1s, at most CAP.
1741        let soft: Vec<u8> = [vec![1; 6], vec![2; 6]].concat();
1742        let old = graded(&soft, &[], &[0.0; 12]);
1743        assert_eq!(policy_of(&old), "fixed");
1744        let want: Vec<String> = (6..12).chain(0..4).map(|i| format!("L{i:02}")).collect();
1745        assert_eq!(free_of(&old), want);
1746        // A 3: the fixed rule asks, hands over nothing.
1747        let block = graded(&[3, 1], &["L00", "L01"], &[1.0, 1.0]);
1748        assert_eq!((policy_of(&block), free_of(&block)), ("fixed", Vec::<String>::new()));
1749        // The learned cut: a propensity between 0 and 1, or an explored check; the rest go free.
1750        let cut = graded(&[3, 1, 1, 1], &["L00", "L01"], &[1.0, 1.0, 0.1, 0.1]);
1751        assert_eq!((policy_of(&cut), free_of(&cut)), ("attention", vec!["L02".to_string(), "L03".into()]));
1752        let explored = Outcome { explore: true, ..graded(&[3, 1, 1], &["L00", "L01", "L02"], &[1.0, 1.0, 1.0]) };
1753        assert_eq!((policy_of(&explored), free_of(&explored)), ("attention", Vec::<String>::new()));
1754        // A record that names its policy is taken at its word, its free list as logged.
1755        let named = Outcome { policy: "learned".into(), free: vec!["L01".into()], ..graded(&[3, 1], &["L00"], &[1.0, 0.0]) };
1756        assert_eq!((policy_of(&named), free_of(&named)), ("learned", vec!["L01".to_string()]));
1757    }
1758
1759    fn tmp(name: &str) -> std::path::PathBuf {
1760        let d = std::env::temp_dir().join(format!("borg-outcome-{name}-{}", std::process::id()));
1761        let _ = std::fs::remove_dir_all(&d);
1762        std::fs::create_dir_all(&d).unwrap();
1763        d
1764    }
1765
1766    fn lines(path: &Path, v: &[String]) {
1767        std::fs::write(path, v.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
1768    }
1769
1770    fn changed(team: &[Outcome], lesson: &str) -> u32 {
1771        let ls = [crate::conscience::Challenge { id: lesson.into(), ..Default::default() }];
1772        crate::memory::derive(team, &ls, None)[lesson].changed
1773    }
1774
1775    #[test]
1776    fn share_redacts() {
1777        let mut a = o(ASKED, "session-raw", &["A"], 5);
1778        a.repo = "secret-repo".into();
1779        a.groups = vec![vec!["A".into(), "B".into()]];
1780        a.grades = vec![3];
1781        a.ranks = vec![0];
1782        a.p = vec![0.5];
1783        let x = share(&a, "n1").unwrap();
1784        let line = serde_json::to_string(&x).unwrap();
1785        for raw in ["session-raw", "secret-repo", "groups", "grades", "ranks", "\"id\"", "version"] {
1786            assert!(!line.contains(raw), "{raw} in {line}");
1787        }
1788        assert_eq!((x.s, x.r, x.p, x.node), (tag("session-raw"), tag("secret-repo"), vec![0.5], "n1".to_string()));
1789        assert_eq!(tag("s").len(), 32);
1790        for kind in [GRADED, "veto"] {
1791            assert!(share(&o(kind, "s", &["A"], 1), "n1").is_none(), "{kind} is not shared");
1792        }
1793        let regret = share(&Outcome { cause: "episode-raw".into(), credit: 0.25, ..o(REGRETTED, "s", &["A"], 1) }, "n1").unwrap();
1794        let line = serde_json::to_string(&regret).unwrap();
1795        assert!(!line.contains("episode-raw") && line.contains(&tag("episode-raw")) && line.contains(r#""credit":0.25"#), "{line}");
1796    }
1797
1798    #[test]
1799    fn pool_fields_stay_local() {
1800        let a = Outcome { pool: vec!["A".into(), "B".into()], base: vec![1.25, 0.5], scoped: vec![true, false], p: vec![0.5], ..o(ASKED, "s", &["A"], 5) };
1801        let line = serde_json::to_string(&a).unwrap();
1802        assert_eq!(serde_json::from_str::<Outcome>(&line).unwrap(), a, "round trip");
1803        let shared = serde_json::to_string(&share(&a, "n1").unwrap()).unwrap();
1804        for field in ["pool", "base", "scoped"] {
1805            assert!(line.contains(field) && !shared.contains(field), "{field}: {shared}");
1806        }
1807        assert!(!serde_json::to_string(&o(ASKED, "s", &["A"], 5)).unwrap().contains("pool"), "empty: not written");
1808    }
1809
1810    #[test]
1811    fn publish_is_idempotent() {
1812        let home = tmp("publish");
1813        assert_eq!(publish(&home), 0, "no outcomes, nothing to publish");
1814        let mut asked = o(ASKED, "s1", &["A"], 1);
1815        asked.p = vec![1.0];
1816        lines(&home.join("outcomes.jsonl"), &[asked, o(GRADED, "s1", &["A"], 1), o(CHANGED, "s1", &["A"], 2)].map(|x| serde_json::to_string(&x).unwrap()));
1817        assert_eq!(publish(&home), 2, "graded stays local");
1818        let first = std::fs::read_to_string(home.join(TEAM_FILE)).unwrap();
1819        assert_eq!(publish(&home), 0);
1820        assert_eq!(std::fs::read_to_string(home.join(TEAM_FILE)).unwrap(), first);
1821        assert!(first.contains(r#""p":[1.0]"#) && !first.contains("\"s1\""), "{first}");
1822        // Unchanged since the last publish: the log is not read again; grown: only the new line goes.
1823        assert_eq!(std::fs::read_to_string(home.join(PUBLISHED)).unwrap(), std::fs::metadata(home.join("outcomes.jsonl")).unwrap().len().to_string());
1824        std::fs::OpenOptions::new()
1825            .append(true)
1826            .open(home.join("outcomes.jsonl"))
1827            .and_then(|mut f| std::io::Write::write_all(&mut f, format!("{}\n", serde_json::to_string(&o(IGNORED, "s2", &["A"], 3)).unwrap()).as_bytes()))
1828            .unwrap();
1829        assert_eq!(publish(&home), 1);
1830        assert_eq!(publish(&home), 0);
1831        // A team file gone (a fresh mesh) is published again in full.
1832        std::fs::remove_file(home.join(TEAM_FILE)).unwrap();
1833        assert_eq!(publish(&home), 3);
1834        let _ = std::fs::remove_dir_all(home);
1835    }
1836
1837    /// A store whose local log has s1 changed L1, and whose team file holds that result as published
1838    /// by this node, a remote session's change of L1, the same remote line from another node's copy,
1839    /// and a kind this binary does not share.
1840    fn team_store(name: &str, shuffle: bool) -> std::path::PathBuf {
1841        let home = tmp(name);
1842        let mut local = o(CHANGED, "s1", &["L1"], 10);
1843        local.repo = "app".into();
1844        lines(&home.join("outcomes.jsonl"), &[serde_json::to_string(&local).unwrap()]);
1845        let remote = |kind: &str, s: &str, node: &str| {
1846            serde_json::to_string(&Shared {
1847                kind: kind.into(),
1848                s: s.into(),
1849                lessons: vec!["L1".into()],
1850                ms: 20,
1851                node: node.into(),
1852                r: tag("web"),
1853                ..Default::default()
1854            })
1855            .unwrap()
1856        };
1857        let mut team = vec![
1858            serde_json::to_string(&share(&local, "me").unwrap()).unwrap(),
1859            remote(CHANGED, "x", "n2"),
1860            remote(CHANGED, "x", "n3"),
1861            remote("hacked", "y", "n2"),
1862            remote("veto", "z", "n2"),
1863        ];
1864        if shuffle {
1865            team.reverse();
1866            team.swap(0, 2);
1867        }
1868        lines(&home.join(TEAM_FILE), &team);
1869        home
1870    }
1871
1872    #[test]
1873    fn read_team_drops_own_copies_and_keeps_remote() {
1874        let home = team_store("team", false);
1875        let team = team_view(&home.join("lessons.jsonl"), true);
1876        assert_eq!(changed(&team, "L1"), 2, "{team:?}");
1877        assert_eq!(team.iter().filter(|o| o.session == "x").count(), 1, "one remote line per (kind, session, lessons, ms)");
1878        assert!(team.iter().all(|o| o.kind != "hacked" && o.kind != "veto"), "unshared kinds, an older peer's hive verdict among them, are ignored");
1879        assert!(team.iter().all(|o| o.repo != "app"), "local repos compare as tags");
1880        let _ = std::fs::remove_dir_all(home);
1881    }
1882
1883    #[test]
1884    fn read_team_is_order_independent() {
1885        let (a, b) = (team_store("order-a", false), team_store("order-b", true));
1886        let ls = [crate::conscience::Challenge { id: "L1".into(), ..Default::default() }];
1887        let m = |h: &Path| crate::memory::derive(&team_view(&h.join("lessons.jsonl"), true), &ls, None);
1888        assert_eq!(m(&a), m(&b));
1889        let _ = std::fs::remove_dir_all(a);
1890        let _ = std::fs::remove_dir_all(b);
1891    }
1892
1893    /// A node's whole fold reaches its peers: a veto that outranks the session's change, a regret's
1894    /// credit, and a session that only graded (no tick on either node). A peer holding only the team file
1895    /// derives the same memory as the node that recorded it.
1896    #[test]
1897    fn a_peer_derives_the_same_memory_from_the_team_file() {
1898        let (a, b) = (tmp("fold-a"), tmp("fold-b"));
1899        let regret = Outcome { cause: "episode-1".into(), credit: 0.5, ..o(REGRETTED, "s2", &["L1"], 40) };
1900        let log = [
1901            o(GRADED, "s0", &["L1"], 5),
1902            o(ASKED, "s1", &["L1"], 10),
1903            o(CHANGED, "s1", &["L1"], 20),
1904            o(VETOED, "s1", &["L1"], 30),
1905            o(ASKED, "s2", &["L1"], 35),
1906            regret,
1907        ];
1908        lines(&a.join("outcomes.jsonl"), &log.map(|x| serde_json::to_string(&x).unwrap()));
1909        publish(&a);
1910        std::fs::copy(a.join(TEAM_FILE), b.join(TEAM_FILE)).unwrap();
1911        let ls = [crate::conscience::Challenge { id: "L1".into(), origin_ms: 1, ..Default::default() }];
1912        let m = |h: &Path| crate::memory::derive(&team_view(&h.join("lessons.jsonl"), true), &ls, None);
1913        let (here, there) = (m(&a), m(&b));
1914        assert_eq!((here["L1"].vetoed, here["L1"].changed, here["L1"].regretted), (1, 0, 0.5), "{here:?}");
1915        assert_eq!(here, there);
1916        let _ = std::fs::remove_dir_all(a);
1917        let _ = std::fs::remove_dir_all(b);
1918    }
1919
1920    /// The unguarded surface `SHARED_KINDS` documents, pinned until the deferred guards land: a remote
1921    /// line under one of this node's session tags is dropped here, whatever its kind, while a peer
1922    /// without that session takes it, and the stronger result wins there.
1923    #[test]
1924    fn a_remote_line_under_a_local_tag_counts_on_peers_only() {
1925        let (victim, peer) = (tmp("forged-victim"), tmp("forged-peer"));
1926        let own = o(CHANGED, "s1", &["L1"], 10);
1927        let forged = Shared { kind: CORRECTED.into(), s: tag("s1"), lessons: vec!["L1".into()], ms: 11, node: "n2".into(), ..Default::default() };
1928        let team = [serde_json::to_string(&share(&own, "me").unwrap()).unwrap(), serde_json::to_string(&forged).unwrap()];
1929        lines(&victim.join("outcomes.jsonl"), &[serde_json::to_string(&own).unwrap()]);
1930        lines(&victim.join(TEAM_FILE), &team);
1931        lines(&peer.join(TEAM_FILE), &team);
1932        let ls = [crate::conscience::Challenge { id: "L1".into(), ..Default::default() }];
1933        let m = |h: &Path| crate::memory::derive(&team_view(&h.join("lessons.jsonl"), true), &ls, None).remove("L1").unwrap();
1934        assert_eq!((m(&victim).changed, m(&victim).corrected), (1, 0), "the victim never sees the override");
1935        assert_eq!((m(&peer).changed, m(&peer).corrected), (0, 1), "a peer counts the forged correction");
1936        let _ = std::fs::remove_dir_all(victim);
1937        let _ = std::fs::remove_dir_all(peer);
1938    }
1939
1940    /// A peer's `tested` line counts for a lesson its session's shared records name, and for no other.
1941    #[test]
1942    fn a_peer_green_run_counts_only_for_lessons_its_session_was_given() {
1943        let home = tmp("tested-team");
1944        let asked = share(&o(ASKED, "p1", &["L1"], 10), "peer").unwrap();
1945        let ok = share(&o(TESTED, "p1", &["L1"], 20), "peer").unwrap();
1946        let stray = share(&o(TESTED, "p1", &["L2"], 20), "peer").unwrap();
1947        let alone = share(&o(TESTED, "p2", &["L1"], 20), "peer").unwrap();
1948        // A 0.3.0 peer's hive verdict is not shared any more, so it gives its session nothing.
1949        let verdict = Shared { kind: "verified".into(), ..share(&o(ASKED, "p3", &["L1"], 10), "peer").unwrap() };
1950        let unbacked = share(&o(TESTED, "p3", &["L1"], 20), "peer").unwrap();
1951        let all = [&asked, &ok, &stray, &alone, &verdict, &unbacked];
1952        lines(&home.join(TEAM_FILE), &all.map(|x| serde_json::to_string(x).unwrap()));
1953        let ls = ["L1", "L2"].map(|id| crate::conscience::Challenge { id: id.into(), ..Default::default() });
1954        let m = crate::memory::derive(&team_view(&home.join("lessons.jsonl"), true), &ls, None);
1955        assert_eq!((m["L1"].tested, m["L2"].tested), (1, 0), "{m:?}");
1956        let _ = std::fs::remove_dir_all(home);
1957    }
1958
1959    #[test]
1960    fn off_keeps_beliefs_local() {
1961        let home = team_store("off", false);
1962        let local = team_view(&home.join("lessons.jsonl"), false);
1963        assert_eq!(local, read(&home.join("outcomes.jsonl")));
1964        assert_eq!(changed(&local, "L1"), 1);
1965        let _ = std::fs::remove_dir_all(home);
1966    }
1967
1968    /// Several writers appending to one log at once (several drones on one store): every record
1969    /// reads back, none torn into `{A}{B}\n\n`.
1970    #[test]
1971    fn concurrent_appends_keep_every_record() {
1972        let home = tmp("concurrent");
1973        let p = home.join("outcomes.jsonl");
1974        let (writers, each) = (8, 2000);
1975        std::thread::scope(|scope| {
1976            for w in 0..writers {
1977                let p = &p;
1978                scope.spawn(move || (0..each).for_each(|i| append(p, &o(ASKED, &format!("s{w}"), &["A"], i)).unwrap()));
1979            }
1980        });
1981        assert_eq!(read(&p).len(), writers * each as usize);
1982        let _ = std::fs::remove_dir_all(home);
1983    }
1984
1985    #[test]
1986    fn append_and_read_round_trip() {
1987        let dir = std::env::temp_dir().join(format!("borg-outcome-{}", std::process::id()));
1988        let p = dir.join("outcomes.jsonl");
1989        let _ = std::fs::remove_file(&p);
1990        append(&p, &o(ASKED, "s", &["A"], 1)).unwrap();
1991        append(&p, &o(CORRECTED, "s", &["A"], 2)).unwrap();
1992        assert_eq!(read(&p), vec![o(ASKED, "s", &["A"], 1), o(CORRECTED, "s", &["A"], 2)]);
1993        let _ = std::fs::remove_dir_all(dir);
1994    }
1995}