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, before 0.7.6), `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    /// `graded` (0.7.7 on): the model's design moves of the work it checked (predict.rs
417    /// `Prediction::moves`), and per apply (aligned with `lessons`) its one-line why; empty in older
418    /// records and on a failed call. Local, as the whole record is (`share`).
419    #[serde(default, skip_serializing_if = "Vec::is_empty")]
420    pub moves: Vec<String>,
421    #[serde(default, skip_serializing_if = "Vec::is_empty")]
422    pub whys: Vec<String>,
423    /// `graded` (0.7.7 on): the tokens the call showed past `tokens`, the boundary draw's and the tail
424    /// sample's (`tail`), so a prompt's whole lesson size is `tokens` + `xtokens`; 0 without any, and in
425    /// older records. Logged only: the latency fit reads `tokens`, the size a budget is predicted at.
426    #[serde(default, skip_serializing_if = "is_default")]
427    pub xtokens: u32,
428    /// `graded` (0.7.7 on): the lesson line format of the compact prompt (whole.rs `Line`, `a1` or
429    /// `a2`); empty without it (`BORG_STOP_FORMAT=classic`, the shortlist) and in older records.
430    #[serde(default, skip_serializing_if = "String::is_empty")]
431    pub line: String,
432    /// `graded` (0.7.7 on): how its check ran, `async` for a detached check (check_async.rs); empty for
433    /// a stop's own check and in older records.
434    #[serde(default, skip_serializing_if = "String::is_empty")]
435    pub run: String,
436}
437
438/// `route` values. Protocol: what a check decided for a lesson, then what delivery did with it.
439/// Asked, handed over free, or judged as a placebo, as decided; or dropped at delivery because the
440/// session had the lesson already (`ROUTE_DROPPED_DONE`) or the delivery budget was spent
441/// (`ROUTE_DROPPED_CHARS`); or never delivered because the session ended first (`ROUTE_NEVER`); or (0.7.7
442/// on) a detached check's waiting ask taken off the queue because a newer check asks the same lesson
443/// (`ROUTE_SUPERSEDED`): the newer ask carries its delivery.
444pub const ROUTE_ASKED: &str = "asked";
445pub const ROUTE_FREE: &str = "free";
446pub const ROUTE_PLACEBO: &str = "placebo";
447pub const ROUTE_DROPPED_DONE: &str = "dropped_done";
448pub const ROUTE_DROPPED_CHARS: &str = "dropped_chars";
449pub const ROUTE_NEVER: &str = "never_delivered";
450pub const ROUTE_SUPERSEDED: &str = "superseded";
451pub const ROUTES: [&str; 7] = [ROUTE_ASKED, ROUTE_FREE, ROUTE_PLACEBO, ROUTE_DROPPED_DONE, ROUTE_DROPPED_CHARS, ROUTE_NEVER, ROUTE_SUPERSEDED];
452
453/// The policy a `graded` record was decided under: its `policy`; for a record from before select.rs,
454/// the fixed rule (`fixed`), unless it shows the one other policy an older binary logged,
455/// `BORG_STOP_ATTENTION=on`'s learned cut (`attention`): it explored, or a propensity lies strictly
456/// between 0 and 1 (attention.rs `propensities`). A learned cut that asked every apply up to its rail
457/// logged only 0s and 1s, and an evaluation's `BORG_STOP_ASK_CAP` logged nothing of its cap: both read
458/// as the fixed rule.
459#[must_use]
460pub fn policy_of(o: &Outcome) -> &str {
461    match o.policy.as_str() {
462        "" if o.explore || o.p.iter().any(|p| *p > 0.0 && *p < 1.0) => "attention",
463        "" => "fixed",
464        p => p,
465    }
466}
467
468/// The lessons a `graded` record handed over free: its `free`; for a record from before select.rs
469/// (`policy` empty), its policy's rule (`policy_of`) replayed on its grades: the fixed rule's 2s, then
470/// 1s, at most `conscience::CAP`, when no lesson is a 3 (conscience.rs `graded_capped`), else none; the
471/// learned cut's lessons after the ones it asked, at most `conscience::CAP` (attention.rs `split`).
472#[must_use]
473pub fn free_of(o: &Outcome) -> Vec<String> {
474    use crate::conscience::{self, Challenge};
475    if !o.policy.is_empty() || o.grades.len() != o.lessons.len() {
476        return o.free.clone();
477    }
478    if o.grades.contains(&3) {
479        return match policy_of(o) {
480            "attention" => o.lessons.iter().filter(|l| !o.chosen.contains(l)).take(conscience::CAP).cloned().collect(),
481            _ => Vec::new(),
482        };
483    }
484    let ls: Vec<Challenge> = o.lessons.iter().map(|id| Challenge { id: id.clone(), ..Default::default() }).collect();
485    let applied: Vec<(&Challenge, u8)> = ls.iter().zip(o.grades.iter().copied()).collect();
486    conscience::graded_capped(&applied, None).1.into_iter().map(|c| c.id.clone()).collect()
487}
488
489fn is_default<T: Default + PartialEq>(v: &T) -> bool {
490    *v == T::default()
491}
492
493/// A propensity rounded to 4 decimals, so lines stay deterministic and short.
494pub fn round_p(p: f64) -> f64 {
495    (p * 1e4).round() / 1e4
496}
497
498fn is_zero(v: &u16) -> bool {
499    *v == 0
500}
501
502fn is_zero_f(v: &f64) -> bool {
503    *v == 0.0
504}
505
506/// The outcomes store next to a lessons file.
507pub fn path_beside(lessons: &Path) -> std::path::PathBuf {
508    lessons.with_file_name("outcomes.jsonl")
509}
510
511/// The redacted outcomes the team sees, at the store root beside `outcomes.jsonl` (module doc).
512pub const TEAM_FILE: &str = "outcomes-team.jsonl";
513/// Beside `TEAM_FILE`, never synced: the length of `outcomes.jsonl` at the last `publish`.
514pub const PUBLISHED: &str = "outcomes-team.published";
515
516/// The kinds `publish` shares. A whitelist: `graded` and any later kind stay local until deliberately
517/// added here.
518///
519/// Closed under memory.rs `derive`: every kind that changes a lesson's result for a session, or its
520/// belief, travels, so a peer folds the same memory. `vetoed` outranks the session's `changed` (shared
521/// alone, a lesson vetoed here would gain a use and spread there); `regretted` carries its `credit` and
522/// its hashed `cause` (`Shared::c`), the key derive dedupes regrets by. `graded` is the asking policy's
523/// denominator, not a result, and never moves the activity clock (`memory::Clock` counts shared kinds).
524///
525/// Unguarded: any member can write a line under any session tag (tags are public in this file), so a
526/// forged `asked_then_corrected` or `vetoed` overrides a teammate's session on every node but that
527/// teammate's, and a few forged `asked_then_changed` with fresh tags and two repo tags consolidate a
528/// lesson. `node` is self-declared. The mesh admits only members' signed lines (borg-mesh origin.rs),
529/// so this is the trusted-member model; the deferred guards (a session tag bound to its first signer,
530/// consolidation from at least two signers) would close it.
531///
532/// `tested` is shared like `asked_then_changed`, the result it is weaker than: memory folds it, so a peer
533/// without it would hold another belief. Both are this node's own reading of its session (the judge's,
534/// the test runner's output), so the trusted-member model above is the same;
535/// `team_view` counts a peer's `tested` line only for lessons the team's records show its session was
536/// given. It never moves the activity clock either.
537pub const SHARED_KINDS: [&str; 9] = [ASKED, CHANGED, IGNORED, CORRECTED, NOT_CORRECTED, MISSED, VETOED, REGRETTED, TESTED];
538
539/// A session or repo as the team sees it: the first 32 hex digits of blake3("borg-outcome-v1\0" + s).
540/// Unsalted on purpose: the same session hashes to the same tag on every node, so a node can drop its
541/// own published copies (`read_team`).
542pub fn tag(s: &str) -> String {
543    let mut h = blake3::Hasher::new();
544    h.update(b"borg-outcome-v1\0");
545    h.update(s.as_bytes());
546    h.finalize().to_hex()[..32].to_string()
547}
548
549/// `tag`, keeping an empty repo empty.
550fn tag_repo(repo: &str) -> String {
551    if repo.is_empty() { String::new() } else { tag(repo) }
552}
553
554/// One line of `TEAM_FILE`. Never carries `id` and `version` together (the mesh would settle it as a
555/// versioned record).
556#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
557pub struct Shared {
558    pub kind: String,
559    /// `tag` of the session.
560    pub s: String,
561    pub lessons: Vec<String>,
562    pub ms: i64,
563    /// The publishing node (stats.rs `node`), self-declared: dedup does not depend on it.
564    pub node: String,
565    #[serde(default, skip_serializing_if = "Vec::is_empty")]
566    pub p: Vec<f64>,
567    #[serde(default, skip_serializing_if = "String::is_empty")]
568    pub channel: String,
569    /// `tag` of the repo: memory.rs counts distinct repos to consolidate a lesson.
570    #[serde(default, skip_serializing_if = "String::is_empty")]
571    pub r: String,
572    /// `tag` of a `regretted` record's cause (the regret episode): memory.rs counts each regret once.
573    #[serde(default, skip_serializing_if = "String::is_empty")]
574    pub c: String,
575    /// A `regretted` record's share of the blame.
576    #[serde(default, skip_serializing_if = "is_zero_f")]
577    pub credit: f64,
578}
579
580/// `o` as the team sees it, or None for a kind not in `SHARED_KINDS` and for a placebo's result
581/// (`is_result`): the judge's floor on this node, never a result a peer folds.
582pub fn share(o: &Outcome, node: &str) -> Option<Shared> {
583    (SHARED_KINDS.contains(&o.kind.as_str()) && is_result(o)).then(|| Shared {
584        kind: o.kind.clone(),
585        s: tag(&o.session),
586        lessons: o.lessons.clone(),
587        ms: o.ms,
588        node: node.into(),
589        p: o.p.clone(),
590        channel: o.channel.clone(),
591        r: tag_repo(&o.repo),
592        c: tag_repo(&o.cause),
593        credit: o.credit,
594    })
595}
596
597/// Team outcomes on: `BORG_SHARE_OUTCOMES` is not `off`.
598pub fn on() -> bool {
599    std::env::var("BORG_SHARE_OUTCOMES").as_deref() != Ok("off")
600}
601
602/// Appends to `TEAM_FILE` in `home` the shared lines of `home`'s `outcomes.jsonl` it lacks; returns
603/// how many. The lines are deterministic, so a re-run appends nothing; two runs at once may append the
604/// same line twice, which the mesh's union and the per-session count make harmless. Nothing when off.
605/// A local log no longer than at the last publish (`PUBLISHED`, its length then) is not read again: the
606/// log only grows, so nothing new can be in it.
607pub fn publish(home: &Path) -> usize {
608    let local = home.join("outcomes.jsonl");
609    let team = home.join(TEAM_FILE);
610    let mark = home.join(PUBLISHED);
611    let len = std::fs::metadata(&local).map_or(0, |m| m.len());
612    if !on() || len == 0 {
613        return 0;
614    }
615    let published = std::fs::read_to_string(&mark).ok().and_then(|t| t.trim().parse::<u64>().ok());
616    if team.exists() && published == Some(len) {
617        return 0;
618    }
619    let mine = std::fs::read_to_string(&local).unwrap_or_default();
620    let node = crate::stats::node(home);
621    let text = std::fs::read_to_string(&team).unwrap_or_default();
622    let mut have: std::collections::HashSet<String> = text.lines().map(str::to_string).collect();
623    let mut out = String::new();
624    // This engineer's personal lessons (reach.rs) are no team's business, not even by id.
625    let personal = crate::reach::personal_ids(home);
626    let records = mine.lines().filter_map(|l| serde_json::from_str::<Outcome>(l).ok()).filter_map(|mut o| {
627        let named = !o.lessons.is_empty();
628        o.lessons.retain(|id| !personal.contains(id));
629        (!named || !o.lessons.is_empty()).then_some(o)
630    });
631    for line in records.filter_map(|o| share(&o, &node)).filter_map(|x| serde_json::to_string(&x).ok()) {
632        if have.insert(line.clone()) {
633            out.push_str(&line);
634            out.push('\n');
635        }
636    }
637    if out.is_empty() {
638        let _ = std::fs::write(&mark, mine.len().to_string());
639        return 0;
640    }
641    use std::io::Write;
642    let open = text.as_bytes().last().is_some_and(|c| *c != b'\n');
643    let written = std::fs::OpenOptions::new()
644        .create(true)
645        .append(true)
646        .open(&team)
647        .and_then(|mut f| f.write_all(format!("{}{out}", if open { "\n" } else { "" }).as_bytes()));
648    if written.is_err() {
649        return 0;
650    }
651    let _ = std::fs::write(&mark, mine.len().to_string());
652    out.lines().count()
653}
654
655/// The belief view of the outcomes beside `lessons`: this machine's log plus, unless
656/// BORG_SHARE_OUTCOMES=off, the team's (`team_view`).
657pub fn read_team(lessons: &Path) -> Vec<Outcome> {
658    team_view(lessons, on())
659}
660
661/// Off: this machine's log as is. On: its records with each repo and cause as its `tag` (memory.rs only
662/// compares them for distinctness, so beliefs are the same and comparable with the team's), then the
663/// team's lines that count (`team_parts`). A remote session then counts once per lesson like a local
664/// one (memory.rs `derive`, `sessions`). learn.rs keys on raw causes: it reads this
665/// machine's log (`read`).
666pub fn team_view(lessons: &Path, on: bool) -> Vec<Outcome> {
667    let (mut out, team) = team_parts(lessons, on);
668    if on {
669        for o in &mut out {
670            o.repo = tag_repo(&o.repo);
671            o.cause = tag_repo(&o.cause);
672        }
673    }
674    out.extend(team);
675    out
676}
677
678/// This machine's records as written, and (on) every `TEAM_FILE` line of a shared kind whose session
679/// is not one of this machine's (that drops this node's own published copies, whatever its node id),
680/// once per (kind, session, lessons, ms, cause): one read of each file, so the two never disagree on
681/// where the local records end (ope.rs reads both). A kind this binary does not share (a newer node's,
682/// or an older one's hive verdict) is ignored, and so is a `tested` line naming a lesson the team's
683/// records do not show its session was given.
684pub fn team_parts(lessons: &Path, on: bool) -> (Vec<Outcome>, Vec<Outcome>) {
685    let local = read(&path_beside(lessons));
686    if !on {
687        return (local, Vec::new());
688    }
689    let mine: std::collections::HashSet<String> = local.iter().map(|o| tag(&o.session)).collect();
690    let text = std::fs::read_to_string(lessons.with_file_name(TEAM_FILE)).unwrap_or_default();
691    let lines: Vec<Shared> = text.lines().filter_map(|l| serde_json::from_str::<Shared>(l).ok()).collect();
692    // The lessons each team session's shared records name: a green run credits only lessons it was given.
693    let mut given: std::collections::HashMap<&str, std::collections::HashSet<&str>> = std::collections::HashMap::new();
694    for x in lines.iter().filter(|x| SHARED_KINDS.contains(&x.kind.as_str()) && x.kind != TESTED) {
695        given.entry(x.s.as_str()).or_default().extend(x.lessons.iter().map(String::as_str));
696    }
697    let mut seen: std::collections::HashSet<(String, String, Vec<String>, i64, String)> = std::collections::HashSet::new();
698    let mut team = Vec::new();
699    for x in lines.iter() {
700        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()))
701        {
702            continue;
703        }
704        if x.kind == TESTED && !x.lessons.iter().all(|l| given.get(x.s.as_str()).is_some_and(|g| g.contains(l.as_str()))) {
705            continue;
706        }
707        team.push(Outcome {
708            kind: x.kind.clone(),
709            session: x.s.clone(),
710            lessons: x.lessons.clone(),
711            ms: x.ms,
712            repo: x.r.clone(),
713            p: x.p.clone(),
714            channel: x.channel.clone(),
715            cause: x.c.clone(),
716            credit: x.credit,
717            ..Default::default()
718        });
719    }
720    (local, team)
721}
722
723pub fn read(path: &Path) -> Vec<Outcome> {
724    std::fs::read_to_string(path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
725}
726
727/// Appends `o` in one write (learn.rs `append_line`: concurrent writers never tear a record), and
728/// counts it in the usage statistics (`count_result`).
729pub fn append(path: &Path, o: &Outcome) -> std::io::Result<()> {
730    crate::learn::append_jsonl(path, o)?;
731    if let Some(home) = path.parent() {
732        count_result(home, o);
733    }
734    Ok(())
735}
736
737/// `o` in the usage statistics of the store `home`: one event of its result kind with its lessons and
738/// channel. `asked` is already counted as the Stop's block, a `vetoed` result as the `veto` that
739/// credited it (veto.rs); a placebo's result is no result (`is_result`): its "changed" never joins the
740/// deliveries' counts. The judge (hook.rs) writes one record per routing check but counts the lessons
741/// of a call's channel as one event, as before checks had ids.
742pub fn count_result(home: &Path, o: &Outcome) {
743    if !is_result(o) {
744        return;
745    }
746    let kind = match o.kind.as_str() {
747        CHANGED => crate::stats::CHANGED,
748        IGNORED => crate::stats::IGNORED,
749        CORRECTED => crate::stats::CORRECTED,
750        NOT_CORRECTED => crate::stats::NOT_CORRECTED,
751        REGRETTED => crate::stats::REGRETTED,
752        TESTED => crate::stats::TESTED,
753        // Measurements, never results (`is_result` already turned them away).
754        UNCLEAR | REMAINS | NOT_ARISEN => return,
755        _ => return,
756    };
757    crate::stats::count(home, kind, &o.session, |e| {
758        e.repo = o.repo.clone();
759        e.lessons = o.lessons.clone();
760        e.channel = o.channel.clone();
761    });
762}
763
764/// Did the conscience ask `lesson` in `session` before `ms`?
765pub fn asked_before(outcomes: &[Outcome], session: &str, lesson: &str, ms: i64) -> bool {
766    outcomes.iter().any(|o| o.kind == ASKED && o.session == session && o.ms < ms && o.lessons.iter().any(|l| l == lesson))
767}
768
769/// Is a result (`kind`) already recorded for `lesson` in `session`? Keeps `borg learn` idempotent.
770pub fn has(outcomes: &[Outcome], kind: &str, session: &str, lesson: &str) -> bool {
771    outcomes.iter().any(|o| o.kind == kind && o.session == session && o.lessons.iter().any(|l| l == lesson))
772}
773
774/// The lessons a correction at `ms` in `session` shows were asked in vain, each asked in `session`
775/// before `ms` and not yet recorded as corrected or vetoed there (a veto is the stronger result): the lessons the correction `supersedes`
776/// (it contradicts them), and `target`, the lesson it was merged into (the same concern came up
777/// again). When `target` was asked as one side of a rendered disagreement, the engineer sided with
778/// it: the other sides of that disagreement were corrected, not `target`. Sorted, unique.
779pub fn contradicted(outcomes: &[Outcome], session: &str, ms: i64, target: Option<&str>, supersedes: &[String]) -> Vec<String> {
780    let mut out: Vec<String> = supersedes.to_vec();
781    if let Some(t) = target {
782        let sides: Vec<String> = outcomes
783            .iter()
784            .filter(|o| o.kind == ASKED && o.session == session && o.ms < ms)
785            .flat_map(|o| &o.groups)
786            .filter(|g| g.iter().any(|x| x == t))
787            .flatten()
788            .filter(|x| *x != t)
789            .cloned()
790            .collect();
791        match sides.is_empty() {
792            true => out.push(t.to_string()),
793            false => out.extend(sides),
794        }
795    }
796    out.retain(|l| asked_before(outcomes, session, l, ms) && !has(outcomes, CORRECTED, session, l) && !has(outcomes, VETOED, session, l));
797    out.sort();
798    out.dedup();
799    out
800}
801
802/// Was `o` a free delivery (channel `early` or `queued`): lessons handed over as context, no question?
803pub fn free(o: &Outcome) -> bool {
804    o.channel == "early" || o.channel == "queued"
805}
806
807/// The lessons a correction at `ms` in `session` shows were needed and not asked: of the lessons it
808/// `supersedes` and `target` (the lesson it was merged into), those a graded check of the session found
809/// applying before `ms` without choosing them, never asked as a question in the session before `ms` (a
810/// free delivery asks nothing: a lesson only handed over as context stays a miss for the cut,
811/// attention.rs), and not yet recorded as missed there. Sorted, unique.
812pub fn missed(outcomes: &[Outcome], session: &str, ms: i64, target: Option<&str>, supersedes: &[String]) -> Vec<String> {
813    let mut out: Vec<String> = supersedes.iter().cloned().chain(target.map(str::to_string)).collect();
814    let applied_unchosen = |l: &str| {
815        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))
816    };
817    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));
818    out.retain(|l| applied_unchosen(l) && !questioned(l) && !has(outcomes, MISSED, session, l));
819    out.sort();
820    out.dedup();
821    out
822}
823
824/// Has `lesson` been credited for the regret `cause` already (in any session)?
825fn credited(outcomes: &[Outcome], cause: &str, lesson: &str) -> bool {
826    outcomes.iter().any(|o| o.kind == REGRETTED && o.cause == cause && o.lessons.iter().any(|l| l == lesson))
827}
828
829/// The lessons a regret blames: those asked in `session` (the deciding one) before `before_ms`, without
830/// a correction or a veto there already (both outrank regretted, as in memory.rs) and not yet credited
831/// for `cause`. When some of `target` (the lesson the regret was folded into, and the lessons that lesson
832/// supersedes) were asked, they share the blame alone: the same concern came up again, and when all of
833/// them already took a correction or a veto for it, nobody else is blamed. Otherwise every asked lesson
834/// shares it equally (the Shapley value of a symmetric game). A lesson a graded check found applying but
835/// did not ask was never shown, so it is not blamed. One record per lesson, sorted, at `ms`,
836/// with `credit = strength / n`; n counts the blamed lessons before the already-credited ones are left
837/// out, so a re-run writes nothing and the shares never change. Every record's session has an earlier
838/// `asked` record, so it never moves memory.rs's `Clock`.
839#[allow(clippy::too_many_arguments)]
840pub fn regretted(outcomes: &[Outcome], session: &str, before_ms: i64, cause: &str, target: &[String], strength: f64, ms: i64, repo: &str) -> Vec<Outcome> {
841    if session.is_empty() || before_ms <= 0 || strength <= 0.0 {
842        return Vec::new();
843    }
844    let mut asked: Vec<&str> =
845        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();
846    asked.sort_unstable();
847    asked.dedup();
848    if asked.iter().any(|l| target.iter().any(|t| t == l)) {
849        asked.retain(|l| target.iter().any(|t| t == l));
850    }
851    asked.retain(|l| !has(outcomes, CORRECTED, session, l) && !has(outcomes, VETOED, session, l));
852    let credit = (strength / asked.len().max(1) as f64).min(1.0);
853    asked
854        .into_iter()
855        .filter(|l| !credited(outcomes, cause, l))
856        .map(|l| Outcome {
857            kind: REGRETTED.into(),
858            session: session.into(),
859            lessons: vec![l.into()],
860            ms,
861            repo: repo.into(),
862            cause: cause.into(),
863            credit,
864            ..Default::default()
865        })
866        .collect()
867}
868
869/// The `tested` records a session's own test runs earn (`tests`: its `<state>/<session>.tests`, `fail <ms>`
870/// and `pass <ms>` lines, hook.rs `capture_test`): each lesson asked as a question in `session` (a free
871/// delivery asks nothing, `free`: handed over at every prompt of its scope, it would gain from every
872/// 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
873/// made on the lesson's point (`asked_then_changed`), and that has no `tested` record there yet, nor a
874/// correction or a veto (the engineer's word outranks a green run), nor `asked_then_ignored` (red, then
875/// green is also how a feature is built: it does not make an ignored question useful), nor
876/// `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
877/// it, and `tested` would move a belief `asked_not_arisen` is censored for). A pass before the ask says nothing
878/// of the lesson. One record per lesson, sorted, at that last pass. Every record's session has an
879/// earlier `asked` record, so it never moves memory.rs's `Clock`.
880pub fn tested(outcomes: &[Outcome], session: &str, tests: &str) -> Vec<Outcome> {
881    let mut runs: Vec<(i64, bool)> = tests
882        .lines()
883        .filter_map(|l| l.split_once(' '))
884        .filter_map(|(w, m)| Some((m.trim().parse::<i64>().ok()?, matches!(w, "pass" | "fail").then_some(w == "pass")?)))
885        .collect();
886    runs.sort_unstable();
887    // Each lesson's first ask in the session, and its repo.
888    let mut first: HashMap<&str, (i64, &str)> = HashMap::new();
889    for o in outcomes.iter().filter(|o| o.kind == ASKED && !free(o) && o.session == session) {
890        for l in &o.lessons {
891            let e = first.entry(l.as_str()).or_insert((o.ms, o.repo.as_str()));
892            if o.ms < e.0 {
893                *e = (o.ms, o.repo.as_str());
894            }
895        }
896    }
897    // A verdict that the question's point never came up, on a question of the lesson (not a placebo's
898    // or a free delivery's, none before its first ask): only that says the green run is not about it.
899    let not_arisen_on_ask = |l: &str, at: i64| {
900        outcomes
901            .iter()
902            .any(|o| o.kind == NOT_ARISEN && o.session == session && o.channel != PLACEBO && !free(o) && o.ms >= at && o.lessons.iter().any(|x| x == l))
903    };
904    let mut out: Vec<Outcome> = first
905        .into_iter()
906        .filter(|(l, _)| ![TESTED, CORRECTED, VETOED, IGNORED].iter().any(|k| has(outcomes, k, session, l)))
907        .filter(|&(l, (at, _))| !not_arisen_on_ask(l, at) || has(outcomes, CHANGED, session, l))
908        .filter_map(|(l, (at, repo))| {
909            let after = &runs[runs.partition_point(|r| r.0 <= at)..];
910            let &(ms, pass) = after.last()?;
911            (pass && (after.iter().any(|r| !r.1) || has(outcomes, CHANGED, session, l))).then(|| Outcome {
912                kind: TESTED.into(),
913                session: session.into(),
914                lessons: vec![l.into()],
915                ms,
916                repo: repo.into(),
917                ..Default::default()
918            })
919        })
920        .collect();
921    out.sort_by(|a, b| a.lessons.cmp(&b.lessons));
922    out
923}
924
925/// At session end: every lesson asked in `session` that has no result yet was not corrected, and every
926/// placebo of it without a verdict is closed. A vetoed lesson already has its result. `settle_with`,
927/// every unjudged lesson's reason `no_call`.
928pub fn settle(outcomes: &[Outcome], session: &str, ms: i64) -> Vec<Outcome> {
929    settle_with(outcomes, session, ms, &|_| UNJUDGED_NO_CALL)
930}
931
932/// `settle`, each record with its `reason`: `judged` when the judge gave the lesson's latest ask in the
933/// session a verdict that settles it (`settles`: `asked_then_changed`, `asked_ignored`,
934/// `asked_not_arisen`), else `unjudged(lesson)` (one of the
935/// `UNJUDGED_*`, from the session's state file, hook.rs `unjudged`); and its `check`, the check behind
936/// that latest `asked` record. A verdict on an earlier delivery says nothing of a later question: a
937/// stop that judges a lesson handed over free and then asks it writes the verdict first, and no judge
938/// call need follow the answer. Nor does a verdict on a free delivery (`free`) say anything of a
939/// question (or one on a question of a free delivery), whenever it came: an older binary's live check
940/// judged the earlier free delivery of a lesson asked since and not yet answered (hook.rs `pending`),
941/// and its question, never judged, then settles censored instead of staying open in the selection
942/// summary (select/summary.rs `settled`).
943/// Then every placebo of the session (a `delivery` routed `placebo`, which writes no `asked`) that no
944/// verdict and no earlier settle closed (`open_placebos`): `asked_not_corrected` on channel `placebo`
945/// (no result, `is_result`; it ends no ask's wait, `resolves`) with the placebo's check and repo, and
946/// the reason `unjudged(lesson)` when it is the lesson's latest delivery in the session, else
947/// `UNJUDGED_LATER`. So the selection summary censors an unjudged placebo as it does an unjudged ask
948/// (select/summary.rs `settled`), and the judge-missingness fit sees both.
949/// Not a result: memory.rs reads `asked_not_corrected` as censored, so a verdict recorded after it (a
950/// resumed session) counts once, alone.
951/// The asks first, sorted by lesson id, then the placebos by lesson id and check, so the appended lines
952/// are deterministic. A few passes over the session's records, whatever the number of asks.
953pub fn settle_with(outcomes: &[Outcome], session: &str, ms: i64, unjudged: &dyn Fn(&str) -> &'static str) -> Vec<Outcome> {
954    let mine: Vec<&Outcome> = outcomes.iter().filter(|o| o.session == session).collect();
955    let resolved: std::collections::HashSet<&str> = mine.iter().filter(|o| resolves(o)).flat_map(|o| o.lessons.iter().map(String::as_str)).collect();
956    // Per lesson: its verdicts' (ms, check, on a free delivery).
957    let mut verdicts: HashMap<&str, Vec<(i64, &str, bool)>> = HashMap::new();
958    for o in mine.iter().filter(|o| settles(&o.kind) && o.channel != PLACEBO) {
959        for l in &o.lessons {
960            verdicts.entry(l.as_str()).or_default().push((o.ms, o.check.as_str(), free(o)));
961        }
962    }
963    // Per lesson: the first of its asks' repos in sort order (as before checks were kept), and the
964    // ms, check and whether free of its latest ask.
965    let mut asked: std::collections::BTreeMap<&str, (&str, i64, &str, bool)> = std::collections::BTreeMap::new();
966    // Per lesson: the ms of its latest delivery, an `asked` for every one the drone sees and a
967    // placebo's `delivery`.
968    let mut latest: HashMap<&str, i64> = HashMap::new();
969    for o in mine.iter().filter(|o| o.kind == ASKED || is_placebo(o)) {
970        for l in o.lessons.iter().map(String::as_str) {
971            let t = latest.entry(l).or_insert(o.ms);
972            *t = (*t).max(o.ms);
973            if o.kind != ASKED || resolved.contains(l) {
974                continue;
975            }
976            let e = asked.entry(l).or_insert((o.repo.as_str(), o.ms, o.check.as_str(), free(o)));
977            e.0 = e.0.min(o.repo.as_str());
978            if o.ms >= e.1 {
979                (e.1, e.2, e.3) = (o.ms, o.check.as_str(), free(o));
980            }
981        }
982    }
983    // A verdict on the latest ask is on the same kind of delivery (a question, or free) and came after it
984    // (the judge sees a delivery in a later call), or names its check. Time first: an older binary's stop
985    // wrote one `asked` naming the stop's check also for a lesson another check routed (hook.rs
986    // `#borg-routed`), whose verdict names that check; a stop now writes one `asked` per routing check
987    // (hook.rs `stop_ask`).
988    let judged = |l: &str, at: i64, check: &str, as_free: bool| {
989        verdicts.get(l).is_some_and(|v| v.iter().any(|&(t, c, f)| f == as_free && (t > at || (!check.is_empty() && c == check))))
990    };
991    let mut out: Vec<Outcome> = asked
992        .into_iter()
993        .map(|(l, (repo, at, check, as_free))| Outcome {
994            kind: NOT_CORRECTED.into(),
995            session: session.into(),
996            lessons: vec![l.into()],
997            ms,
998            repo: repo.into(),
999            check: check.into(),
1000            reason: if judged(l, at, check, as_free) { UNJUDGED_NONE } else { unjudged(l) }.into(),
1001            // The binary that settled: from 0.7.3 on, the selection summary closes every delivery of the
1002            // lesson the session left without a verdict (select/summary.rs `settled`).
1003            version: env!("CARGO_PKG_VERSION").into(),
1004            ..Default::default()
1005        })
1006        .collect();
1007    let mut placebos: Vec<Outcome> = open_placebos(&mine)
1008        .into_iter()
1009        .map(|(l, d)| Outcome {
1010            kind: NOT_CORRECTED.into(),
1011            session: session.into(),
1012            lessons: vec![l.into()],
1013            ms,
1014            repo: d.repo.clone(),
1015            channel: PLACEBO.into(),
1016            check: d.check.clone(),
1017            // Delivered again later, the lesson's later delivery is the one the judge saw.
1018            reason: if latest.get(l).is_some_and(|&t| t > d.ms) { UNJUDGED_LATER } else { unjudged(l) }.into(),
1019            ..Default::default()
1020        })
1021        .collect();
1022    placebos.sort_by(|a, b| (&a.lessons, &a.check).cmp(&(&b.lessons, &b.check)));
1023    out.extend(placebos);
1024    out
1025}
1026
1027/// Does `o` end an ask's wait for its result (`settle`)? A placebo's settle record ends none: a
1028/// placebo is never asked, and the lesson may be asked later in the session.
1029fn resolves(o: &Outcome) -> bool {
1030    matches!(o.kind.as_str(), CORRECTED | NOT_CORRECTED | VETOED) && o.channel != PLACEBO
1031}
1032
1033/// A placebo's delivery (`delivery` routed `placebo`, hook.rs `queued`): judged blindly, never shown,
1034/// so it writes no `asked`.
1035fn is_placebo(o: &Outcome) -> bool {
1036    o.kind == DELIVERY && o.route == ROUTE_PLACEBO
1037}
1038
1039/// Does `r`, a placebo channel's verdict that settles (`settles`: `asked_then_changed`, `asked_ignored`,
1040/// `asked_not_arisen`) or settle record (`asked_not_corrected`), close placebo delivery `d` of its
1041/// lesson? A settle record names the placebo's own check, so it closes exactly that one, and settling
1042/// again writes nothing. A verdict names the check it judged (a check routes a lesson once), or, a
1043/// record from before check ids, came after the placebo. An unclear verdict or a remaining consequence
1044/// closes nothing, as it leaves an ask pending.
1045fn closes(r: &Outcome, d: &Outcome) -> bool {
1046    match r.kind.as_str() {
1047        NOT_CORRECTED => r.check == d.check,
1048        k if settles(k) && (r.check.is_empty() || d.check.is_empty()) => r.ms > d.ms,
1049        k if settles(k) => r.check == d.check,
1050        _ => false,
1051    }
1052}
1053
1054/// The open placebos among `mine` (one session's records), in log order: per placebo delivery
1055/// (`is_placebo`) and lesson, none of the session's placebo records `closes` it.
1056fn open_placebos<'a>(mine: &[&'a Outcome]) -> Vec<(&'a str, &'a Outcome)> {
1057    let mut closers: HashMap<&str, Vec<&Outcome>> = HashMap::new();
1058    for &o in mine.iter().filter(|o| o.channel == PLACEBO && !is_placebo(o)) {
1059        for l in &o.lessons {
1060            closers.entry(l.as_str()).or_default().push(o);
1061        }
1062    }
1063    mine.iter()
1064        .copied()
1065        .filter(|o| is_placebo(o))
1066        .flat_map(|d| d.lessons.iter().map(move |l| (l.as_str(), d)))
1067        .filter(|&(l, d)| !closers.get(l).is_some_and(|rs| rs.iter().any(|r| closes(r, d))))
1068        .collect()
1069}
1070
1071/// Sessions with asks or placebos that are idle at `now`: their newest ask or placebo and newest
1072/// episode (`last_episode`, newest episode ms per session) are at least `IDLE_MS` old. Sorted. Only
1073/// sessions with an ask still without its result or an open placebo (`open_placebos`), so `borg learn`
1074/// (under the store lock) settles what is new, not every session it ever settled: one pass over the
1075/// log.
1076pub fn idle_sessions<'a>(outcomes: &'a [Outcome], last_episode: &HashMap<String, i64>, now: i64) -> Vec<&'a str> {
1077    let mut newest: HashMap<&str, i64> = HashMap::new();
1078    let (mut asked, mut resolved) = (std::collections::HashSet::new(), std::collections::HashSet::new());
1079    // Per session, its placebo channel's records: deliveries, verdicts and settles.
1080    let mut placebos: HashMap<&str, Vec<&Outcome>> = HashMap::new();
1081    for o in outcomes {
1082        if o.channel == PLACEBO || is_placebo(o) {
1083            placebos.entry(o.session.as_str()).or_default().push(o);
1084        }
1085        if o.kind == ASKED || is_placebo(o) {
1086            let m = newest.entry(o.session.as_str()).or_insert(o.ms);
1087            *m = (*m).max(o.ms);
1088        }
1089        let into = match o.kind.as_str() {
1090            ASKED => &mut asked,
1091            _ if resolves(o) => &mut resolved,
1092            _ => continue,
1093        };
1094        into.extend(o.lessons.iter().map(|l| (o.session.as_str(), l.as_str())));
1095    }
1096    let mut open: std::collections::HashSet<&str> = asked.difference(&resolved).map(|(s, _)| *s).collect();
1097    open.extend(placebos.iter().filter(|(_, rs)| !open_placebos(rs).is_empty()).map(|(s, _)| *s));
1098    let mut idle: Vec<&str> = newest
1099        .into_iter()
1100        .filter(|&(s, ms)| open.contains(s) && ms.max(last_episode.get(s).copied().unwrap_or(i64::MIN)) <= now - IDLE_MS)
1101        .map(|(s, _)| s)
1102        .collect();
1103    idle.sort();
1104    idle
1105}
1106
1107/// Usefulness of a lesson from its asked outcomes:
1108///
1109/// w = (1 + not_corrected) / (1 + not_corrected + 2 * corrected)
1110///
1111/// The +1 is a neutral prior, so a lesson without outcomes keeps w = 1 and a single bad session
1112/// cannot zero it. A correction of the same concern right after asking is strong evidence the
1113/// question did not help (too generic, or it does not change what the drone does), while a
1114/// session without correction is weak evidence (the engineer may simply not have looked), so a
1115/// correction counts twice. w stays in (0, 1]: outcomes only demote, BM25 relevance still decides
1116/// what is on topic. One corrected session gives 1/3; one corrected and one not gives 1/2.
1117pub fn weight(not_corrected: u32, corrected: u32) -> f64 {
1118    let (n, c) = (not_corrected as f64, corrected as f64);
1119    (1.0 + n) / (1.0 + n + f64::from(CORRECTED_W) * c)
1120}
1121
1122/// The weight of every lesson that has outcomes. Each (session, lesson) counts once; corrected wins.
1123pub fn weights(outcomes: &[Outcome]) -> HashMap<String, f64> {
1124    counts(outcomes).into_iter().map(|(l, (n, c))| (l, weight(n, c))).collect()
1125}
1126
1127/// Per lesson with results: (sessions not corrected, sessions corrected). Each (session, lesson)
1128/// counts once; corrected wins. Used by `weights`.
1129pub fn counts(outcomes: &[Outcome]) -> HashMap<String, (u32, u32)> {
1130    sessions(outcomes).into_iter().map(|(l, ss)| (l.to_string(), tally(ss.values(), i64::MIN))).collect()
1131}
1132
1133/// Per lesson, per session with a result: (corrected, ms of the session's earliest result for the
1134/// lesson). Corrected wins over a later (resumed) settle. trust.rs filters these by when an engineer
1135/// joined the lesson. A veto (`vetoed`) counts as a correction here, so trust and `weight` see it too
1136/// (as heavy as a correction; only memory.rs weighs it above one).
1137pub fn sessions(outcomes: &[Outcome]) -> HashMap<&str, HashMap<&str, (bool, i64)>> {
1138    let mut out: HashMap<&str, HashMap<&str, (bool, i64)>> = HashMap::new();
1139    // A placebo's record is no result (`is_result`).
1140    for o in outcomes.iter().filter(|o| is_result(o)) {
1141        let corrected = match o.kind.as_str() {
1142            CORRECTED | VETOED => true,
1143            NOT_CORRECTED => false,
1144            _ => continue,
1145        };
1146        for l in &o.lessons {
1147            let r = out.entry(l.as_str()).or_default().entry(o.session.as_str()).or_insert((corrected, o.ms));
1148            r.0 |= corrected;
1149            r.1 = r.1.min(o.ms);
1150        }
1151    }
1152    out
1153}
1154
1155/// (sessions not corrected, sessions corrected) among `sessions` results whose earliest result is
1156/// after `since`.
1157pub fn tally<'a>(sessions: impl IntoIterator<Item = &'a (bool, i64)>, since: i64) -> (u32, u32) {
1158    sessions.into_iter().filter(|(_, ms)| *ms > since).fold((0, 0), |(n, c), (corrected, _)| match corrected {
1159        true => (n, c + 1),
1160        false => (n + 1, c),
1161    })
1162}
1163
1164#[cfg(test)]
1165mod tests {
1166    use super::*;
1167
1168    fn o(kind: &str, session: &str, lessons: &[&str], ms: i64) -> Outcome {
1169        Outcome {
1170            kind: kind.into(),
1171            session: session.into(),
1172            lessons: lessons.iter().map(|l| l.to_string()).collect(),
1173            ms,
1174            repo: "r".into(),
1175            ..Default::default()
1176        }
1177    }
1178
1179    #[test]
1180    fn missed_is_an_applied_unasked_lesson_a_later_correction_lands_on() {
1181        let graded = |ms: i64, chosen: &[&str]| Outcome {
1182            kind: GRADED.into(),
1183            session: "s".into(),
1184            lessons: vec!["A".into(), "B".into()],
1185            ms,
1186            chosen: chosen.iter().map(|x| x.to_string()).collect(),
1187            ..Default::default()
1188        };
1189        let none: Vec<String> = Vec::new();
1190        let log = vec![graded(10, &["B"])];
1191        assert_eq!(missed(&log, "s", 20, Some("A"), &none), ["A"]);
1192        assert_eq!(missed(&log, "s", 20, None, &["A".into(), "B".into()]), ["A"], "B was chosen");
1193        assert!(missed(&log, "s", 5, Some("A"), &none).is_empty(), "a correction before the check");
1194        assert!(missed(&log, "t", 20, Some("A"), &none).is_empty(), "another session");
1195        assert!(missed(&log, "s", 20, Some("C"), &none).is_empty(), "never applied");
1196        let mut asked = log.clone();
1197        asked.push(o(ASKED, "s", &["A"], 15));
1198        assert!(missed(&asked, "s", 20, Some("A"), &none).is_empty(), "asked later in the session: not a miss");
1199        let mut free = log.clone();
1200        free.push(Outcome { channel: "queued".into(), ..o(ASKED, "s", &["A"], 15) });
1201        free.push(Outcome { channel: "early".into(), ..o(ASKED, "s", &["A"], 16) });
1202        assert_eq!(missed(&free, "s", 20, Some("A"), &none), ["A"], "handed over free, never asked: still a miss");
1203        let mut done = log.clone();
1204        done.push(o(MISSED, "s", &["A"], 18));
1205        assert!(missed(&done, "s", 20, Some("A"), &none).is_empty(), "recorded once");
1206    }
1207
1208    #[test]
1209    fn weight_formula() {
1210        assert_eq!(weight(0, 0), 1.0);
1211        assert_eq!(weight(5, 0), 1.0);
1212        assert!((weight(0, 1) - 1.0 / 3.0).abs() < 1e-12);
1213        assert_eq!(weight(1, 1), 0.5);
1214        assert!(weight(0, 3) < weight(0, 1));
1215    }
1216
1217    #[test]
1218    fn weights_count_each_session_once_and_corrected_wins() {
1219        let all = vec![
1220            o(ASKED, "s1", &["A", "B"], 10),
1221            o(CORRECTED, "s1", &["A"], 20),
1222            o(CORRECTED, "s1", &["A"], 30),     // second correction in the same session: still one
1223            o(NOT_CORRECTED, "s1", &["A"], 40), // resumed session settled later: corrected wins
1224            o(NOT_CORRECTED, "s1", &["B"], 40),
1225            o(NOT_CORRECTED, "s2", &["A"], 50),
1226        ];
1227        let w = weights(&all);
1228        assert_eq!(w["A"], weight(1, 1));
1229        assert_eq!(w["B"], 1.0);
1230        assert!(!w.contains_key("C"));
1231    }
1232
1233    #[test]
1234    fn a_session_whose_tests_go_green_after_an_ask_credits_it_once() {
1235        let mut log = vec![o(ASKED, "s", &["A", "B"], 10), o(ASKED, "t", &["A"], 10)];
1236        // Red after the ask, then green: one credit per lesson asked, dated at the pass.
1237        let got = tested(&log, "s", "fail 20\npass 30\n");
1238        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)]);
1239        // Idempotent: a re-run with the records written writes nothing.
1240        log.extend(got);
1241        assert!(tested(&log, "s", "fail 20\npass 30\n").is_empty());
1242        // Only the session's own asks: t ran no tests.
1243        assert!(tested(&log, "t", "").is_empty(), "no tests file: nothing");
1244    }
1245
1246    #[test]
1247    fn a_green_run_credits_only_after_the_ask_and_with_a_reason() {
1248        let log = vec![o(ASKED, "s", &["A"], 50)];
1249        assert!(tested(&log, "s", "fail 20\npass 30\n").is_empty(), "red and green before the ask");
1250        assert!(tested(&log, "s", "fail 20\npass 60\n").is_empty(), "the failure before the ask: green proves nothing new");
1251        assert!(tested(&log, "s", "fail 60\npass 70\nfail 80\n").is_empty(), "last run red");
1252        assert!(tested(&log, "s", "pass 60\n").is_empty(), "green alone, nothing changed");
1253        assert!(tested(&log, "s", "pass 60\npass 70 \ngarbage\n").is_empty());
1254        let early = [Outcome { channel: "early".into(), ..o(ASKED, "e", &["A"], 10) }];
1255        assert!(tested(&early, "e", "fail 20\npass 30\n").is_empty(), "a free delivery asked nothing");
1256        // Green after the drone changed its work on the lesson: a credit.
1257        let changed = [log.clone(), vec![o(CHANGED, "s", &["A"], 55)]].concat();
1258        assert_eq!(tested(&changed, "s", "pass 60\n").len(), 1);
1259        // A correction or a veto of the lesson in the session outranks a green run; an ignored question
1260        // gains nothing from the drone fixing its own failing test.
1261        for k in [CORRECTED, VETOED, IGNORED] {
1262            let worse = [log.clone(), vec![o(k, "s", &["A"], 55)]].concat();
1263            assert!(tested(&worse, "s", "fail 60\npass 70\n").is_empty(), "{k}");
1264        }
1265        // Lines out of order still find the last run; the first ask decides what is after it.
1266        let twice = [log.clone(), vec![o(ASKED, "s", &["A"], 65)]].concat();
1267        assert_eq!(tested(&twice, "s", "pass 70\nfail 60\n")[0].ms, 70);
1268    }
1269
1270    #[test]
1271    fn settle_marks_only_unresolved_asks_of_this_session() {
1272        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)];
1273        let settled = settle(&all, "s1", 99);
1274        assert_eq!(settled, vec![unjudged("s1", "B", UNJUDGED_NO_CALL), unjudged("s1", "C", UNJUDGED_NO_CALL)]);
1275        assert!(asked_before(&all, "s1", "A", 11) && !asked_before(&all, "s1", "C", 15) && !asked_before(&all, "s2", "A", 99));
1276    }
1277
1278    /// An ask's settle record, as this binary writes it (`settle_with`: with its version).
1279    fn unjudged(session: &str, lesson: &str, reason: &str) -> Outcome {
1280        Outcome { reason: reason.into(), version: env!("CARGO_PKG_VERSION").into(), ..o(NOT_CORRECTED, session, &[lesson], 99) }
1281    }
1282
1283    #[test]
1284    fn a_settled_lesson_says_why_it_had_no_verdict_and_names_its_latest_check() {
1285        let ask = |lessons: &[&str], ms: i64, check: &str| Outcome { check: check.into(), ..o(ASKED, "s", lessons, ms) };
1286        let placebo = Outcome { channel: PLACEBO.into(), ..o(CHANGED, "s", &["C"], 30) };
1287        let all = vec![ask(&["A", "B", "C"], 10, "c1"), ask(&["B"], 20, "c2"), o(IGNORED, "s", &["A"], 25), placebo];
1288        let why = |l: &str| if l == "B" { UNJUDGED_TRIES } else { UNJUDGED_SLOTS };
1289        let got = settle_with(&all, "s", 99, &why);
1290        let want = |l: &str, reason: &str, check: &str| Outcome { check: check.into(), ..unjudged("s", l, reason) };
1291        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");
1292    }
1293
1294    /// A verdict on an earlier delivery of the lesson is none for its later question: handed over free,
1295    /// judged ignored by a stop that then asks it, and the session ends after the answer, so no judge
1296    /// saw the question. A verdict after the question, or on its check, is its own.
1297    #[test]
1298    fn a_verdict_on_an_earlier_delivery_leaves_the_later_question_unjudged() {
1299        let ask = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(ASKED, "s", &["L"], ms) };
1300        let verdict = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(IGNORED, "s", &["L"], ms) };
1301        let why = |log: &[Outcome]| settle_with(log, "s", 99, &|_| UNJUDGED_NO_CALL).into_iter().map(|x| (x.reason, x.check)).collect::<Vec<_>>();
1302        let said = |reason: &str, check: &str| vec![(reason.to_string(), check.to_string())];
1303        // The stop writes its verdict on the free delivery, then the question, in the same millisecond.
1304        let free_then_asked = vec![ask("queued", 10, "cF"), verdict("queued", 20, "cF"), ask("stop", 20, "cS")];
1305        assert_eq!(why(&free_then_asked), said(UNJUDGED_NO_CALL, "cS"));
1306        let answered = [free_then_asked, vec![verdict("stop", 30, "cS")]].concat();
1307        assert_eq!(why(&answered), said(UNJUDGED_NONE, "cS"));
1308        // A lesson another check routed, asked at the stop: its verdict names the routing check.
1309        assert_eq!(why(&[ask("stop", 20, "cS"), verdict("stop", 30, "cL")]), said(UNJUDGED_NONE, "cS"));
1310        // On the question's check, though its clock stepped back.
1311        assert_eq!(why(&[ask("stop", 20, "cS"), verdict("stop", 15, "cS")]), said(UNJUDGED_NONE, "cS"));
1312    }
1313
1314    /// An older binary's live check judged a lesson's earlier free delivery after the lesson was asked
1315    /// live and before the answer (hook.rs `pending`); no judge saw the question. The session ends: the
1316    /// free verdict is not the question's, so the question settles censored (an unjudged reason), which
1317    /// the selection summary reads as its label, instead of staying open for good. A free delivery's own
1318    /// verdict still settles it as judged.
1319    #[test]
1320    fn a_free_deliverys_verdict_after_a_later_question_leaves_the_question_unjudged() {
1321        let ask = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(ASKED, "s", &["L"], ms) };
1322        let verdict = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(CHANGED, "s", &["L"], ms) };
1323        let why = |log: &[Outcome]| settle_with(log, "s", 99, &|_| UNJUDGED_TRIES).into_iter().map(|x| (x.reason, x.check)).collect::<Vec<_>>();
1324        let said = |reason: &str, check: &str| vec![(reason.to_string(), check.to_string())];
1325        let stuck = vec![ask("queued", 10, "cA"), ask("live", 20, "cB"), verdict("queued", 30, "cA")];
1326        assert_eq!(why(&stuck), said(UNJUDGED_TRIES, "cB"));
1327        let early = vec![ask("early", 10, "cA"), ask("stop", 20, "cB"), verdict("early", 30, "cA")];
1328        assert_eq!(why(&early), said(UNJUDGED_TRIES, "cB"));
1329        assert_eq!(why(&[stuck.clone(), vec![verdict("live", 40, "cB")]].concat()), said(UNJUDGED_NONE, "cB"), "the question's own verdict");
1330        assert_eq!(why(&[ask("queued", 10, "cA"), verdict("queued", 30, "cA")]), said(UNJUDGED_NONE, "cA"), "a free delivery's own");
1331
1332        // The selection summary labels the stuck question censored once the session settles.
1333        use crate::select::{
1334            Route,
1335            summary::{Label, Summary, fold},
1336        };
1337        let graded = |check: &str, ms: i64, channel: &str| Outcome {
1338            grades: vec![3],
1339            ranks: vec![0],
1340            applied: 1,
1341            channel: channel.into(),
1342            check: check.into(),
1343            ..o(GRADED, "s", &["L"], ms)
1344        };
1345        let mut log = vec![Outcome { free: vec!["L".into()], ..graded("cA", 5, "live") }, Outcome { chosen: vec!["L".into()], ..graded("cB", 15, "live") }];
1346        log.extend(stuck);
1347        log.extend(settle_with(&log, "s", 99, &|_| UNJUDGED_TRIES));
1348        let text: String = log.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1349        let s = fold(&text, Summary::default());
1350        let label = |route: Route| s.applies.iter().find(|a| a.route == route).map(|a| a.label);
1351        assert_eq!(label(Route::Ask), Some(Label::Censored), "{:?}", s.applies);
1352    }
1353
1354    /// The later delivery wins the judge (hook.rs `pending`): handed over free at cA then asked at cB, or
1355    /// asked at cA then handed over free at cB, the lesson is judged on cB alone. Once the session settles
1356    /// (a settle naming its binary), the delivery the judge never got to is censored, never left open,
1357    /// whose reason says "judged".
1358    #[test]
1359    fn a_settle_leaves_no_delivery_of_its_lesson_open() {
1360        use crate::select::{
1361            Route,
1362            summary::{Label, Summary, fold},
1363        };
1364        let graded = |check: &str, ms: i64, ask: bool| Outcome {
1365            grades: vec![2],
1366            ranks: vec![0],
1367            applied: 1,
1368            channel: "live".into(),
1369            check: check.into(),
1370            chosen: if ask { vec!["L".into()] } else { Vec::new() },
1371            free: if ask { Vec::new() } else { vec!["L".into()] },
1372            ..o(GRADED, "s", &["L"], ms)
1373        };
1374        let asked = |channel: &str, ms: i64, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(ASKED, "s", &["L"], ms) };
1375        let verdict = |channel: &str, check: &str| Outcome { channel: channel.into(), check: check.into(), ..o(CHANGED, "s", &["L"], 40) };
1376        for (first_ask, channels) in [(false, ["queued", "live"]), (true, ["live", "queued"])] {
1377            let mut log = vec![graded("cA", 5, first_ask), asked(channels[0], 10, "cA"), graded("cB", 15, !first_ask), asked(channels[1], 20, "cB")];
1378            log.push(verdict(channels[1], "cB"));
1379            let settled = settle_with(&log, "s", 99, &|_| UNJUDGED_TRIES);
1380            assert_eq!(settled.iter().map(|x| (x.reason.as_str(), x.check.as_str())).collect::<Vec<_>>(), [(UNJUDGED_NONE, "cB")]);
1381            log.extend(settled);
1382            let text: String = log.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1383            let s = fold(&text, Summary::default());
1384            let label = |route: Route| s.applies.iter().find(|a| a.route == route).map(|a| a.label);
1385            let (a, b) = if first_ask { (Route::Ask, Route::Free) } else { (Route::Free, Route::Ask) };
1386            assert_eq!((label(a), label(b)), (Some(Label::Censored), Some(Label::Changed)), "first asked {first_ask}: {:?}", s.applies);
1387        }
1388        // An older binary judged the free delivery while the question waited, and its settle (no
1389        // version) said "judged" for the question: it folds as when its hooks decided on it, the
1390        // question open, so the replay still reproduces those decisions.
1391        let mut log = vec![graded("cA", 5, false), asked("queued", 10, "cA"), graded("cB", 15, true), asked("live", 20, "cB"), verdict("queued", "cA")];
1392        log.push(Outcome { reason: UNJUDGED_NONE.into(), check: "cB".into(), ..o(NOT_CORRECTED, "s", &["L"], 99) });
1393        let text: String = log.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1394        let s = fold(&text, Summary::default());
1395        let labels: Vec<(Route, Label)> = s.applies.iter().map(|a| (a.route, a.label)).collect();
1396        assert_eq!(labels, [(Route::Free, Label::Changed), (Route::Ask, Label::Open)]);
1397    }
1398
1399    fn placebo(lessons: &[&str], check: &str, ms: i64) -> Outcome {
1400        Outcome { channel: PLACEBO.into(), check: check.into(), route: ROUTE_PLACEBO.into(), ..o(DELIVERY, "s", lessons, ms) }
1401    }
1402
1403    /// A placebo writes no `asked`, only its `delivery`: one the judge gave no verdict settles too, on the
1404    /// placebo channel (no result, and no ask's end), with its own check and reason. Delivered again
1405    /// later, the later delivery took its place in the judge's queue.
1406    #[test]
1407    fn an_unjudged_placebo_settles_on_its_own_channel() {
1408        let on = |kind: &str, lesson: &str, check: &str, ms: i64| Outcome { channel: PLACEBO.into(), check: check.into(), ..o(kind, "s", &[lesson], ms) };
1409        let log = vec![
1410            placebo(&["A", "B"], "p1", 10),
1411            on(IGNORED, "A", "p1", 15),
1412            on(UNCLEAR, "B", "p1", 15),
1413            placebo(&["C"], "p2", 20),
1414            Outcome { channel: "queued".into(), check: "c3".into(), ..o(ASKED, "s", &["C"], 30) },
1415            Outcome { route: ROUTE_DROPPED_DONE.into(), ..placebo(&["D"], "p4", 40) },
1416        ];
1417        let why = |l: &str| if l == "B" { UNJUDGED_TRIES } else { UNJUDGED_NO_CALL };
1418        let got = settle_with(&log, "s", 99, &why);
1419        let closed =
1420            |l: &str, check: &str, reason: &str| Outcome { channel: PLACEBO.into(), check: check.into(), version: String::new(), ..unjudged("s", l, reason) };
1421        let asked = Outcome { check: "c3".into(), ..unjudged("s", "C", UNJUDGED_NO_CALL) };
1422        let want = vec![asked, closed("B", "p1", UNJUDGED_TRIES), closed("C", "p2", UNJUDGED_LATER)];
1423        assert_eq!(got, want, "A has its verdict; D never reached the judge's queue");
1424        assert!(got[1..].iter().all(|x| !is_result(x) && share(x, "n1").is_none()), "no result, never shared");
1425        // Settled once: the same records close their placebos, so settling again writes nothing.
1426        let mut resumed = [log, got].concat();
1427        assert!(settle_with(&resumed, "s", 120, &why).is_empty());
1428        // Resumed: B asked, E a new placebo. B's placebo settle ended no ask's wait.
1429        resumed.extend([Outcome { channel: "stop".into(), check: "c5".into(), ..o(ASKED, "s", &["B"], 110) }, placebo(&["E"], "p6", 111)]);
1430        let again: Vec<(String, String, String)> =
1431            settle_with(&resumed, "s", 120, &why).into_iter().map(|x| (x.lessons.join(","), x.channel, x.check)).collect();
1432        assert_eq!(again, [("B".to_string(), String::new(), "c5".to_string()), ("E".to_string(), PLACEBO.to_string(), "p6".to_string())]);
1433    }
1434
1435    /// Judge v3 (0.7.5): `asked_not_arisen` settles its delivery (a question's settle says "judged", a
1436    /// placebo is closed) while staying no result and never shared; `asked_consequence_remains` leaves
1437    /// it pending as `asked_unclear` does. The selection summary labels each apart, an older
1438    /// `asked_unclear` still `Unclear`, and a pending verdict never overwrites a settling one.
1439    #[test]
1440    fn not_arisen_settles_its_delivery_and_a_remaining_consequence_leaves_it_pending() {
1441        use crate::select::{
1442            Route,
1443            summary::{Label, Summary, fold},
1444        };
1445        let ask = |l: &str, check: &str| Outcome { channel: "stop".into(), check: check.into(), ..o(ASKED, "s", &[l], 10) };
1446        let on = |kind: &str, l: &str, check: &str, channel: &str| Outcome {
1447            channel: channel.into(),
1448            check: check.into(),
1449            judge: 3,
1450            reasons: vec!["only the docs changed".into()],
1451            ..o(kind, "s", &[l], 20)
1452        };
1453        let log = vec![
1454            ask("A", "cA"),
1455            on(NOT_ARISEN, "A", "cA", "stop"),
1456            ask("B", "cB"),
1457            on(REMAINS, "B", "cB", "stop"),
1458            placebo(&["P"], "pP", 10),
1459            on(NOT_ARISEN, "P", "pP", PLACEBO),
1460            placebo(&["Q"], "pQ", 10),
1461            on(REMAINS, "Q", "pQ", PLACEBO),
1462        ];
1463        assert!(log.iter().filter(|x| x.kind == NOT_ARISEN || x.kind == REMAINS).all(|x| !is_result(x) && share(x, "n1").is_none()));
1464        assert!(settles(NOT_ARISEN) && settles(CHANGED) && settles(IGNORED) && !settles(REMAINS) && !settles(UNCLEAR));
1465        let got: Vec<(String, String, String)> =
1466            settle_with(&log, "s", 99, &|_| UNJUDGED_TRIES).into_iter().map(|x| (x.lessons.join(","), x.channel, x.reason)).collect();
1467        let row = |l: &str, channel: &str, reason: &str| (l.to_string(), channel.to_string(), reason.to_string());
1468        assert_eq!(got, [row("A", "", UNJUDGED_NONE), row("B", "", UNJUDGED_TRIES), row("Q", PLACEBO, UNJUDGED_TRIES)], "P closed by its verdict");
1469        // The reason travels on the record and reads back; an older line without it reads empty.
1470        let line = serde_json::to_string(&log[1]).unwrap();
1471        assert!(line.contains(r#""reasons":["only the docs changed"]"#), "{line}");
1472        assert_eq!(serde_json::from_str::<Outcome>(&line).unwrap(), log[1]);
1473        let old: Outcome = serde_json::from_str(r#"{"kind":"asked_unclear","session":"s","lessons":["A"],"ms":1,"repo":"r","channel":"stop"}"#).unwrap();
1474        assert!(old.reasons.is_empty() && !is_result(&old) && !settles(&old.kind));
1475
1476        // The summary: each graded apply its own label.
1477        let graded = |l: &str, check: &str, ask: bool, placebo: bool| Outcome {
1478            grades: vec![3],
1479            ranks: vec![0],
1480            applied: 1,
1481            channel: "stop".into(),
1482            check: check.into(),
1483            chosen: if ask { vec![l.into()] } else { Vec::new() },
1484            placebo: if placebo { vec![l.into()] } else { Vec::new() },
1485            psi: if placebo { 0.5 } else { 0.0 },
1486            ..o(GRADED, "s", &[l], 5)
1487        };
1488        let mut all = vec![graded("A", "cA", true, false), graded("B", "cB", true, false), graded("C", "cC", true, false)];
1489        all.push(graded("P", "pP", false, true));
1490        all.extend(log);
1491        all.extend([ask("C", "cC"), on(UNCLEAR, "C", "cC", "stop")]);
1492        // A later pending verdict does not undo a settling one; a later settling one replaces a pending one.
1493        all.extend([on(UNCLEAR, "A", "cA", "stop"), on(CHANGED, "B", "cB", "stop")]);
1494        let text: String = all.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1495        let s = fold(&text, Summary::default());
1496        let label = |l: &str| {
1497            let i = s.lessons.iter().position(|x| x == l).unwrap() as u32;
1498            s.applies.iter().find(|a| a.lesson == i).map(|a| (a.route, a.label, a.judge.is_some()))
1499        };
1500        assert_eq!(label("A"), Some((Route::Ask, Label::NotArisen, true)), "{:?}", s.applies);
1501        assert_eq!(label("B"), Some((Route::Ask, Label::Changed, true)));
1502        assert_eq!(label("C"), Some((Route::Ask, Label::Unclear, false)), "an older kind keeps its label");
1503        assert_eq!(label("P"), Some((Route::Placebo, Label::NotArisen, true)));
1504        // Before the later change, B's remaining consequence is its own pending label.
1505        let first: String = all[..all.len() - 1].iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1506        let s = fold(&first, Summary::default());
1507        let b = s.lessons.iter().position(|x| x == "B").unwrap() as u32;
1508        let a = s.applies.iter().find(|a| a.lesson == b).unwrap();
1509        assert_eq!((a.label, a.judge, a.jv), (Label::Remains, None, 3), "a pending label keeps its judge's version");
1510        assert!(a.label.pending() && !a.label.verdict() && Label::NotArisen.verdict() && !Label::NotArisen.pending());
1511        // The session-end judge is a judge level of its own; a check's verdict keeps the level it had.
1512        let end = [&all[..], &[graded("E", "cE", true, false), ask("E", "cE"), Outcome { at: AT_END.into(), ..on(CHANGED, "E", "cE", "stop") }]].concat();
1513        let text: String = end.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1514        let s = fold(&text, Summary::default());
1515        assert!(s.judges.iter().any(|j| j.starts_with("v3|")) && s.judges.iter().any(|j| j.starts_with("v3@end|")), "{:?}", s.judges);
1516    }
1517
1518    /// An open placebo keeps its session waiting to settle when its `end` hook never ran, as an open ask
1519    /// does; its settle closes it.
1520    #[test]
1521    fn idle_sessions_wait_for_open_placebos() {
1522        let only = vec![placebo(&["A"], "p1", 0)];
1523        assert_eq!(idle_sessions(&only, &HashMap::new(), IDLE_MS + 10), ["s"]);
1524        assert!(idle_sessions(&only, &HashMap::new(), IDLE_MS - 10).is_empty(), "the placebo is the session's newest activity");
1525        let settled = [only.clone(), settle(&only, "s", 5)].concat();
1526        assert!(idle_sessions(&settled, &HashMap::new(), IDLE_MS + 10).is_empty());
1527    }
1528
1529    /// The selection summary reads a placebo's settle as its censoring (select/summary.rs `settled`), so
1530    /// the judge-missingness fit (select/policy.rs `judged`) counts the placebo as not judged instead of
1531    /// leaving it out.
1532    #[test]
1533    fn the_selection_summary_censors_a_settled_placebo() {
1534        use crate::select::summary::{Label, Summary, fold};
1535        let graded = Outcome {
1536            grades: vec![1, 1],
1537            ranks: vec![0, 1],
1538            applied: 2,
1539            channel: "stop".into(),
1540            check: "p1".into(),
1541            policy: "learned".into(),
1542            placebo: vec!["A".into(), "B".into()],
1543            ..o(GRADED, "s", &["A", "B"], 5)
1544        };
1545        let mut log = vec![graded, placebo(&["A", "B"], "p1", 10), Outcome { channel: PLACEBO.into(), check: "p1".into(), ..o(IGNORED, "s", &["A"], 15) }];
1546        log.extend(settle(&log, "s", 99));
1547        let text: String = log.iter().map(|x| format!("{}\n", serde_json::to_string(x).unwrap())).collect();
1548        let s = fold(&text, Summary::default());
1549        let label = |l: &str| s.applies.iter().find(|a| s.lessons[a.lesson as usize] == l).map(|a| a.label);
1550        assert_eq!((label("A"), label("B")), (Some(Label::Ignored), Some(Label::Censored)));
1551    }
1552
1553    #[test]
1554    fn contradicted_marks_superseded_asks_and_the_other_sides_of_a_disagreement() {
1555        let mut ask = o(ASKED, "s1", &["A", "B", "C", "D"], 10);
1556        ask.groups = vec![vec!["A".into(), "B".into()]];
1557        let all = vec![ask, o(ASKED, "s1", &["E"], 30), o(CORRECTED, "s1", &["D"], 15)];
1558        let ids = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1559        // A plain merge into C: C was asked in vain.
1560        assert_eq!(contradicted(&all, "s1", 20, Some("C"), &[]), ["C"]);
1561        // A correction that sides with A in the rendered A/B disagreement: B was wrong, A was right.
1562        assert_eq!(contradicted(&all, "s1", 20, Some("A"), &[]), ["B"]);
1563        // A new lesson superseding C and E: only C was asked before it; D is already corrected.
1564        assert_eq!(contradicted(&all, "s1", 20, None, &ids(&["C", "E", "D", "Z"])), ["C"]);
1565        assert!(contradicted(&all, "s2", 20, Some("C"), &ids(&["A"])).is_empty(), "another session asked nothing");
1566        let mut vetoed = all.clone();
1567        vetoed.push(o(VETOED, "s1", &["C"], 12));
1568        assert!(contradicted(&vetoed, "s1", 20, Some("C"), &[]).is_empty(), "a vetoed lesson already has the stronger result");
1569    }
1570
1571    #[test]
1572    fn a_placebo_or_unclear_result_is_no_result_for_any_reader() {
1573        let placebo = |kind: &str| Outcome { channel: PLACEBO.into(), ..o(kind, "s", &["A"], 5) };
1574        let unclear = Outcome { channel: "stop".into(), ..o(UNCLEAR, "s", &["A"], 5) };
1575        for x in [placebo(CHANGED), placebo(IGNORED), placebo(UNCLEAR), unclear.clone()] {
1576            assert!(!is_result(&x), "{x:?}");
1577            assert!(share(&x, "n1").is_none(), "never shared: {x:?}");
1578        }
1579        assert!(is_result(&Outcome { channel: "queued".into(), ..o(CHANGED, "s", &["A"], 5) }));
1580        assert!(!SHARED_KINDS.contains(&UNCLEAR) && !SHARED_KINDS.contains(&DELIVERY));
1581        // trust's view (`sessions`): a placebo result moves nothing, whatever its kind.
1582        let all = [placebo(CORRECTED), placebo(NOT_CORRECTED), o(NOT_CORRECTED, "t", &["A"], 6)];
1583        assert_eq!(tally(sessions(&all)["A"].values(), i64::MIN), (1, 0));
1584        // The statistics count no placebo result (`append`).
1585        let d = tmp("placebo-stats");
1586        append(&d.join("outcomes.jsonl"), &placebo(CHANGED)).unwrap();
1587        append(&d.join("outcomes.jsonl"), &unclear).unwrap();
1588        append(&d.join("outcomes.jsonl"), &Outcome { channel: "stop".into(), ..o(CHANGED, "s", &["B"], 7) }).unwrap();
1589        let kinds: Vec<String> = crate::stats::events(&d).into_iter().map(|e| e.kind).collect();
1590        assert_eq!(kinds, [crate::stats::CHANGED], "{kinds:?}");
1591        let _ = std::fs::remove_dir_all(d);
1592    }
1593
1594    #[test]
1595    fn a_vetoed_lesson_is_not_settled_and_counts_as_corrected() {
1596        let all = vec![o(ASKED, "s1", &["A", "B"], 10), o(VETOED, "s1", &["A"], 20)];
1597        assert_eq!(settle(&all, "s1", 99), vec![unjudged("s1", "B", UNJUDGED_NO_CALL)]);
1598        assert_eq!(sessions(&all)["A"]["s1"], (true, 20));
1599        assert_eq!(weights(&all)["A"], weight(0, 1));
1600    }
1601
1602    #[test]
1603    fn sessions_keep_the_earliest_result_and_tally_filters_by_it() {
1604        let all =
1605            vec![o(NOT_CORRECTED, "s1", &["A"], 10), o(CORRECTED, "s2", &["A"], 20), o(NOT_CORRECTED, "s2", &["A"], 25), o(NOT_CORRECTED, "s3", &["A"], 30)];
1606        let s = sessions(&all);
1607        assert_eq!(s["A"]["s2"], (true, 20));
1608        assert_eq!(tally(s["A"].values(), i64::MIN), (2, 1));
1609        assert_eq!(tally(s["A"].values(), 20), (1, 0));
1610    }
1611
1612    #[test]
1613    fn idle_sessions_need_old_asks_and_old_episodes() {
1614        let all = vec![o(ASKED, "old", &["A"], 0), o(ASKED, "busy", &["A"], 0), o(ASKED, "fresh", &["A"], 50), o(CORRECTED, "x", &["A"], 0)];
1615        let episodes = HashMap::from([("busy".to_string(), 60)]);
1616        assert_eq!(idle_sessions(&all, &episodes, IDLE_MS + 10), ["old"]);
1617        assert_eq!(idle_sessions(&all, &episodes, IDLE_MS + 60), ["busy", "fresh", "old"]);
1618    }
1619
1620    #[test]
1621    fn idle_sessions_skip_settled_ones() {
1622        let all = vec![
1623            o(ASKED, "done", &["A", "B"], 0),
1624            o(NOT_CORRECTED, "done", &["A"], 1),
1625            o(CORRECTED, "done", &["B"], 1),
1626            o(ASKED, "vetoed", &["A"], 0),
1627            o(VETOED, "vetoed", &["A"], 1),
1628            o(ASKED, "half", &["A", "B"], 0),
1629            o(NOT_CORRECTED, "half", &["A"], 1),
1630        ];
1631        assert_eq!(idle_sessions(&all, &HashMap::new(), IDLE_MS + 10), ["half"], "every ask of the others has its result");
1632    }
1633
1634    #[test]
1635    fn regretted_blames_asks_before_the_decision_shared_or_by_target() {
1636        let mut graded = o(GRADED, "s", &["G"], 5);
1637        graded.chosen = vec![];
1638        let log = vec![graded, o(ASKED, "s", &["B", "A"], 10), o(ASKED, "s", &["C"], 30), o(ASKED, "t", &["D"], 10)];
1639        let ids = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1640        let blame = |log: &[Outcome], target: &[String]| regretted(log, "s", 20, "R1", target, 0.5, 99, "r");
1641        let got = blame(&log, &[]);
1642        let want = |l: &str, credit: f64| Outcome { cause: "R1".into(), credit, ..o(REGRETTED, "s", &[l], 99) };
1643        assert_eq!(got, vec![want("A", 0.25), want("B", 0.25)], "shared; C was asked after the decision, G never shown");
1644        assert_eq!(blame(&log, &ids(&["B", "Z"])), vec![want("B", 0.5)], "the merge target takes it all");
1645        assert_eq!(blame(&log, &ids(&["Z"])), got, "a target not asked: shared");
1646        let mut corrected = log.clone();
1647        corrected.push(o(CORRECTED, "s", &["B"], 15));
1648        assert_eq!(blame(&corrected, &[]), vec![want("A", 0.5)], "corrected outranks regretted");
1649        let mut vetoed = log.clone();
1650        vetoed.push(o(VETOED, "s", &["B"], 15));
1651        assert_eq!(blame(&vetoed, &[]), vec![want("A", 0.5)], "vetoed outranks regretted");
1652        assert!(blame(&corrected, &ids(&["B"])).is_empty(), "the target took it as a correction: nobody else is blamed");
1653        assert!(blame(&vetoed, &ids(&["B", "Z"])).is_empty(), "the target took it as a veto: nobody else is blamed");
1654        assert_eq!(blame(&corrected, &ids(&["A", "B"])), vec![want("A", 0.5)], "the uncorrected target keeps its share");
1655        let mut again = log.clone();
1656        again.extend(got.clone());
1657        assert!(blame(&again, &[]).is_empty(), "credited once per cause");
1658        let mut half = log.clone();
1659        half.push(got[0].clone());
1660        assert_eq!(blame(&half, &[]), vec![want("B", 0.25)], "a partial run completes with the same share");
1661        assert_eq!(regretted(&again, "s", 20, "R2", &[], 0.5, 99, "r").len(), 2, "another regret blames again");
1662        assert!(regretted(&log, "u", 20, "R1", &[], 0.5, 99, "r").is_empty(), "another session asked nothing");
1663        assert!(regretted(&log, "", 20, "R1", &[], 0.5, 99, "r").is_empty());
1664        assert!(regretted(&log, "s", 0, "R1", &[], 0.5, 99, "r").is_empty(), "no decision time");
1665        assert!(regretted(&log, "s", 20, "R1", &[], 0.0, 99, "r").is_empty(), "not strong");
1666        // An old line without cause and credit still reads; a regretted line round-trips.
1667        let old: Outcome = serde_json::from_str(r#"{"kind":"asked","session":"s","lessons":["A"],"ms":1,"repo":"r"}"#).unwrap();
1668        assert_eq!(old, o(ASKED, "s", &["A"], 1));
1669        assert!(!serde_json::to_string(&old).unwrap().contains("credit"));
1670        let line = serde_json::to_string(&got[0]).unwrap();
1671        assert!(line.contains(r#""cause":"R1","credit":0.25"#), "{line}");
1672        assert_eq!(serde_json::from_str::<Outcome>(&line).unwrap(), got[0]);
1673    }
1674
1675    #[test]
1676    fn a_line_from_before_propensities_reads_and_writes_back_unchanged() {
1677        let line = r#"{"kind":"asked","session":"s","lessons":["A","B"],"ms":1,"repo":"r","channel":"stop","grades":[3,1],"ranks":[0,1],"applied":2}"#;
1678        let o: Outcome = serde_json::from_str(line).unwrap();
1679        assert!(o.p.is_empty());
1680        assert_eq!(serde_json::to_string(&o).unwrap(), line);
1681        let with = Outcome { p: vec![round_p(1.0), round_p(1.0 / 3.0)], ..o };
1682        assert!(serde_json::to_string(&with).unwrap().ends_with(r#""applied":2,"p":[1.0,0.3333]}"#));
1683    }
1684
1685    #[test]
1686    fn a_graded_line_from_before_select_reads_and_writes_back_unchanged() {
1687        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]}"#;
1688        let o: Outcome = serde_json::from_str(line).unwrap();
1689        assert!(o.check.is_empty() && o.policy.is_empty() && o.free.is_empty() && o.pf.is_empty() && o.judge == 0 && !o.failed);
1690        assert!(o.nofree.is_empty() && o.tail.is_empty() && o.pt == 0.0 && o.rel.is_empty());
1691        assert_eq!(serde_json::to_string(&o).unwrap(), line);
1692        // A 0.6.0 graded line and an early delivery's from before `nofree`, `tail`, `pt` and `rel`.
1693        for line in [
1694            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}"#,
1695            r#"{"kind":"asked","session":"s","lessons":["A","B"],"ms":2,"repo":"r","channel":"early","p":[1.0,0.5],"route":"asked"}"#,
1696        ] {
1697            let o: Outcome = serde_json::from_str(line).unwrap();
1698            assert!(o.nofree.is_empty() && o.tail.is_empty() && o.pt == 0.0 && o.rel.is_empty(), "{line}");
1699            assert_eq!((o.xk, o.xs), (None, None), "{line}");
1700            assert_eq!(serde_json::to_string(&o).unwrap(), line);
1701        }
1702    }
1703
1704    #[test]
1705    fn the_selection_fields_round_trip_and_stay_local() {
1706        let g = Outcome {
1707            check: "0123456789ab".into(),
1708            policy: "learned".into(),
1709            fit: "120-ab12".into(),
1710            free: vec!["B".into()],
1711            pf: vec![0.0, 1.0, 0.0],
1712            placebo: vec!["C".into()],
1713            psi: 0.5,
1714            nofree: vec!["N9".into()],
1715            xk: Some(2),
1716            xs: Some(0),
1717            tail: vec!["T9".into()],
1718            pt: 0.125,
1719            eligible: 40,
1720            shown: 30,
1721            tokens: 12_000,
1722            fill: vec![0, 4, 7],
1723            model: "m".into(),
1724            prompt_hash: "ph".into(),
1725            harness: "claude".into(),
1726            version: "0.6.0".into(),
1727            dur_ms: 9_000,
1728            failed: true,
1729            ..o(GRADED, "s", &["A", "B", "C"], 5)
1730        };
1731        let delivered = Outcome { check: "0123456789ab".into(), route: ROUTE_DROPPED_CHARS.into(), reason: "budget".into(), ..o(ASKED, "s", &["B"], 6) };
1732        let judged = Outcome { check: "0123456789ab".into(), judge: 2, stripped: true, ..o(CHANGED, "s", &["A"], 7) };
1733        let early = Outcome { channel: "early".into(), rel: vec![0.75], ..o(ASKED, "s", &["D"], 8) };
1734        // Shareable kinds carrying every per-check field, so `share` is put to the test on each.
1735        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() };
1736        for x in [&g, &delivered, &judged, &early, &carried] {
1737            let line = serde_json::to_string(x).unwrap();
1738            assert_eq!(&serde_json::from_str::<Outcome>(&line).unwrap(), x, "round trip");
1739        }
1740        // The test's s = 0 is logged, not skipped: it is a draw, not an absent field.
1741        assert!(serde_json::to_string(&g).unwrap().contains(r#""xk":2,"xs":0"#));
1742        assert!(share(&g, "n1").is_none(), "graded stays local");
1743        for x in [&delivered, &judged, &early, &carried] {
1744            let shared = serde_json::to_string(&share(x, "n1").unwrap()).unwrap();
1745            for field in
1746                ["check", "0123456789ab", "route", "reason", "judge", "stripped", "nofree", "N9", "xk", "xs", "tail", "T9", "pt", "0.125", "rel", "0.75"]
1747            {
1748                assert!(!shared.contains(field), "{field}: {shared}");
1749            }
1750        }
1751        assert!(ROUTES.iter().all(|r| !r.is_empty() && !r.contains(' ')), "one word each");
1752    }
1753
1754    #[test]
1755    fn an_older_graded_record_is_the_fixed_rule_unless_it_shows_the_cut() {
1756        let graded = |grades: &[u8], chosen: &[&str], p: &[f64]| Outcome {
1757            lessons: (0..grades.len()).map(|i| format!("L{i:02}")).collect(),
1758            grades: grades.to_vec(),
1759            chosen: chosen.iter().map(|c| c.to_string()).collect(),
1760            p: p.to_vec(),
1761            ..o(GRADED, "s", &[], 1)
1762        };
1763        // No 3: the fixed rule hands over the 2s, then the 1s, at most CAP.
1764        let soft: Vec<u8> = [vec![1; 6], vec![2; 6]].concat();
1765        let old = graded(&soft, &[], &[0.0; 12]);
1766        assert_eq!(policy_of(&old), "fixed");
1767        let want: Vec<String> = (6..12).chain(0..4).map(|i| format!("L{i:02}")).collect();
1768        assert_eq!(free_of(&old), want);
1769        // A 3: the fixed rule asks, hands over nothing.
1770        let block = graded(&[3, 1], &["L00", "L01"], &[1.0, 1.0]);
1771        assert_eq!((policy_of(&block), free_of(&block)), ("fixed", Vec::<String>::new()));
1772        // The learned cut: a propensity between 0 and 1, or an explored check; the rest go free.
1773        let cut = graded(&[3, 1, 1, 1], &["L00", "L01"], &[1.0, 1.0, 0.1, 0.1]);
1774        assert_eq!((policy_of(&cut), free_of(&cut)), ("attention", vec!["L02".to_string(), "L03".into()]));
1775        let explored = Outcome { explore: true, ..graded(&[3, 1, 1], &["L00", "L01", "L02"], &[1.0, 1.0, 1.0]) };
1776        assert_eq!((policy_of(&explored), free_of(&explored)), ("attention", Vec::<String>::new()));
1777        // A record that names its policy is taken at its word, its free list as logged.
1778        let named = Outcome { policy: "learned".into(), free: vec!["L01".into()], ..graded(&[3, 1], &["L00"], &[1.0, 0.0]) };
1779        assert_eq!((policy_of(&named), free_of(&named)), ("learned", vec!["L01".to_string()]));
1780    }
1781
1782    fn tmp(name: &str) -> std::path::PathBuf {
1783        let d = std::env::temp_dir().join(format!("borg-outcome-{name}-{}", std::process::id()));
1784        let _ = std::fs::remove_dir_all(&d);
1785        std::fs::create_dir_all(&d).unwrap();
1786        d
1787    }
1788
1789    fn lines(path: &Path, v: &[String]) {
1790        std::fs::write(path, v.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
1791    }
1792
1793    fn changed(team: &[Outcome], lesson: &str) -> u32 {
1794        let ls = [crate::conscience::Challenge { id: lesson.into(), ..Default::default() }];
1795        crate::memory::derive(team, &ls, None)[lesson].changed
1796    }
1797
1798    #[test]
1799    fn share_redacts() {
1800        let mut a = o(ASKED, "session-raw", &["A"], 5);
1801        a.repo = "secret-repo".into();
1802        a.groups = vec![vec!["A".into(), "B".into()]];
1803        a.grades = vec![3];
1804        a.ranks = vec![0];
1805        a.p = vec![0.5];
1806        let x = share(&a, "n1").unwrap();
1807        let line = serde_json::to_string(&x).unwrap();
1808        for raw in ["session-raw", "secret-repo", "groups", "grades", "ranks", "\"id\"", "version"] {
1809            assert!(!line.contains(raw), "{raw} in {line}");
1810        }
1811        assert_eq!((x.s, x.r, x.p, x.node), (tag("session-raw"), tag("secret-repo"), vec![0.5], "n1".to_string()));
1812        assert_eq!(tag("s").len(), 32);
1813        for kind in [GRADED, "veto"] {
1814            assert!(share(&o(kind, "s", &["A"], 1), "n1").is_none(), "{kind} is not shared");
1815        }
1816        let regret = share(&Outcome { cause: "episode-raw".into(), credit: 0.25, ..o(REGRETTED, "s", &["A"], 1) }, "n1").unwrap();
1817        let line = serde_json::to_string(&regret).unwrap();
1818        assert!(!line.contains("episode-raw") && line.contains(&tag("episode-raw")) && line.contains(r#""credit":0.25"#), "{line}");
1819    }
1820
1821    #[test]
1822    fn pool_fields_stay_local() {
1823        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) };
1824        let line = serde_json::to_string(&a).unwrap();
1825        assert_eq!(serde_json::from_str::<Outcome>(&line).unwrap(), a, "round trip");
1826        let shared = serde_json::to_string(&share(&a, "n1").unwrap()).unwrap();
1827        for field in ["pool", "base", "scoped"] {
1828            assert!(line.contains(field) && !shared.contains(field), "{field}: {shared}");
1829        }
1830        assert!(!serde_json::to_string(&o(ASKED, "s", &["A"], 5)).unwrap().contains("pool"), "empty: not written");
1831    }
1832
1833    #[test]
1834    fn new_graded_fields_stay_local() {
1835        let g = Outcome {
1836            moves: vec!["hold a lock across an await".into()],
1837            whys: vec!["the send awaits under the lock".into()],
1838            xtokens: 120,
1839            line: "a2".into(),
1840            run: "async".into(),
1841            ..o(GRADED, "s", &["A"], 5)
1842        };
1843        let line = serde_json::to_string(&g).unwrap();
1844        assert_eq!(serde_json::from_str::<Outcome>(&line).unwrap(), g, "round trip");
1845        for field in ["moves", "whys", "xtokens", "\"line\"", "\"run\""] {
1846            assert!(line.contains(field), "{field}: {line}");
1847        }
1848        assert!(share(&g, "n1").is_none(), "graded stays local");
1849        let plain = serde_json::to_string(&o(GRADED, "s", &["A"], 5)).unwrap();
1850        for field in ["moves", "whys", "xtokens", "\"line\"", "\"run\""] {
1851            assert!(!plain.contains(field), "empty: not written, older lines write back unchanged: {plain}");
1852        }
1853    }
1854
1855    #[test]
1856    fn publish_is_idempotent() {
1857        let home = tmp("publish");
1858        assert_eq!(publish(&home), 0, "no outcomes, nothing to publish");
1859        let mut asked = o(ASKED, "s1", &["A"], 1);
1860        asked.p = vec![1.0];
1861        lines(&home.join("outcomes.jsonl"), &[asked, o(GRADED, "s1", &["A"], 1), o(CHANGED, "s1", &["A"], 2)].map(|x| serde_json::to_string(&x).unwrap()));
1862        assert_eq!(publish(&home), 2, "graded stays local");
1863        let first = std::fs::read_to_string(home.join(TEAM_FILE)).unwrap();
1864        assert_eq!(publish(&home), 0);
1865        assert_eq!(std::fs::read_to_string(home.join(TEAM_FILE)).unwrap(), first);
1866        assert!(first.contains(r#""p":[1.0]"#) && !first.contains("\"s1\""), "{first}");
1867        // Unchanged since the last publish: the log is not read again; grown: only the new line goes.
1868        assert_eq!(std::fs::read_to_string(home.join(PUBLISHED)).unwrap(), std::fs::metadata(home.join("outcomes.jsonl")).unwrap().len().to_string());
1869        std::fs::OpenOptions::new()
1870            .append(true)
1871            .open(home.join("outcomes.jsonl"))
1872            .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()))
1873            .unwrap();
1874        assert_eq!(publish(&home), 1);
1875        assert_eq!(publish(&home), 0);
1876        // A team file gone (a fresh mesh) is published again in full.
1877        std::fs::remove_file(home.join(TEAM_FILE)).unwrap();
1878        assert_eq!(publish(&home), 3);
1879        let _ = std::fs::remove_dir_all(home);
1880    }
1881
1882    /// A store whose local log has s1 changed L1, and whose team file holds that result as published
1883    /// by this node, a remote session's change of L1, the same remote line from another node's copy,
1884    /// and a kind this binary does not share.
1885    fn team_store(name: &str, shuffle: bool) -> std::path::PathBuf {
1886        let home = tmp(name);
1887        let mut local = o(CHANGED, "s1", &["L1"], 10);
1888        local.repo = "app".into();
1889        lines(&home.join("outcomes.jsonl"), &[serde_json::to_string(&local).unwrap()]);
1890        let remote = |kind: &str, s: &str, node: &str| {
1891            serde_json::to_string(&Shared {
1892                kind: kind.into(),
1893                s: s.into(),
1894                lessons: vec!["L1".into()],
1895                ms: 20,
1896                node: node.into(),
1897                r: tag("web"),
1898                ..Default::default()
1899            })
1900            .unwrap()
1901        };
1902        let mut team = vec![
1903            serde_json::to_string(&share(&local, "me").unwrap()).unwrap(),
1904            remote(CHANGED, "x", "n2"),
1905            remote(CHANGED, "x", "n3"),
1906            remote("hacked", "y", "n2"),
1907            remote("veto", "z", "n2"),
1908        ];
1909        if shuffle {
1910            team.reverse();
1911            team.swap(0, 2);
1912        }
1913        lines(&home.join(TEAM_FILE), &team);
1914        home
1915    }
1916
1917    #[test]
1918    fn read_team_drops_own_copies_and_keeps_remote() {
1919        let home = team_store("team", false);
1920        let team = team_view(&home.join("lessons.jsonl"), true);
1921        assert_eq!(changed(&team, "L1"), 2, "{team:?}");
1922        assert_eq!(team.iter().filter(|o| o.session == "x").count(), 1, "one remote line per (kind, session, lessons, ms)");
1923        assert!(team.iter().all(|o| o.kind != "hacked" && o.kind != "veto"), "unshared kinds, an older peer's hive verdict among them, are ignored");
1924        assert!(team.iter().all(|o| o.repo != "app"), "local repos compare as tags");
1925        let _ = std::fs::remove_dir_all(home);
1926    }
1927
1928    #[test]
1929    fn read_team_is_order_independent() {
1930        let (a, b) = (team_store("order-a", false), team_store("order-b", true));
1931        let ls = [crate::conscience::Challenge { id: "L1".into(), ..Default::default() }];
1932        let m = |h: &Path| crate::memory::derive(&team_view(&h.join("lessons.jsonl"), true), &ls, None);
1933        assert_eq!(m(&a), m(&b));
1934        let _ = std::fs::remove_dir_all(a);
1935        let _ = std::fs::remove_dir_all(b);
1936    }
1937
1938    /// A node's whole fold reaches its peers: a veto that outranks the session's change, a regret's
1939    /// credit, and a session that only graded (no tick on either node). A peer holding only the team file
1940    /// derives the same memory as the node that recorded it.
1941    #[test]
1942    fn a_peer_derives_the_same_memory_from_the_team_file() {
1943        let (a, b) = (tmp("fold-a"), tmp("fold-b"));
1944        let regret = Outcome { cause: "episode-1".into(), credit: 0.5, ..o(REGRETTED, "s2", &["L1"], 40) };
1945        let log = [
1946            o(GRADED, "s0", &["L1"], 5),
1947            o(ASKED, "s1", &["L1"], 10),
1948            o(CHANGED, "s1", &["L1"], 20),
1949            o(VETOED, "s1", &["L1"], 30),
1950            o(ASKED, "s2", &["L1"], 35),
1951            regret,
1952        ];
1953        lines(&a.join("outcomes.jsonl"), &log.map(|x| serde_json::to_string(&x).unwrap()));
1954        publish(&a);
1955        std::fs::copy(a.join(TEAM_FILE), b.join(TEAM_FILE)).unwrap();
1956        let ls = [crate::conscience::Challenge { id: "L1".into(), origin_ms: 1, ..Default::default() }];
1957        let m = |h: &Path| crate::memory::derive(&team_view(&h.join("lessons.jsonl"), true), &ls, None);
1958        let (here, there) = (m(&a), m(&b));
1959        assert_eq!((here["L1"].vetoed, here["L1"].changed, here["L1"].regretted), (1, 0, 0.5), "{here:?}");
1960        assert_eq!(here, there);
1961        let _ = std::fs::remove_dir_all(a);
1962        let _ = std::fs::remove_dir_all(b);
1963    }
1964
1965    /// The unguarded surface `SHARED_KINDS` documents, pinned until the deferred guards land: a remote
1966    /// line under one of this node's session tags is dropped here, whatever its kind, while a peer
1967    /// without that session takes it, and the stronger result wins there.
1968    #[test]
1969    fn a_remote_line_under_a_local_tag_counts_on_peers_only() {
1970        let (victim, peer) = (tmp("forged-victim"), tmp("forged-peer"));
1971        let own = o(CHANGED, "s1", &["L1"], 10);
1972        let forged = Shared { kind: CORRECTED.into(), s: tag("s1"), lessons: vec!["L1".into()], ms: 11, node: "n2".into(), ..Default::default() };
1973        let team = [serde_json::to_string(&share(&own, "me").unwrap()).unwrap(), serde_json::to_string(&forged).unwrap()];
1974        lines(&victim.join("outcomes.jsonl"), &[serde_json::to_string(&own).unwrap()]);
1975        lines(&victim.join(TEAM_FILE), &team);
1976        lines(&peer.join(TEAM_FILE), &team);
1977        let ls = [crate::conscience::Challenge { id: "L1".into(), ..Default::default() }];
1978        let m = |h: &Path| crate::memory::derive(&team_view(&h.join("lessons.jsonl"), true), &ls, None).remove("L1").unwrap();
1979        assert_eq!((m(&victim).changed, m(&victim).corrected), (1, 0), "the victim never sees the override");
1980        assert_eq!((m(&peer).changed, m(&peer).corrected), (0, 1), "a peer counts the forged correction");
1981        let _ = std::fs::remove_dir_all(victim);
1982        let _ = std::fs::remove_dir_all(peer);
1983    }
1984
1985    /// A peer's `tested` line counts for a lesson its session's shared records name, and for no other.
1986    #[test]
1987    fn a_peer_green_run_counts_only_for_lessons_its_session_was_given() {
1988        let home = tmp("tested-team");
1989        let asked = share(&o(ASKED, "p1", &["L1"], 10), "peer").unwrap();
1990        let ok = share(&o(TESTED, "p1", &["L1"], 20), "peer").unwrap();
1991        let stray = share(&o(TESTED, "p1", &["L2"], 20), "peer").unwrap();
1992        let alone = share(&o(TESTED, "p2", &["L1"], 20), "peer").unwrap();
1993        // A 0.3.0 peer's hive verdict is not shared any more, so it gives its session nothing.
1994        let verdict = Shared { kind: "verified".into(), ..share(&o(ASKED, "p3", &["L1"], 10), "peer").unwrap() };
1995        let unbacked = share(&o(TESTED, "p3", &["L1"], 20), "peer").unwrap();
1996        let all = [&asked, &ok, &stray, &alone, &verdict, &unbacked];
1997        lines(&home.join(TEAM_FILE), &all.map(|x| serde_json::to_string(x).unwrap()));
1998        let ls = ["L1", "L2"].map(|id| crate::conscience::Challenge { id: id.into(), ..Default::default() });
1999        let m = crate::memory::derive(&team_view(&home.join("lessons.jsonl"), true), &ls, None);
2000        assert_eq!((m["L1"].tested, m["L2"].tested), (1, 0), "{m:?}");
2001        let _ = std::fs::remove_dir_all(home);
2002    }
2003
2004    #[test]
2005    fn off_keeps_beliefs_local() {
2006        let home = team_store("off", false);
2007        let local = team_view(&home.join("lessons.jsonl"), false);
2008        assert_eq!(local, read(&home.join("outcomes.jsonl")));
2009        assert_eq!(changed(&local, "L1"), 1);
2010        let _ = std::fs::remove_dir_all(home);
2011    }
2012
2013    /// Several writers appending to one log at once (several drones on one store): every record
2014    /// reads back, none torn into `{A}{B}\n\n`.
2015    #[test]
2016    fn concurrent_appends_keep_every_record() {
2017        let home = tmp("concurrent");
2018        let p = home.join("outcomes.jsonl");
2019        let (writers, each) = (8, 2000);
2020        std::thread::scope(|scope| {
2021            for w in 0..writers {
2022                let p = &p;
2023                scope.spawn(move || (0..each).for_each(|i| append(p, &o(ASKED, &format!("s{w}"), &["A"], i)).unwrap()));
2024            }
2025        });
2026        assert_eq!(read(&p).len(), writers * each as usize);
2027        let _ = std::fs::remove_dir_all(home);
2028    }
2029
2030    #[test]
2031    fn append_and_read_round_trip() {
2032        let dir = std::env::temp_dir().join(format!("borg-outcome-{}", std::process::id()));
2033        let p = dir.join("outcomes.jsonl");
2034        let _ = std::fs::remove_file(&p);
2035        append(&p, &o(ASKED, "s", &["A"], 1)).unwrap();
2036        append(&p, &o(CORRECTED, "s", &["A"], 2)).unwrap();
2037        assert_eq!(read(&p), vec![o(ASKED, "s", &["A"], 1), o(CORRECTED, "s", &["A"], 2)]);
2038        let _ = std::fs::remove_dir_all(dir);
2039    }
2040}