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