Skip to main content

borg/
learn.rs

1//! The conscience's live learning loop.
2//!
3//! **Capture** (hooks, deterministic, 0 tokens): an engineer correction is a prompt that pushes
4//! back on what the drone just proposed ("no…", "double check…", "why do you…"), or a rejected
5//! tool call / plan whose rejection carries the engineer's words. Each becomes a raw *episode*:
6//! the task, the drone's proposal, the correction.
7//!
8//! **Generalise** (`borg learn`, at session end, one model call per episode): the episode becomes a
9//! lesson (question + situations → consequence) or is merged into an existing lesson that
10//! expresses the same concern — the old wording is kept in `history` and `support` grows, so the
11//! library consolidates instead of piling up near-duplicates. Each lesson lists the engineers
12//! (git user.email) whose corrections it was learned from, its area (the kind of concern, for trust per
13//! engineer × area, trust.rs) and, when the correction contradicts a lesson it was shown, which
14//! lessons it `supersedes`; all from the same model call.
15//!
16//! **Outcomes** (`borg learn`, 0 tokens): a merge into a lesson the conscience asked earlier in the
17//! same session, or a new lesson superseding one it asked, means asking did not prevent the
18//! correction; a correction siding with one side of a rendered disagreement corrects the other
19//! sides instead; see outcome.rs.
20//!
21//! **Vetoes** (`borg no`, veto.rs): an engineer's "no" is an episode of kind `veto`, asked with its own
22//! prompt (`veto::OPENING`), whose answer may also name an invariant. It is learned at the end of any
23//! session, not only its own (a terminal veto may name an ended session). A veto merged into a lesson
24//! an earlier veto made counts as `veto_repeat`; an invariant of a lesson placed in this store becomes
25//! a proposed constraint in the queen's queue (`veto::propose`), never a constraint.
26
27use std::collections::{HashMap, HashSet};
28use std::io::Write;
29use std::path::{Path, PathBuf};
30use std::process::Command;
31use std::sync::LazyLock;
32
33use regex::Regex;
34use serde::{Deserialize, Serialize};
35use serde_json::{Value, json};
36
37use crate::conscience::{self, Challenge};
38use crate::outcome;
39// After `MAX_FAILURES` failed model calls in a row `borg learn` stops (runner.rs: the model is
40// unavailable, and asking about every remaining episode would only burn time and quota).
41use crate::runner::MAX_FAILURES;
42use crate::trust;
43
44pub mod regret;
45
46static CORRECTION: LazyLock<Regex> = LazyLock::new(|| {
47    Regex::new(r"(?i)^\s*(no\b|nope|don'?t|do not|stop|wrong|that'?s not|not what|why did you|why do you|i said|instead|you should|never\b|always\b|please don'?t|double check|carefully check|check against|are you sure|hmm|but\b|just a second|still\b|can'?t we|don'?t we|isn'?t)").unwrap()
48});
49static REJECTION: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?is)want to proceed with this tool use.*?the user said:\s*(.*)").unwrap());
50/// A tool call the engineer refused without saying why: omp's approval prompt ("Tool call denied by
51/// user: bash"), omp over ACP ("Tool call rejected by user (bash)"), Claude's plain rejection.
52static DENIAL: LazyLock<Regex> = LazyLock::new(|| {
53    Regex::new(r"(?i)^\s*(tool call denied by user: |tool call rejected by user \(|the user doesn'?t want to proceed with this tool use)").unwrap()
54});
55
56/// The longest excerpt an episode keeps of a correction, a rejected tool call, and the task as the
57/// learn prompt shows it. Guard: bounds what one episode adds to the store and to its prompt (a pasted
58/// log would otherwise go in whole); a regret's excerpts share it (regret.rs `CAP`).
59pub const EXCERPT_CHARS: usize = 1500;
60/// The session's task an episode keeps (hook.rs `capture_prompt`): the prompt it started from. Guard:
61/// bounds the `.task` state file and each episode's `task` (a pasted spec would otherwise go in whole);
62/// the learn prompt shows its first `EXCERPT_CHARS`.
63pub const TASK_CHARS: usize = 3000;
64/// The end of the drone's last proposal an episode keeps (hook.rs `proposal`). Guard: bounds one
65/// episode's `agent` text.
66pub const PROPOSAL_CHARS: usize = 2000;
67
68/// A prompt that pushes back on the drone's last proposal (same heuristic as the offline miner).
69pub fn is_correction(prompt: &str) -> bool {
70    let t = prompt.trim();
71    t.len() > 3 && !t.starts_with('<') && CORRECTION.is_match(t)
72}
73
74/// The engineer's words from a rejected tool call or plan, if any.
75pub fn rejection(error: &str) -> Option<String> {
76    let said = REJECTION.captures(error)?.get(1)?.as_str();
77    let said = said.split("Note: The user").next().unwrap_or(said).trim();
78    (said.len() > 3).then(|| said.chars().take(EXCERPT_CHARS).collect())
79}
80
81/// A refusal that carries no words (see `DENIAL`): the engineer's reason is their next prompt.
82pub fn denied(error: &str) -> bool {
83    rejection(error).is_none() && DENIAL.is_match(error)
84}
85
86#[derive(Debug, Clone, Default, Serialize, Deserialize)]
87pub struct Episode {
88    pub id: String,
89    pub ms: i64,
90    pub repo: String,
91    pub session: String,
92    pub task: String,
93    pub agent: String,
94    pub rejected_tool: Option<String>,
95    pub correction: String,
96    /// Who corrected: `git config user.email` in the episode's cwd, empty if unknown.
97    #[serde(default)]
98    pub engineer: String,
99    /// Empty for a correction; `regret::KIND` for a decision a later session fixed.
100    #[serde(default, skip_serializing_if = "String::is_empty")]
101    pub kind: String,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub regret: Option<regret::Regret>,
104    /// How the engineer said it, where that is not a prompt or a rejected tool call: [`ANSWER`] for an
105    /// answer to the agent's own question (the questions and their options are the `agent` text).
106    #[serde(default, skip_serializing_if = "String::is_empty")]
107    pub via: String,
108    /// The harness whose transcript the episode was read from (`Harness::name`); empty for one the hook
109    /// captured live.
110    #[serde(default, skip_serializing_if = "String::is_empty")]
111    pub harness: String,
112    /// That harness's version as its transcript names it (Claude Code's `version`, omp's
113    /// `runtime.version`, opencode 1.x's session `version`, Codex's `cli_version`); empty where it names none.
114    #[serde(default, skip_serializing_if = "String::is_empty")]
115    pub harness_version: String,
116}
117
118/// `Episode::via` of an answer to the agent's own question, and its `why` in the usage statistics.
119pub const ANSWER: &str = "answer";
120/// `Episode::via` of a correction the engineer recorded in a collective by name (`borg correct
121/// --collective`): placed there explicitly, so `borg learn` never holds it for its repo's route
122/// ([`held`]).
123pub const CORRECT: &str = "correct";
124
125/// Two prompt episodes of one session this close together are the same correction. Method: a dedupe
126/// window; the live hook's capture time and the transcript's message time of one prompt differ by a
127/// second or two, two corrections of a session by far more. Episodes of a tool call are matched by
128/// their id and words instead ([`Known::holds`]).
129pub const SAME_MS: i64 = 5_000;
130
131/// The id of an episode read from a transcript: `<session8>-T<call>` for one about a tool call (the
132/// harness's own id for it: Claude's `tool_use_id`, omp's `toolCallId`, opencode's part id, Codex's
133/// `call_id`), else `<session8>-<ms>` as the hook names a prompt's. Content, never a position: a
134/// transcript still being written cannot shift it.
135pub fn transcript_id(session: &str, call: &str, ms: i64) -> String {
136    let s8: String = session.chars().take(8).collect();
137    if call.is_empty() { format!("{s8}-{ms}") } else { format!("{s8}-T{call}") }
138}
139
140/// A correction's words with its whitespace collapsed: the hook and a transcript may wrap or pad the
141/// same words differently.
142fn words(t: &str) -> String {
143    t.split_whitespace().collect::<Vec<_>>().join(" ")
144}
145
146/// What a store already holds, so an episode read again (the transcript sweep, session end,
147/// `borg assimilate`) is never appended twice. Read once, then grown with what is appended.
148#[derive(Debug, Default)]
149pub struct Known {
150    ids: HashSet<String>,
151    /// Per session: each episode's time, whether it was a prompt's, whether a transcript named it by its
152    /// tool call ([`from_call`]), and its words ([`words`]).
153    sessions: HashMap<String, Vec<Held>>,
154}
155
156impl Known {
157    /// The episodes of `store`'s `episodes.jsonl`.
158    pub fn read(store: &Path) -> Self {
159        let mut k = Known::default();
160        for e in read_jsonl::<Episode>(&store.join("episodes.jsonl")) {
161            k.add(&e);
162        }
163        k
164    }
165
166    /// Whether `e` is already held: an episode with its id; one of its session with the same words that no
167    /// transcript named by its call (the hook stamps capture time, a transcript message time, so their ids
168    /// differ; two calls the transcript named are two events, whatever their words); or, for a prompt's
169    /// episode, a prompt's of its session within [`SAME_MS`] (the hook and the transcript cut a prompt
170    /// alike, but an older store's wording may differ). An answer is matched by its id alone: only a
171    /// transcript records answers, and the same pick to two questions is two answers.
172    pub fn holds(&self, e: &Episode) -> bool {
173        if self.ids.contains(&e.id) {
174            return true;
175        }
176        let said = words(&e.correction);
177        let (prompt, answer) = (prompt_episode(e), e.via == ANSWER);
178        self.sessions
179            .get(&e.session)
180            .is_some_and(|seen| seen.iter().any(|h| (!answer && !h.from_call && h.words == said) || (prompt && h.prompt && (h.ms - e.ms).abs() < SAME_MS)))
181    }
182
183    /// Remember `e` as held.
184    pub fn add(&mut self, e: &Episode) {
185        self.ids.insert(e.id.clone());
186        let held = Held { ms: e.ms, prompt: prompt_episode(e), from_call: from_call(e), words: words(&e.correction) };
187        self.sessions.entry(e.session.clone()).or_default().push(held);
188    }
189}
190
191/// One held episode, as [`Known::holds`] compares it.
192#[derive(Debug)]
193struct Held {
194    ms: i64,
195    prompt: bool,
196    from_call: bool,
197    words: String,
198}
199
200/// Whether a transcript named `e` by its tool call ([`transcript_id`]'s `<session8>-T<call>`); the hook
201/// names its episodes `<session8>-<ms>`.
202fn from_call(e: &Episode) -> bool {
203    let s8: String = e.session.chars().take(8).collect();
204    e.id.strip_prefix(&s8).is_some_and(|rest| rest.starts_with("-T"))
205}
206
207/// An episode said in a prompt: a pushback or a veto, not a rejected tool call or an answer.
208fn prompt_episode(e: &Episode) -> bool {
209    e.rejected_tool.is_none() && e.via.is_empty() && e.kind != regret::KIND
210}
211
212impl AsMut<Episode> for Episode {
213    fn as_mut(&mut self) -> &mut Episode {
214        self
215    }
216}
217
218/// Appends to `store` each of `eps` it does not hold yet ([`Known`]), each counted as
219/// `record_episode_in` counts it, and returns those appended, in order. `ready` completes an episode
220/// (its repo, its engineer) just before it is appended, so one already held costs nothing. The one
221/// entry for transcript capture (the transcript sweep, `borg assimilate --apply`).
222///
223/// What the store holds is read under the lock of its `episodes.jsonl`, which every caller of this
224/// takes: a writer that read the store earlier (an assimilate that learned another collective
225/// meanwhile, a turn-end sweep of the same session) never appends an episode another one appended
226/// since.
227///
228/// # Errors
229/// When an episode cannot be appended; none after it is.
230pub fn record_new_in<T: AsMut<Episode>>(store: &Path, eps: Vec<T>, mut ready: impl FnMut(&mut T)) -> std::io::Result<Vec<T>> {
231    if eps.is_empty() {
232        return Ok(Vec::new());
233    }
234    std::fs::create_dir_all(store)?;
235    crate::live::locked(&store.join("episodes.jsonl"), || {
236        let mut known = Known::read(store);
237        let mut appended = Vec::new();
238        for mut x in eps {
239            if known.holds(x.as_mut()) {
240                continue;
241            }
242            ready(&mut x);
243            record_episode_in(store, x.as_mut())?;
244            known.add(x.as_mut());
245            appended.push(x);
246        }
247        Ok(appended)
248    })
249}
250
251/// A lesson as stored: the conscience's `Challenge` plus provenance and consolidation state.
252/// Append-only: a merge writes a new version with the same id; readers keep the latest.
253#[derive(Debug, Clone, Default, Serialize, Deserialize)]
254pub struct Lesson {
255    pub id: String,
256    pub origin_ms: i64,
257    pub repo: String,
258    pub question: String,
259    pub situations: Vec<String>,
260    pub consequence: String,
261    pub support: u32,
262    pub episodes: Vec<String>,
263    pub history: Vec<Value>,
264    pub version: u32,
265    /// Engineers whose corrections this lesson was learned from, first contributor first.
266    #[serde(default)]
267    pub engineers: Vec<String>,
268    /// When each later engineer joined (ms of their first episode merged in): trust.rs counts a
269    /// lesson's outcomes for an engineer only from then on. The first contributor is absent.
270    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
271    pub joined: std::collections::BTreeMap<String, i64>,
272    /// Kind of concern (trust.rs `AREAS`), set by the generalising model call; "other" if absent.
273    #[serde(default = "other_area")]
274    pub area: String,
275    /// Existing lessons this one replaces or contradicts; the conscience asks this one instead.
276    #[serde(default, skip_serializing_if = "Vec::is_empty")]
277    pub supersedes: Vec<String>,
278    /// "queen" for a queen answer (queen.rs), "import" for team knowledge read from a directory
279    /// (assimilate_dir.rs), kept across merges; empty for learned lessons.
280    #[serde(default, skip_serializing_if = "String::is_empty")]
281    pub source: String,
282    /// Where the lesson applies, as names (systems, repos, services: "Orion", "harbor_orion"). Empty:
283    /// wherever it matches. A scoped lesson is asked only when the drone's context names one of them
284    /// (conscience.rs `in_scope`), so a team rule for one system never reaches another.
285    #[serde(default, skip_serializing_if = "Vec::is_empty")]
286    pub scope: Vec<String>,
287    /// The outside rule or idiom this lesson replaces, and why ("upstream petri-net-design seeds a budget
288    /// with a reset arc; Orion drains instead because ..."). Lessons replace lessons via `supersedes`;
289    /// this names what is not a lesson (a vendored skill, upstream docs). Rendered with the question:
290    /// an override that does not name what it replaces loses to it (seen in an earlier eval).
291    #[serde(default, skip_serializing_if = "String::is_empty")]
292    pub overrides: String,
293    /// Source location of an imported lesson (`path:line` in the source repo); empty for learned ones.
294    #[serde(default, skip_serializing_if = "String::is_empty")]
295    pub origin: String,
296    /// Alternative phrasings of the lesson for search (facets.rs): the concept without names, the symptom,
297    /// the action, the consequence, German, the identifiers as aliases. Each is its own BM25 document
298    /// (conscience.rs `rank`); never shown to a drone. Empty for lessons learned before facets existed.
299    #[serde(default, skip_serializing_if = "Vec::is_empty")]
300    pub facets: Vec<String>,
301    /// Who should hear the lesson (reach.rs): empty for the team, `repo` for its repo only, `personal`
302    /// for a lesson in the store's local-only `personal.jsonl`, and for the tombstone that withdrew it
303    /// from `lessons.jsonl`.
304    #[serde(default, skip_serializing_if = "String::is_empty")]
305    pub reach: String,
306}
307
308fn other_area() -> String {
309    trust::OTHER.into()
310}
311
312pub fn home() -> PathBuf {
313    std::env::var("BORG_HOME").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/borg"))
314}
315
316pub(crate) fn append_jsonl<T: Serialize>(path: &Path, v: &T) -> std::io::Result<()> {
317    append_line(path, &serde_json::to_string(v)?)
318}
319
320/// Appends `line` and its newline in one write. Under O_APPEND one write lands whole; `writeln!` makes
321/// two (the record, then "\n"), so two writers at once (two drones on one store) can leave
322/// `{A}{B}\n\n`, and every reader drops both unparseable records without a word.
323pub(crate) fn append_line(path: &Path, line: &str) -> std::io::Result<()> {
324    if let Some(d) = path.parent() {
325        std::fs::create_dir_all(d)?;
326    }
327    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
328    f.write_all(format!("{line}\n").as_bytes())
329}
330
331fn read_jsonl<T: for<'de> Deserialize<'de>>(path: &Path) -> Vec<T> {
332    std::fs::read_to_string(path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
333}
334
335/// False when BORG_LEARN=off (eval drones): nothing is captured or recorded.
336pub fn learning() -> bool {
337    std::env::var("BORG_LEARN").as_deref() != Ok("off")
338}
339
340/// The engineer working in `cwd`: their git user.email, empty when unknown.
341pub fn engineer(cwd: &str) -> String {
342    if cwd.is_empty() {
343        return String::new();
344    }
345    Command::new("git")
346        .args(["-C", cwd, "config", "user.email"])
347        .stdin(std::process::Stdio::null())
348        .stderr(std::process::Stdio::null())
349        .output()
350        .ok()
351        .filter(|o| o.status.success())
352        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
353        .unwrap_or_default()
354}
355
356/// Records the hook's episode `e` in this session's store (`record_episode_locked`).
357///
358/// # Errors
359/// When the episode cannot be appended.
360pub fn record_episode(e: &Episode) -> std::io::Result<()> {
361    record_episode_locked(&home(), e)
362}
363
364/// `record_episode_in` under the store's `episodes.jsonl` lock (live.rs `locked`): a `borg move` of a
365/// repo's evidence rewrites that file under the lock, and an append landing between its read and its
366/// rename would be lost. Contended only by those moves and the captures that also lock it; uncontended,
367/// one lock taken on a path that writes anyway.
368///
369/// # Errors
370/// When the episode cannot be appended.
371pub fn record_episode_locked(store: &Path, e: &Episode) -> std::io::Result<()> {
372    std::fs::create_dir_all(store)?;
373    crate::live::locked(&store.join("episodes.jsonl"), || record_episode_in(store, e))
374}
375
376/// `record_episode` into `store` (the end-of-session job writes to the route's store).
377///
378/// # Errors
379/// When the episode cannot be appended.
380pub fn record_episode_in(store: &Path, e: &Episode) -> std::io::Result<()> {
381    append_jsonl(&store.join("episodes.jsonl"), e)?;
382    count_correction(store, e);
383    Ok(())
384}
385
386/// A correction in the usage statistics: a rejected tool call, a pushback, an answer to the agent's question
387/// (`why` [`ANSWER`], rolled up apart from the corrections, stats.rs `fold`) or a regret, with a short excerpt.
388pub fn count_correction(store: &Path, e: &Episode) {
389    // A veto counts itself (`stats::VETO`, veto.rs).
390    if e.kind == crate::veto::KIND {
391        return;
392    }
393    let snippet = crate::stats::excerpt(&e.correction, crate::stats::FEED_CHARS);
394    let (why, text) = match &e.rejected_tool {
395        _ if e.kind == regret::KIND => ("regret", snippet),
396        _ if e.via == ANSWER => (ANSWER, snippet),
397        Some(tool) => ("rejected_tool", format!("{tool}: {snippet}")),
398        None => ("pushback", snippet),
399    };
400    crate::stats::count(store, crate::stats::CORRECTION, &e.session, |ev| {
401        ev.ms = e.ms;
402        ev.engineer.clone_from(&e.engineer);
403        ev.repo.clone_from(&e.repo);
404        ev.why = why.into();
405        ev.text = text;
406        ev.source = crate::stats::source(&e.harness, &e.harness_version);
407    });
408}
409
410/// The lessons of the store `home` as this engineer has them: `lessons.jsonl` with the store's personal
411/// lessons (reach.rs `PERSONAL_FILE`) over it, a personal version winning over the team one of its id
412/// (the tombstone that withdrew it). For counts and "learned" (`learned_episodes`); `borg status`.
413pub fn store_lessons(home: &Path) -> Vec<Lesson> {
414    let mine = crate::reach::personal_lessons(home);
415    let mut all: Vec<Lesson> = lessons(&home.join("lessons.jsonl")).into_iter().filter(|l| !mine.iter().any(|m| m.id == l.id)).collect();
416    all.extend(mine);
417    all.sort_by_key(|l| l.origin_ms);
418    all
419}
420
421/// The episodes the store `home` has folded into a lesson, team or personal (tombstones included: they
422/// keep their episodes).
423pub fn learned_episodes(home: &Path) -> HashSet<String> {
424    let mine = crate::reach::personal_all(home);
425    lessons(&home.join("lessons.jsonl")).into_iter().chain(mine).flat_map(|l| l.episodes).collect()
426}
427
428/// The latest version of every lesson.
429pub fn lessons(path: &Path) -> Vec<Lesson> {
430    let mut by: HashMap<String, Lesson> = HashMap::new();
431    for l in read_jsonl::<Lesson>(path) {
432        if by.get(&l.id).is_none_or(|o| o.version <= l.version) {
433            by.insert(l.id.clone(), l);
434        }
435    }
436    let mut v: Vec<Lesson> = by.into_values().collect();
437    v.sort_by_key(|l| l.origin_ms);
438    v
439}
440
441/// The correction prompt's opening.
442const OPENING: &str = "An engineer corrected a coding agent. Decide whether the correction expresses a reusable engineering \
443lesson: a critical concern about quality, design, correctness, reuse, spec conformance or root cause that this engineer would \
444plausibly raise again about similar future work. Operational remarks (\"still working?\", \"stop\", \"push\", \"restart\") are NOT lessons.";
445
446/// Who should hear a lesson: shared by the correction and the regret prompt.
447const REACH_RULES: &str = "Then decide its reach: who should hear it. Ask: would a teammate working on the same code get this correction too?
448- personal: how this one engineer likes the agent to work with them, not a property of the code: commit message style \
449or length, AI attribution or co-author trailers, whether and when to commit, push, branch or open a PR, what to stage, \
450how to report or ask, language and tone, their own tooling habits.
451- repo: a convention of the repo it happened in that other repos do not share (its branch or deploy workflow, a tool \
452or command it mandates).
453- team: everything else: an engineering concern about the code, design, correctness or verification.";
454
455const FIELDS: &str = "If it is a lesson, write:
456- question: ONE question the agent should ask itself next time, general enough to transfer, keeping the technical substance;
457- situations: 1-3 lines, each `<action> on/in <kind of state or component> [under <condition>]`, without project/class names;
458- consequence: one line, what goes wrong or what the engineer requires instead;";
459
460/// The last field of either prompt.
461const AREA: &str = "- area: the one kind of concern: concurrency, spec-conformance, reuse-existing, architecture-boundary, verification, minimality, \
462protocol-correctness, data-source, security, dependency-version, scope, or other if none fits.";
463
464/// Merging and superseding: shared by the correction and the regret prompt.
465const MERGE_RULES: &str = "Existing lessons that may express the same concern are listed. If one of them IS the same concern (the same kind of mistake) \
466and agrees with this correction, set same_as to its id and write the merged, improved wording in question/situations/consequence. \
467Otherwise same_as is empty.
468
469If this correction contradicts or replaces a listed lesson (in the same situation it requires something different or the \
470opposite, e.g. the engineer reversed an earlier correction), list that lesson's id in supersedes; never the same_as lesson. \
471Otherwise supersedes is empty.";
472
473/// The prompt for one episode: a correction's, a veto's (veto.rs) or a regret's (regret.rs).
474fn episode_prompt(e: &Episode, listed: &[String]) -> String {
475    let existing = if listed.is_empty() { "(none)".into() } else { listed.join("\n") };
476    if e.kind == crate::veto::KIND {
477        let agent = if e.agent.trim().is_empty() { "(not available)" } else { e.agent.as_str() };
478        return format!(
479            "{}\n\n{REACH_RULES}\n\n{FIELDS}\n{AREA}\n{}\n\n{MERGE_RULES}\n\n## Task the agent had\n{}\n\n## What the agent proposed (excerpt)\n{agent}\n\n## Engineer's veto\n{}\n\n## Existing lessons\n{existing}\n",
480            crate::veto::OPENING,
481            crate::veto::INVARIANT,
482            e.task.chars().take(EXCERPT_CHARS).collect::<String>(),
483            e.correction,
484        );
485    }
486    if let Some(r) = e.regret.as_ref().filter(|_| e.kind == regret::KIND) {
487        let (head, sections) = (regret::head(r), regret::sections(r, &e.task));
488        let (reach, merge) = (regret::neutral(REACH_RULES), regret::neutral(MERGE_RULES));
489        return format!("{head}\n\n{reach}\n\n{}\n{AREA}\n\n{merge}\n\n{sections}## Existing lessons\n{existing}\n", regret::FIELDS);
490    }
491    format!(
492        "{OPENING}\n\n{REACH_RULES}\n\n{FIELDS}\n{AREA}\n\n{MERGE_RULES}\n\n## Task the agent had\n{}\n\n## What the agent proposed (excerpt)\n{}\n{}\n\n## Engineer's correction\n{}\n\n## Existing lessons\n{existing}\n",
493        e.task.chars().take(EXCERPT_CHARS).collect::<String>(),
494        e.agent,
495        if e.via == ANSWER { ANSWERED } else { e.rejected_tool.as_deref().unwrap_or("") },
496        e.correction,
497    )
498}
499
500/// Under an answer's proposal (the agent's own questions): what makes an answer a lesson.
501const ANSWERED: &str = "(The agent asked these questions; the correction below is the engineer's answer. An answer that only picks \
502what fits this one task is NOT a lesson; one that states a rule, a preference or a reason that holds beyond it is.)";
503
504fn schema() -> Value {
505    json!({"type": "object", "additionalProperties": false, "properties": {
506        "is_lesson": {"type": "boolean"}, "question": {"type": "string"},
507        "situations": {"type": "array", "items": {"type": "string"}}, "consequence": {"type": "string"},
508        "same_as": {"type": "string"}, "area": {"type": "string", "enum": trust::AREAS},
509        "supersedes": {"type": "array", "items": {"type": "string"}},
510        "reach": {"type": "string", "enum": ["team", "repo", "personal"]}},
511        "required": ["is_lesson", "question", "situations", "consequence", "same_as", "area", "supersedes", "reach"]})
512}
513
514/// `schema` plus the invariant a veto's reason may name (veto.rs).
515fn veto_schema() -> Value {
516    let mut s = schema();
517    s["properties"]["invariant"] = json!({"type": "string"});
518    if let Some(r) = s["required"].as_array_mut() {
519        r.push(json!("invariant"));
520    }
521    s
522}
523
524/// The answer schema for `prompt`: a veto's prompt (it starts with `veto::OPENING`) gets the invariant
525/// field; correction and regret calls stay as they were.
526pub fn schema_for(prompt: &str) -> Value {
527    if prompt.starts_with(crate::veto::OPENING) { veto_schema() } else { schema() }
528}
529
530/// The model call failed (quota, rate limit, not logged in, network, malformed answer): unlike a
531/// verdict of "not a lesson", the episode stays waiting and a later `borg learn` retries it.
532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
533pub struct AskFailed;
534
535/// The model's verdict on an episode that is a lesson.
536struct Answer {
537    question: String,
538    situations: Vec<String>,
539    consequence: String,
540    area: String,
541    reach: String,
542    same_as: String,
543    supersedes: Vec<String>,
544    /// A veto's invariant (veto.rs); empty for every other episode, and when the model named none.
545    invariant: String,
546}
547
548impl Answer {
549    /// `Ok(None)` not a lesson; `Err` no usable verdict.
550    fn parse(v: &Value) -> Result<Option<Answer>, AskFailed> {
551        match v["is_lesson"].as_bool() {
552            Some(true) => {}
553            Some(false) => return Ok(None),
554            None => return Err(AskFailed),
555        }
556        let strs = |k: &str| v[k].as_array().into_iter().flatten().filter_map(|x| x.as_str().map(str::to_string)).collect::<Vec<_>>();
557        let text = |k: &str| v[k].as_str().unwrap_or_default().to_string();
558        let question = v["question"].as_str().filter(|q| !q.trim().is_empty()).ok_or(AskFailed)?.to_string();
559        let reach = v["reach"].as_str().filter(|r| [crate::reach::REPO, crate::reach::PERSONAL].contains(r)).unwrap_or_default();
560        Ok(Some(Answer {
561            question,
562            situations: strs("situations"),
563            consequence: text("consequence"),
564            area: trust::area(v["area"].as_str().unwrap_or_default()).to_string(),
565            reach: reach.to_string(),
566            same_as: text("same_as"),
567            supersedes: strs("supersedes"),
568            invariant: text("invariant"),
569        }))
570    }
571}
572
573/// The lessons most like an episode that the learn prompt offers for merging (`similar`). Baseline:
574/// the count since 0.1.0, never evaluated, the reference a later value is compared against. A duplicate
575/// ranked below it is not offered, so its episode can become a second lesson instead of a merge.
576const MERGE_CANDIDATES: usize = 5;
577
578/// The library's lessons most like the episode (at most `MERGE_CANDIDATES`), offered for merging.
579fn similar<'a>(e: &Episode, library: &'a [Lesson]) -> Vec<&'a Lesson> {
580    let as_challenges: Vec<Challenge> = library
581        .iter()
582        .map(|l| Challenge {
583            id: l.id.clone(),
584            origin_ms: l.origin_ms,
585            question: format!("{} {}", l.question, l.situations.join(" ")),
586            situations: l.situations.clone(),
587            consequence: l.consequence.clone(),
588            // A superseded lesson is not offered for merging; its live successor is, in its place. A
589            // re-reversal then contradicts the successor and becomes a new lesson superseding it.
590            supersedes: l.supersedes.clone(),
591            engineers: l.engineers.clone(),
592            source: l.source.clone(),
593            ..Default::default() // similarity for merging is about meaning, not usefulness or trust
594        })
595        .collect();
596    let query = format!("{} {} {}", e.task, e.agent, e.correction);
597    conscience::select(&as_challenges, &query, MERGE_CANDIDATES).iter().filter_map(|c| library.iter().find(|l| l.id == c.id)).collect()
598}
599
600/// `old` with the episode merged in: the new wording, the old one kept in `history`.
601fn merged(old: &Lesson, e: &Episode, a: Answer, mut supersedes: Vec<String>) -> Lesson {
602    let mut history = old.history.clone();
603    history.push(json!({"question": old.question, "consequence": old.consequence, "version": old.version}));
604    let mut episodes = old.episodes.clone();
605    episodes.push(e.id.clone());
606    let (mut engineers, mut joined) = (old.engineers.clone(), old.joined.clone());
607    // Emails compare case-insensitively; an alias (collective.rs "Engineers") is stored as
608    // its raw email and mapped when read, so the store never depends on this machine's config.
609    let same = |x: &String| x.trim().to_lowercase() == e.engineer.trim().to_lowercase();
610    if !e.engineer.trim().is_empty() && !engineers.iter().any(same) {
611        engineers.push(e.engineer.clone());
612        joined.insert(e.engineer.clone(), e.ms);
613    }
614    for id in old.supersedes.iter().rev() {
615        if !supersedes.contains(id) {
616            supersedes.insert(0, id.clone());
617        }
618    }
619    Lesson {
620        question: a.question,
621        situations: a.situations,
622        consequence: a.consequence,
623        support: old.support + 1,
624        episodes,
625        history,
626        version: old.version + 1,
627        engineers,
628        joined,
629        area: a.area,
630        supersedes,
631        // New wording: the old facets describe the old wording; `borg learn` generates new ones.
632        facets: Vec::new(),
633        reach: scoped(&old.repo, crate::reach::narrower(&old.reach, &a.reach)),
634        ..old.clone()
635    }
636}
637
638/// A new lesson from the episode alone.
639fn fresh(e: &Episode, a: Answer, supersedes: Vec<String>) -> Lesson {
640    Lesson {
641        id: format!("L{}", e.id),
642        origin_ms: e.ms,
643        repo: e.repo.clone(),
644        question: a.question,
645        situations: a.situations,
646        consequence: a.consequence,
647        support: 1,
648        episodes: vec![e.id.clone()],
649        version: 1,
650        engineers: Some(e.engineer.clone()).filter(|x| !x.is_empty()).into_iter().collect(),
651        area: a.area,
652        supersedes,
653        reach: scoped(&e.repo, &a.reach),
654        ..Lesson::default()
655    }
656}
657
658/// `reach` for a lesson of `repo`: one repo's reach needs a repo to be delivered in (reach.rs
659/// `deliverable`), so a lesson of none (a `borg correct` without `--repo`) is the team's instead of
660/// heard nowhere.
661fn scoped(repo: &str, reach: &str) -> String {
662    if reach == crate::reach::REPO && repo.trim().is_empty() { String::new() } else { reach.to_string() }
663}
664
665/// Generalise one episode against the existing library (the merge targets: team and personal lessons, no
666/// tombstone): `Ok(Some)` a new lesson or a merged version of an existing one, `Ok(None)` not a lesson,
667/// `Err` no verdict. `ask` performs the model call
668/// (injectable for tests). A regret (regret.rs) gets its own prompt, the same verdict.
669///
670/// # Errors
671/// `AskFailed` when the model gave no usable verdict.
672pub fn generalise(e: &Episode, library: &[Lesson], ask: &dyn Fn(&str) -> Option<Value>) -> Result<Option<Lesson>, AskFailed> {
673    generalise_with(e, library, ask).map(|o| o.map(|(l, _)| l))
674}
675
676/// `generalise`, with the invariant a veto's answer named (empty otherwise).
677///
678/// # Errors
679/// `AskFailed` when the model gave no usable verdict.
680pub fn generalise_with(e: &Episode, library: &[Lesson], ask: &dyn Fn(&str) -> Option<Value>) -> Result<Option<(Lesson, String)>, AskFailed> {
681    let similar = similar(e, library);
682    let listed: Vec<String> = similar.iter().map(|l| format!("[{}] {} -> {}", l.id, l.question, l.consequence)).collect();
683    let Some(a) = Answer::parse(&ask(&episode_prompt(e, &listed)).ok_or(AskFailed)?)? else { return Ok(None) };
684    let same_as = similar.iter().find(|l| a.same_as == l.id);
685    // Only lessons the model was shown can be superseded, and never the one it merges into.
686    let supersedes: Vec<String> =
687        a.supersedes.iter().filter(|id| similar.iter().any(|l| &l.id == *id) && same_as.is_none_or(|m| &m.id != *id)).cloned().collect();
688    let invariant = a.invariant.trim().to_string();
689    Ok(Some((
690        match same_as {
691            Some(old) => merged(old, e, a, supersedes),
692            None => fresh(e, a, supersedes),
693        },
694        invariant,
695    )))
696}
697
698/// One structured call to the drone's model (runner.rs picks claude, omp or opencode).
699pub fn ask_claude(prompt: &str) -> Option<Value> {
700    ask_model(prompt, &schema_for(prompt)).map(|(v, _)| v)
701}
702
703/// The model call behind `ask_claude`, for any JSON schema: the structured answer and its cost in USD
704/// (None when the CLI reported none). `BORG_LEARN_MODEL` picks the model, `runner::choose` the CLI.
705pub fn ask_model(prompt: &str, schema: &Value) -> Option<(Value, Option<f64>)> {
706    let started = std::time::Instant::now();
707    let answer = call_model(prompt, schema);
708    crate::stats::count(&home(), crate::stats::MODEL_CALL, "", |ev| {
709        ev.why = crate::stats::purpose().into();
710        ev.usd = answer.as_ref().and_then(|(_, c)| *c).unwrap_or(0.0);
711        ev.dur_ms = started.elapsed().as_millis() as u64;
712        if answer.is_none() {
713            ev.text = "no answer".into();
714        }
715    });
716    answer
717}
718
719fn call_model(prompt: &str, schema: &Value) -> Option<(Value, Option<f64>)> {
720    let candidates = crate::runner::choose(std::env::var("BORG_LEARN_MODEL").ok().as_deref());
721    crate::runner::structured(&candidates, prompt, schema, learn_timeout())
722}
723
724/// How long one learn-side model call may take (`BORG_LEARN_TIMEOUT_S`, default 300 s): it runs in
725/// the background, but a hung runner must not keep `borg learn` alive forever.
726fn learn_timeout() -> std::time::Duration {
727    std::time::Duration::from_secs(std::env::var("BORG_LEARN_TIMEOUT_S").ok().and_then(|v| v.parse().ok()).unwrap_or(300))
728}
729
730pub fn now_ms() -> i64 {
731    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
732}
733
734/// `borg learn [--session ID]`: generalise every episode not yet folded into a lesson.
735/// `--session` is given when that session ended: its asked lessons and the placebos the judge never
736/// reached are then settled. Any run also settles sessions idle for a day, so a missing `end` hook does
737/// not bias the outcomes.
738/// Returns (new lessons, merges, episodes still waiting because the model gave no verdict).
739pub fn learn_pending(session: Option<&str>, ask: &dyn Fn(&str) -> Option<Value>) -> (usize, usize, usize) {
740    learn_in(&home(), session, ask, learning(), now_ms())
741}
742
743/// `learn_pending` on the store in `home`. With `track`, outcomes of asked lessons are recorded
744/// (outcome.rs): a merge into a lesson asked earlier in the episode's session, and a lesson asked
745/// earlier that the new one supersedes, are `asked_then_corrected` (`outcome::contradicted`); at the end of `session`, and in every session idle for
746/// `outcome::IDLE_MS` at `now`, the other asked lessons are `asked_not_corrected`. So any run
747/// settles, not only the `end` hook's; a session it skipped episodes of is not settled as idle.
748/// Only a "not a lesson" verdict is recorded as skipped: an episode whose model call failed stays
749/// waiting (and its session unsettled) for the next run, and after `MAX_FAILURES` failures in a row
750/// the run stops asking. Returns (new lessons, merges, episodes still waiting for a verdict).
751pub fn learn_in(home: &Path, session: Option<&str>, ask: &dyn Fn(&str) -> Option<Value>, track: bool, now: i64) -> (usize, usize, usize) {
752    learn_in_reporting(home, session, ask, track, now, &mut |_| {})
753}
754
755/// A progress line on stderr: `[12/104 · 18 s · ~28 min left] new lesson L…: <question>`.
756pub fn print_step(st: Step) {
757    let left = (st.total - st.done) as f64 * st.secs / 60.0;
758    let mut v: String = st.verdict.chars().take(110).collect();
759    if v.len() < st.verdict.len() {
760        v.push('…');
761    }
762    eprintln!("[{}/{} · {:.0} s · ~{:.0} min left] {v}", st.done, st.total, st.secs, left);
763}
764
765/// One model verdict during a learn run, for a progress line: the episode's place among those this
766/// run asks about (`done` of `total`), and what came of it.
767pub struct Step<'a> {
768    pub done: usize,
769    pub total: usize,
770    pub verdict: &'a str,
771    pub secs: f64,
772}
773
774/// Whether a veto's lesson, placed as `placed`, proposes its `invariant` as a constraint: only a team
775/// lesson; a personal one never does, a preference being no invariant.
776fn proposes(placed: &crate::reach::Placed, invariant: &str) -> bool {
777    matches!(placed, crate::reach::Placed::Here(_)) && !invariant.trim().is_empty()
778}
779
780/// False when BORG_REGRET_CREDIT=off: a regret no longer counts against the lessons asked before the
781/// decision (`credit_regrets`).
782pub fn regret_credit() -> bool {
783    std::env::var("BORG_REGRET_CREDIT").as_deref() != Ok("off")
784}
785
786/// Crediting a session's own green test runs on (`outcome::tested`): learning is, and BORG_TEST_CREDIT is
787/// not `off` (an eval's frozen arm).
788pub fn test_credit() -> bool {
789    learning() && std::env::var("BORG_TEST_CREDIT").as_deref() != Ok("off")
790}
791
792/// Each regret episode generalised into a lesson of this store (`library`, as stored: a lesson placed in
793/// a private store is not in it) blames the lessons asked in its deciding session before the decision
794/// (`outcome::regretted`). Runs over every such episode on every run, so regrets learned before this
795/// existed are credited once too; the (cause, lesson) key keeps it idempotent. A regret the model judged
796/// "not a lesson", one still waiting, and one without `decision_ms` credit nothing. For a review regret
797/// the deciding session is the episode's own: a lesson `contradicted` already marked corrected there is
798/// not blamed twice.
799///
800/// Indexed once per run, so a run costs one pass over the log and the library plus each deciding
801/// session's own records: `regretted` reads only the deciding session's records, and a regret's credits
802/// carry that session too.
803///
804/// A regret is also a correction of the deciding session's work: the lesson it was folded into, and the
805/// lessons that one supersedes, if a graded check of that session found them applying before the
806/// decision and the session never asked them, were questions needed and not asked
807/// (`applied_then_corrected`, `outcome::missed`, at the decision's time and with the regret as `cause`),
808/// as for a correction merged into a lesson. These misses are recorded with `credit` off too: they blame
809/// no lesson asked.
810fn credit_regrets(regrets: &[Episode], library: &[Lesson], outcomes: &mut Vec<outcome::Outcome>, path: &Path, credit: bool) {
811    let mut holder: HashMap<&str, &Lesson> = HashMap::new();
812    for l in library {
813        for id in &l.episodes {
814            holder.entry(id.as_str()).or_insert(l);
815        }
816    }
817    let deciding: HashSet<&str> = regrets.iter().filter_map(|e| e.regret.as_ref()).map(|r| r.decision_session.as_str()).collect();
818    let mut by_session: HashMap<String, Vec<outcome::Outcome>> = HashMap::new();
819    for o in outcomes.iter().filter(|o| deciding.contains(o.session.as_str())) {
820        by_session.entry(o.session.clone()).or_default().push(o.clone());
821    }
822    for e in regrets {
823        let Some(r) = &e.regret else { continue };
824        let Some(holder) = holder.get(e.id.as_str()) else { continue };
825        let target: Vec<String> = std::iter::once(holder.id.clone()).chain(holder.supersedes.iter().cloned()).collect();
826        let records = by_session.entry(r.decision_session.clone()).or_default();
827        let blamed = match credit {
828            true => outcome::regretted(records, &r.decision_session, r.decision_ms, &e.id, &target, regret::strength(r), e.ms, &e.repo),
829            false => Vec::new(),
830        };
831        let missed = match r.decision_ms > 0 && !r.decision_session.is_empty() {
832            true => outcome::missed(records, &r.decision_session, r.decision_ms, Some(&holder.id), &holder.supersedes),
833            false => Vec::new(),
834        };
835        let missed = missed.into_iter().map(|l| outcome::Outcome {
836            kind: outcome::MISSED.into(),
837            session: r.decision_session.clone(),
838            lessons: vec![l],
839            ms: r.decision_ms,
840            repo: e.repo.clone(),
841            cause: e.id.clone(),
842            ..Default::default()
843        });
844        for o in blamed.into_iter().chain(missed.collect::<Vec<_>>()) {
845            let _ = outcome::append(path, &o);
846            records.push(o.clone());
847            outcomes.push(o);
848        }
849    }
850}
851
852/// Whether the session whose state file is `ctx` is still open at `now`: the file changed within
853/// `outcome::IDLE_MS` (every prompt and touch appends to it). No file: not open.
854fn open(ctx: &Path, now: i64) -> bool {
855    let ms = std::fs::metadata(ctx).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as i64);
856    ms.is_some_and(|ms| ms > now - outcome::IDLE_MS)
857}
858
859/// The sessions besides `session` whose waiting episodes (not in `done` nor `skipped`) a run with
860/// `session` learns too: quiet ones, whose newest episode is `outcome::IDLE_MS` old at `now` and which
861/// `is_open` (its state file, `open`) says are not open. A session left open never sends its end, and
862/// the transcript sweep (sweep.rs `idle`) adds its last corrections after it went quiet. Each such
863/// session costs one stat.
864fn quiet(
865    episodes: &[Episode],
866    session: Option<&str>,
867    done: &HashSet<String>,
868    skipped: &HashSet<String>,
869    now: i64,
870    is_open: impl Fn(&str) -> bool,
871) -> HashSet<String> {
872    let Some(session) = session else { return HashSet::new() };
873    let mut newest: HashMap<&str, i64> = HashMap::new();
874    for e in episodes {
875        let n = newest.entry(e.session.as_str()).or_insert(e.ms);
876        *n = (*n).max(e.ms);
877    }
878    let waiting: HashSet<&str> =
879        episodes.iter().filter(|e| e.session != session && !done.contains(&e.id) && !skipped.contains(&e.id)).map(|e| e.session.as_str()).collect();
880    waiting.into_iter().filter(|s| newest[s] <= now - outcome::IDLE_MS && !is_open(s)).map(str::to_string).collect()
881}
882
883/// Episode kinds the removed hive made (a group's reflection, a rework), skipped where an older store has them.
884const RETIRED: [&str; 2] = ["group", "rework"];
885
886/// Where the episodes of a store route now, one lookup per repo (collective.rs `route_repo`).
887struct Routes<'a> {
888    cfg: Option<&'a crate::collective::Config>,
889    home: PathBuf,
890    base: PathBuf,
891    by_repo: HashMap<String, Option<crate::collective::Route>>,
892}
893
894impl<'a> Routes<'a> {
895    /// For the store `home` under `cfg`. Holds nothing without a config, nor in a store that is no
896    /// collective's (the root store, a test's or an eval's directory).
897    fn new(cfg: Option<&'a crate::collective::Config>, home: &Path) -> Self {
898        let cfg = cfg.filter(|c| crate::collective::is_store(c, home));
899        Routes { cfg, home: home.to_path_buf(), base: crate::collective::root_of(home), by_repo: HashMap::new() }
900    }
901
902    /// Where `e` belongs when that is not this store: its repo routes to another collective's store, or
903    /// off, under the current config. `None`: it belongs here, or its route is unknown (never guessed),
904    /// or the engineer placed it here by name ([`CORRECT`]).
905    fn elsewhere(&mut self, e: &Episode) -> Option<crate::collective::Route> {
906        let cfg = self.cfg?;
907        if e.via == CORRECT {
908            return None;
909        }
910        let (base, home) = (&self.base, &self.home);
911        let r = self.by_repo.entry(e.repo.clone()).or_insert_with(|| crate::collective::route_repo(cfg, &e.repo, base)).clone()?;
912        match &r {
913            crate::collective::Route::Collective { home: h, .. } if h == home => None,
914            _ => Some(r),
915        }
916    }
917}
918
919/// The waiting episodes of one repo that `borg learn` holds in a store because the repo routes elsewhere
920/// now (`held`).
921#[derive(Debug, Clone, PartialEq)]
922pub struct HeldRepo {
923    pub repo: String,
924    /// Where the repo routes now: another collective (its name and store) or `Off`.
925    pub route: crate::collective::Route,
926    /// The held episodes' ids, in log order.
927    pub episodes: Vec<String>,
928}
929
930/// The episodes of the store `home` that `borg learn` holds under `cfg`, per repo: not learned, not
931/// skipped, not recorded here by name ([`CORRECT`]), of a repo that routes to another store (or off)
932/// now. They wait, never learned here, until they are moved where they belong (`borg move <repo>`).
933/// Reads this store and the config only.
934pub fn held(home: &Path, cfg: Option<&crate::collective::Config>) -> Vec<HeldRepo> {
935    let mut routes = Routes::new(cfg, home);
936    if routes.cfg.is_none() {
937        return Vec::new();
938    }
939    let done = learned_episodes(home);
940    let skipped: HashSet<String> = std::fs::read_to_string(home.join("episodes-not-lessons.txt")).unwrap_or_default().lines().map(str::to_string).collect();
941    let mut out: Vec<HeldRepo> = Vec::new();
942    for e in read_jsonl::<Episode>(&home.join("episodes.jsonl")) {
943        if done.contains(&e.id) || skipped.contains(&e.id) || RETIRED.contains(&e.kind.as_str()) {
944            continue;
945        }
946        let Some(route) = routes.elsewhere(&e) else { continue };
947        match out.iter_mut().find(|h| h.repo == e.repo) {
948            Some(h) if !h.episodes.contains(&e.id) => h.episodes.push(e.id),
949            Some(_) => {}
950            None => out.push(HeldRepo { repo: e.repo, route, episodes: vec![e.id] }),
951        }
952    }
953    out
954}
955
956/// `learn_in`, calling `report` after every model call (the CLI prints it; the hooks pass a no-op).
957///
958/// One run per store at a time (an exclusive lock on `lessons.jsonl.lock`): session-end runs of several
959/// drones share the veto episodes and the regret credits, and two runs reading the store before either
960/// writes would learn a veto twice and count its credits twice. A waiting run then reads what the first
961/// one wrote and has nothing left to do for them.
962pub fn learn_in_reporting(
963    home: &Path,
964    session: Option<&str>,
965    ask: &dyn Fn(&str) -> Option<Value>,
966    track: bool,
967    now: i64,
968    report: &mut dyn FnMut(Step),
969) -> (usize, usize, usize) {
970    let cfg = crate::collective::load().ok().flatten();
971    learn_in_config(home, cfg.as_ref(), session, ask, track, now, report)
972}
973
974/// `learn_in_reporting` under an explicit collectives config: an episode whose repo routes to another
975/// store under `cfg` is held, never learned here ([`held`]).
976pub fn learn_in_config(
977    home: &Path,
978    cfg: Option<&crate::collective::Config>,
979    session: Option<&str>,
980    ask: &dyn Fn(&str) -> Option<Value>,
981    track: bool,
982    now: i64,
983    report: &mut dyn FnMut(Step),
984) -> (usize, usize, usize) {
985    crate::live::locked(&home.join("lessons.jsonl"), || learn_unlocked(home, cfg, session, ask, track, now, report))
986}
987
988fn learn_unlocked(
989    home: &Path,
990    cfg: Option<&crate::collective::Config>,
991    session: Option<&str>,
992    ask: &dyn Fn(&str) -> Option<Value>,
993    track: bool,
994    now: i64,
995    report: &mut dyn FnMut(Step),
996) -> (usize, usize, usize) {
997    let (ep_path, lessons_path) = (home.join("episodes.jsonl"), home.join("lessons.jsonl"));
998    let outcomes_path = outcome::path_beside(&lessons_path);
999    let mut outcomes = if track { outcome::read(&outcomes_path) } else { Vec::new() };
1000    // The merge targets: this engineer's personal lessons (reach.rs) and the team's, no tombstone. Done:
1001    // every episode either file holds, tombstones included.
1002    let team = lessons(&lessons_path);
1003    let personal_lines = crate::reach::personal_all(home);
1004    let done: HashSet<String> = team.iter().chain(&personal_lines).flat_map(|l| l.episodes.clone()).collect();
1005    // A lesson `borg move` took elsewhere is no merge target here (reach.rs `MOVED`).
1006    let personal: Vec<Lesson> = personal_lines.into_iter().filter(|l| l.question != crate::reach::MOVED).collect();
1007    let mut personal_ids: HashSet<String> = personal.iter().map(|l| l.id.clone()).collect();
1008    let mut library: Vec<Lesson> = team.into_iter().filter(|l| l.reach != crate::reach::PERSONAL && !personal_ids.contains(&l.id)).chain(personal).collect();
1009    let skipped_path = home.join("episodes-not-lessons.txt");
1010    let mut skipped: HashSet<String> = std::fs::read_to_string(&skipped_path).unwrap_or_default().lines().map(str::to_string).collect();
1011    let (mut new, mut merged, mut failed, mut failures_in_row) = (0, 0, 0, 0);
1012    // Newest episode per session, and sessions with episodes this run left pending (--session).
1013    let mut last_episode: std::collections::HashMap<String, i64> = std::collections::HashMap::new();
1014    let mut pending: std::collections::HashSet<String> = std::collections::HashSet::new();
1015    // `RETIRED` kinds an older store holds are never learned.
1016    let episodes: Vec<Episode> = read_jsonl::<Episode>(&ep_path).into_iter().filter(|e| !RETIRED.contains(&e.kind.as_str())).collect();
1017    // Held (`held`): an episode of a repo that routes elsewhere now waits, unlearned and unmarked, and
1018    // keeps no session pending. Treated as settled for this run only, never written as skipped.
1019    let mut routes = Routes::new(cfg, home);
1020    let held_here: HashSet<String> =
1021        episodes.iter().filter(|e| !done.contains(&e.id) && !skipped.contains(&e.id) && routes.elsewhere(e).is_some()).map(|e| e.id.clone()).collect();
1022    skipped.extend(held_here);
1023    let regrets: Vec<Episode> = episodes.iter().filter(|e| e.kind == regret::KIND && e.regret.is_some()).cloned().collect();
1024    let state = std::env::var_os("BORG_STATE").map_or_else(|| home.join("state"), std::path::PathBuf::from);
1025    let ctx = |s: &str| state.join(format!("{}.ctx", crate::notes::safe(s)));
1026    // A veto is learned at the end of any session (veto.rs): a terminal veto may name one already ended.
1027    // So is a quiet session's episode (`quiet`): one that never sends its end would keep it waiting.
1028    let quiet = quiet(&episodes, session, &done, &skipped, now, |s| open(&ctx(s), now));
1029    let mine = |e: &Episode| session.is_none_or(|s| s == e.session) || e.kind == crate::veto::KIND || quiet.contains(&e.session);
1030    let vetoes: HashSet<String> = episodes.iter().filter(|e| e.kind == crate::veto::KIND).map(|e| e.id.clone()).collect();
1031    let total = episodes.iter().filter(|e| !done.contains(&e.id) && !skipped.contains(&e.id) && mine(e)).count();
1032    let mut asked = 0;
1033    for e in episodes {
1034        let last = last_episode.entry(e.session.clone()).or_insert(e.ms);
1035        *last = (*last).max(e.ms);
1036        if done.contains(&e.id) || skipped.contains(&e.id) {
1037            continue;
1038        }
1039        if !mine(&e) {
1040            pending.insert(e.session.clone());
1041            continue;
1042        }
1043        if failures_in_row >= MAX_FAILURES {
1044            failed += 1;
1045            pending.insert(e.session.clone());
1046            continue;
1047        }
1048        let started = std::time::Instant::now();
1049        let verdict = generalise_with(&e, &library, ask);
1050        asked += 1;
1051        let what = match &verdict {
1052            Err(AskFailed) => "no answer from the model, left pending".to_string(),
1053            Ok(Some((l, _))) if l.version > 1 => format!("merged into {}: {}", l.id, l.question),
1054            Ok(Some((l, _))) => format!("new lesson {}: {}", l.id, l.question),
1055            Ok(None) => "not a lesson".to_string(),
1056        };
1057        report(Step { done: asked, total, verdict: &what, secs: started.elapsed().as_secs_f64() });
1058        failures_in_row = if verdict.is_err() { failures_in_row + 1 } else { 0 };
1059        match verdict {
1060            Err(AskFailed) => {
1061                failed += 1;
1062                pending.insert(e.session.clone());
1063            }
1064            Ok(Some((l, invariant))) => {
1065                // A personal lesson stays in this store, for this engineer only (reach.rs `place`).
1066                let team = library.iter().find(|x| x.id == l.id && !personal_ids.contains(&x.id));
1067                let placed = crate::reach::place(&l, &e, personal_ids.contains(&l.id), team);
1068                if placed.lesson().version > 1 {
1069                    merged += 1
1070                } else {
1071                    new += 1
1072                }
1073                // Where it came from, for the feed: a review finding, a later fix, or a correction.
1074                let source = match &e.regret {
1075                    Some(r) if regret::is_review(r) => "review",
1076                    Some(_) => "regret",
1077                    None if e.kind == crate::veto::KIND => "veto",
1078                    None => "session",
1079                };
1080                let _ = crate::reach::write(home, &placed);
1081                let written = placed.lesson();
1082                let kind = if written.version > 1 { crate::stats::LESSON_MERGED } else { crate::stats::LESSON_NEW };
1083                let why = if matches!(placed, crate::reach::Placed::Personal { .. }) { "personal" } else { source };
1084                crate::stats::count(home, kind, &e.session, |ev| {
1085                    ev.engineer = e.engineer.clone();
1086                    ev.repo = e.repo.clone();
1087                    ev.lessons = vec![written.id.clone()];
1088                    ev.why = why.into();
1089                });
1090                if e.kind == crate::veto::KIND {
1091                    // The same "no" said twice: merged into a lesson an earlier veto made.
1092                    let earlier = library.iter().find(|x| x.id == l.id);
1093                    if l.version > 1 && earlier.is_some_and(|o| o.episodes.iter().any(|id| id != &e.id && vetoes.contains(id))) {
1094                        // Dated when the engineer said it, the week of its own `veto`, not when it was
1095                        // learned: a weekly share of repeated vetoes pairs counts of the same no's.
1096                        crate::stats::count(home, crate::stats::VETO_REPEAT, &e.session, |ev| {
1097                            ev.ms = if e.ms > 0 { e.ms } else { ev.ms };
1098                            ev.engineer = e.engineer.clone();
1099                            ev.repo = e.repo.clone();
1100                            ev.lessons = vec![l.id.clone()];
1101                            ev.text = crate::stats::excerpt(&e.correction, crate::stats::FEED_CHARS);
1102                        });
1103                    }
1104                    if proposes(&placed, &invariant) {
1105                        let _ = crate::veto::propose(home, &l, &invariant, &e, now);
1106                    }
1107                }
1108                let target = (l.version > 1).then_some(l.id.as_str());
1109                // A veto credited the lessons shown before it already (veto.rs): it never doubles as a
1110                // correction, nor as a missed question (`applied_then_corrected`).
1111                let track_results = track && e.kind != crate::veto::KIND;
1112                let contradicted = match track_results {
1113                    true => outcome::contradicted(&outcomes, &e.session, e.ms, target, &l.supersedes),
1114                    false => Vec::new(),
1115                };
1116                for id in contradicted {
1117                    let o = outcome::Outcome {
1118                        kind: outcome::CORRECTED.into(),
1119                        session: e.session.clone(),
1120                        lessons: vec![id],
1121                        ms: e.ms,
1122                        repo: e.repo.clone(),
1123                        ..Default::default()
1124                    };
1125                    let _ = outcome::append(&outcomes_path, &o);
1126                    outcomes.push(o);
1127                }
1128                let missed = match track_results {
1129                    true => outcome::missed(&outcomes, &e.session, e.ms, target, &l.supersedes),
1130                    false => Vec::new(),
1131                };
1132                for id in missed {
1133                    let o = outcome::Outcome {
1134                        kind: outcome::MISSED.into(),
1135                        session: e.session.clone(),
1136                        lessons: vec![id],
1137                        ms: e.ms,
1138                        repo: e.repo.clone(),
1139                        ..Default::default()
1140                    };
1141                    let _ = outcome::append(&outcomes_path, &o);
1142                    outcomes.push(o);
1143                }
1144                let written = placed.lesson().clone();
1145                if matches!(placed, crate::reach::Placed::Personal { .. }) {
1146                    personal_ids.insert(written.id.clone());
1147                }
1148                library.retain(|x| x.id != written.id);
1149                library.push(written);
1150            }
1151            Ok(None) => {
1152                let _ = append_line(&skipped_path, &e.id);
1153                crate::stats::count(home, crate::stats::NOT_A_LESSON, &e.session, |ev| ev.engineer = e.engineer.clone());
1154            }
1155        }
1156    }
1157    if track {
1158        credit_regrets(&regrets, &store_lessons(home), &mut outcomes, &outcomes_path, regret_credit());
1159        // Settled only once ended: its `end` hook ran (`session`), or it is idle by the log and its state
1160        // file is as quiet (`open`): a session working without asks or episodes for a day is still open.
1161        let mut ended: Vec<String> = outcome::idle_sessions(&outcomes, &last_episode, now)
1162            .into_iter()
1163            .filter(|s| !pending.contains(*s) && !open(&ctx(s), now))
1164            .map(str::to_string)
1165            .collect();
1166        if let Some(s) = session.filter(|s| !ended.iter().any(|x| x == s) && !pending.contains(*s)) {
1167            ended.push(s.to_string());
1168        }
1169        for s in &ended {
1170            // The session's own tests that went green after an ask (hook.rs `capture_test`) credit the
1171            // lessons asked, once each, as it settles.
1172            if test_credit() {
1173                let tests = std::fs::read_to_string(state.join(format!("{}.tests", crate::notes::safe(s)))).unwrap_or_default();
1174                for o in outcome::tested(&outcomes, s, &tests) {
1175                    let _ = outcome::append(&outcomes_path, &o);
1176                    outcomes.push(o);
1177                }
1178            }
1179            // Each lesson left without a verdict says why (hook.rs `unjudged`, from the state file):
1180            // censored, never an ignore (memory.rs).
1181            let why = crate::hook::unjudged(&std::fs::read_to_string(ctx(s)).unwrap_or_default());
1182            for o in outcome::settle_with(&outcomes, s, now, &|l| why.get(l).copied().unwrap_or(outcome::UNJUDGED_NO_CALL)) {
1183                let _ = outcome::append(&outcomes_path, &o);
1184                outcomes.push(o);
1185            }
1186        }
1187    }
1188    (new, merged, failed)
1189}
1190
1191#[cfg(test)]
1192mod tests {
1193    use super::*;
1194
1195    #[test]
1196    fn concurrent_jsonl_appends_keep_every_line() {
1197        let dir = std::env::temp_dir().join(format!("borg-learn-append-{}", std::process::id()));
1198        let _ = std::fs::remove_dir_all(&dir);
1199        let p = dir.join("episodes.jsonl");
1200        let (writers, each) = (8, 2000);
1201        std::thread::scope(|scope| {
1202            for w in 0..writers {
1203                let p = &p;
1204                scope.spawn(move || (0..each).for_each(|i| append_jsonl(p, &serde_json::json!({"w": w, "i": i})).unwrap()));
1205            }
1206        });
1207        assert_eq!(read_jsonl::<Value>(&p).len(), writers * each);
1208        let _ = std::fs::remove_dir_all(dir);
1209    }
1210
1211    #[test]
1212    fn a_regret_is_asked_with_its_own_prompt_and_the_shared_rules() {
1213        let r = regret::Regret {
1214            decision_task: "read the flag in b".into(),
1215            fix_subject: "fix: take the lock".into(),
1216            signals: vec!["subject".into()],
1217            age_days: 3,
1218            ..regret::Regret::default()
1219        };
1220        let e = Episode {
1221            kind: regret::KIND.into(),
1222            regret: Some(r),
1223            task: "make the flag safe".into(),
1224            ..ep("Rdddd-ffff", "Fixed later (3d, subject): fix: take the lock")
1225        };
1226        let shown = std::cell::RefCell::new(String::new());
1227        let l = generalise(&e, &[], &|p| {
1228            *shown.borrow_mut() = p.to_string();
1229            Some(json!({"is_lesson": true, "question": "Before reading a shared flag without a lock, has a concurrent writer been considered?",
1230                "situations": ["reading a shared flag across threads"], "consequence": "a race", "same_as": "", "area": "concurrency", "supersedes": []}))
1231        })
1232        .unwrap()
1233        .unwrap();
1234        let p = shown.into_inner();
1235        assert!(p.starts_with("A coding agent made a decision in an earlier session") && p.contains("3 days later"), "{p}");
1236        for part in [
1237            regret::neutral(REACH_RULES).as_str(),
1238            regret::FIELDS,
1239            AREA,
1240            regret::neutral(MERGE_RULES).as_str(),
1241            "## The decision (task)\nread the flag in b",
1242            "## The fix (subject, task)\nfix: take the lock\nmake the flag safe",
1243        ] {
1244            assert!(p.contains(part), "{part}");
1245        }
1246        assert!(!p.contains("## Engineer's correction") && !p.contains(OPENING) && !p.contains("correction"), "{p}");
1247        assert_eq!((l.id.as_str(), l.area.as_str(), l.episodes.as_slice()), ("LRdddd-ffff", "concurrency", &["Rdddd-ffff".to_string()][..]));
1248        // A correction keeps its prompt; a kind without its regret is asked as a correction.
1249        assert!(episode_prompt(&ep("e1", "no, the lock"), &[]).starts_with(OPENING));
1250        assert!(episode_prompt(&Episode { kind: regret::KIND.into(), ..ep("e2", "no") }, &[]).starts_with(OPENING));
1251    }
1252
1253    /// The injected model for vetoes: like `fake_ask` on the veto's section, plus `invariant:<rest>`.
1254    fn fake_veto_ask(p: &str) -> Option<Value> {
1255        let reason = p.split("## Engineer's veto\n").nth(1)?.lines().next()?;
1256        let after = |k: &str| reason.split(k).nth(1).and_then(|r| r.split_whitespace().next()).unwrap_or("").to_string();
1257        let invariant = reason.split("invariant:").nth(1).unwrap_or("").trim().to_string();
1258        Some(json!({"is_lesson": true, "question": format!("Q {reason}"), "situations": [], "consequence": "c",
1259            "same_as": after("merge:"), "supersedes": [], "invariant": invariant}))
1260    }
1261
1262    fn veto(id: &str, session: &str, ms: i64, reason: &str) -> Episode {
1263        Episode { kind: crate::veto::KIND.into(), ..at(id, session, ms, "ann@x", reason) }
1264    }
1265
1266    #[test]
1267    fn a_veto_is_asked_with_its_own_prompt_and_schema() {
1268        let p = episode_prompt(&veto("no-s-1", "s", 1, "never read the commit log for merges"), &[]);
1269        assert!(p.starts_with(crate::veto::OPENING), "{p}");
1270        for part in [
1271            "## Engineer's veto\nnever read the commit log for merges",
1272            crate::veto::INVARIANT,
1273            REACH_RULES,
1274            FIELDS,
1275            MERGE_RULES,
1276            "## Task the agent had\nplan the relay",
1277        ] {
1278            assert!(p.contains(part), "{part}");
1279        }
1280        assert!(!p.contains(OPENING) && !p.contains("## Engineer's correction"));
1281        let without = episode_prompt(&Episode { agent: String::new(), ..veto("no-s-2", "s", 1, "no") }, &[]);
1282        assert!(without.contains("## What the agent proposed (excerpt)\n(not available)"), "{without}");
1283        assert!(schema_for(&p)["required"].as_array().unwrap().contains(&json!("invariant")));
1284        assert!(schema_for(&p)["properties"]["invariant"].is_object());
1285        let correction = episode_prompt(&ep("e1", "no, the lock"), &[]);
1286        assert_eq!(schema_for(&correction), schema(), "a correction's call is unchanged");
1287        // The invariant comes back with the lesson; a correction's answer has none.
1288        let (l, inv) =
1289            generalise_with(&veto("no-s-3", "s", 1, "merge lookups invariant: lookups go through the review API"), &[], &fake_veto_ask).unwrap().unwrap();
1290        assert_eq!((l.id.as_str(), inv.as_str()), ("Lno-s-3", "lookups go through the review API"));
1291        let (_, none) = generalise_with(&ep("e2", "no, the lock merge:x"), &[], &fake_ask).unwrap().unwrap();
1292        assert!(none.is_empty());
1293    }
1294
1295    #[test]
1296    fn a_veto_is_learned_at_any_sessions_end_and_never_counted_as_a_correction() {
1297        let home = temp_home("veto-any");
1298        crate::learn::record_episode_in(&home, &veto("no-s1-1", "s1", 1, "never read the commit log for merges")).unwrap();
1299        append_jsonl(&home.join("episodes.jsonl"), &at("e1", "s1", 2, "ann@x", "a correction of s1")).unwrap();
1300        assert!(!crate::stats::events(&home).iter().any(|e| e.kind == crate::stats::CORRECTION), "count_correction skips a veto");
1301        // s2 ends: the veto of s1 is learned, s1's correction waits for its own session.
1302        assert_eq!(learn_in(&home, Some("s2"), &fake_veto_ask, true, 3), (1, 0, 0));
1303        let ls = lessons(&home.join("lessons.jsonl"));
1304        assert_eq!(ls.iter().map(|l| l.id.as_str()).collect::<Vec<_>>(), ["Lno-s1-1"]);
1305        let news: Vec<crate::stats::Event> = crate::stats::events(&home).into_iter().filter(|e| e.kind == crate::stats::LESSON_NEW).collect();
1306        assert_eq!(news[0].why, "veto");
1307        let _ = std::fs::remove_dir_all(home);
1308    }
1309
1310    #[test]
1311    fn a_veto_merged_into_an_earlier_vetos_lesson_is_a_repeat() {
1312        let home = temp_home("veto-repeat");
1313        let repeats = |home: &Path| crate::stats::events(home).iter().filter(|e| e.kind == crate::stats::VETO_REPEAT).count();
1314        // A lesson from a correction, then a veto merged into it: no repeat (the first "no").
1315        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "use the lock on the flag")).unwrap();
1316        append_jsonl(&home.join("episodes.jsonl"), &veto("no-s1-2", "s1", 2, "the lock again merge:Le0")).unwrap();
1317        // Le0 was asked in s1 before the veto: the veto credits it (veto.rs), learning never adds a correction.
1318        let asked = outcome::Outcome { kind: outcome::ASKED.into(), session: "s1".into(), lessons: vec!["Le0".into()], ms: 1, ..Default::default() };
1319        outcome::append(&home.join("outcomes.jsonl"), &asked).unwrap();
1320        learn_in(&home, None, &|p| if p.starts_with(crate::veto::OPENING) { fake_veto_ask(p) } else { fake_ask(p) }, true, 3);
1321        assert_eq!(repeats(&home), 0);
1322        let results = outcome::read(&home.join("outcomes.jsonl"));
1323        assert!(!results.iter().any(|o| o.kind == outcome::CORRECTED || o.kind == outcome::MISSED), "{results:?}");
1324        assert!(!crate::stats::events(&home).iter().any(|e| e.kind == crate::stats::CORRECTED));
1325        // A second veto with the same reason: merged into the lesson a veto is part of.
1326        append_jsonl(&home.join("episodes.jsonl"), &veto("no-s2-4", "s2", 4, "the lock, third time merge:Le0")).unwrap();
1327        assert_eq!(learn_in(&home, Some("s2"), &fake_veto_ask, true, 5), (0, 1, 0));
1328        assert_eq!(repeats(&home), 1);
1329        let r = crate::stats::events(&home).into_iter().find(|e| e.kind == crate::stats::VETO_REPEAT).unwrap();
1330        assert_eq!((r.session.as_str(), r.lessons.clone()), ("s2", vec!["Le0".to_string()]));
1331        assert_eq!(r.ms, 4, "dated when the veto was said, the week of its own veto");
1332        let _ = std::fs::remove_dir_all(home);
1333    }
1334
1335    #[test]
1336    fn an_invariant_of_a_veto_becomes_a_proposed_constraint_never_a_constraint() {
1337        let home = temp_home("veto-invariant");
1338        append_jsonl(&home.join("episodes.jsonl"), &veto("no-s1-1", "s1", 1, "no commit log invariant: merge lookups use the review API")).unwrap();
1339        append_jsonl(&home.join("episodes.jsonl"), &veto("no-s1-2", "s1", 2, "not now, later")).unwrap();
1340        learn_in(&home, Some("s1"), &fake_veto_ask, true, 3);
1341        let queue = crate::queen::entries(&home);
1342        assert_eq!(queue.len(), 1, "only the veto that named an invariant");
1343        assert_eq!((queue[0].kind, queue[0].session.as_str()), (crate::queen::Kind::Constraint, "s1"));
1344        assert!(
1345            queue[0].evidence.contains(&"invariant: merge lookups use the review API".to_string())
1346                && queue[0].evidence.contains(&"lesson Lno-s1-1".to_string())
1347        );
1348        assert!(!crate::veto::constraints_path(&home).exists());
1349        // A personal lesson never proposes; nor does one without an invariant.
1350        let l = Lesson { id: "L".into(), ..Lesson::default() };
1351        let personal = crate::reach::Placed::Personal { lesson: Box::new(l.clone()), withdraw: None };
1352        assert!(proposes(&crate::reach::Placed::Here(Box::new(l)), "x") && !proposes(&personal, "x"));
1353        assert!(!proposes(&crate::reach::Placed::Here(Box::default()), " "));
1354        let _ = std::fs::remove_dir_all(home);
1355    }
1356
1357    #[test]
1358    fn detects_corrections_and_rejections() {
1359        assert!(is_correction("double check against spec document"));
1360        assert!(is_correction("No, let's not move this into the net"));
1361        assert!(!is_correction("let's pick up the gpt live plan"));
1362        let err = "The user doesn't want to proceed with this tool use. The tool use was rejected. the user said:\ncarefully check TOCTOU\nNote: The user's next message may contain a correction";
1363        assert_eq!(rejection(err).as_deref(), Some("carefully check TOCTOU"));
1364        assert_eq!(rejection("Exit code 1\nTraceback"), None);
1365        // omp's refusals carry no words; the reason follows as the next prompt.
1366        assert!(denied("Tool call denied by user: bash"));
1367        assert!(denied("Tool call rejected by user (edit)"));
1368        assert!(denied(
1369            "The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed."
1370        ));
1371        assert!(!denied(err), "a rejection with words is captured directly");
1372        assert!(!denied("Exit code 1\nTool call denied by user: bash"), "only the harness's own message, not tool output");
1373    }
1374
1375    #[test]
1376    fn known_holds_an_id_the_same_words_or_a_prompt_moments_apart() {
1377        let at = |id: &str, ms: i64, tool: Option<&str>, said: &str| Episode {
1378            id: id.into(),
1379            ms,
1380            session: "s1".into(),
1381            rejected_tool: tool.map(String::from),
1382            correction: said.into(),
1383            ..Episode::default()
1384        };
1385        let mut k = Known::default();
1386        // What the hook recorded: a rejection at capture time, a prompt.
1387        k.add(&at("s1-100000", 100_000, Some("Edit {}"), "use backoff,\n  not a fixed sleep"));
1388        k.add(&at("s1-200000", 200_000, None, "no, the other crate"));
1389        assert!(k.holds(&at("s1-Ttoolu_1", 70_000, Some("Edit {}"), "use backoff, not a fixed sleep")), "same words, whitespace aside");
1390        assert!(k.holds(&at("s1-100000", 1, None, "anything")), "same id");
1391        assert!(k.holds(&at("s1-201500", 201_500, None, "no, the other crate!")), "a prompt within SAME_MS");
1392        assert!(!k.holds(&at("s1-Ttoolu_2", 201_000, Some("Bash {}"), "keep the cache")), "a tool call's episode needs its id or its words");
1393        assert!(!k.holds(&Episode { via: ANSWER.into(), ..at("s1-Ttoolu_3", 200_500, None, "Exponential") }), "nor does an answer");
1394        assert!(!k.holds(&Episode { session: "s2".into(), ..at("s2-Tx", 100_000, Some("Edit {}"), "use backoff, not a fixed sleep") }));
1395        // Two calls the transcript named are two events, though their words match: a second rejection
1396        // with the same words, the same pick to another question.
1397        let mut t = Known::default();
1398        t.add(&at("s1-Ttoolu_4", 300_000, Some("Edit {}"), "keep it in the relay crate"));
1399        t.add(&Episode { via: ANSWER.into(), ..at("s1-Ttoolu_5", 400_000, None, "Create, no parent") });
1400        assert!(!t.holds(&at("s1-Ttoolu_6", 900_000, Some("Edit {}"), "keep it in the relay crate")), "another rejected call");
1401        assert!(!t.holds(&Episode { via: ANSWER.into(), ..at("s1-Ttoolu_7", 900_000, None, "Create, no parent") }), "another question");
1402        // An answer is never matched to a hook's episode by words.
1403        assert!(!k.holds(&Episode { via: ANSWER.into(), ..at("s1-Ttoolu_8", 900_000, None, "no, the other crate") }));
1404        assert_eq!(transcript_id("abcdefghij", "toolu_9", 5), "abcdefgh-Ttoolu_9");
1405        assert_eq!(transcript_id("abcdefghij", "", 5), "abcdefgh-5");
1406
1407        // record_new_in appends once, and once within one batch.
1408        let store = std::env::temp_dir().join(format!("borg-known-{}", std::process::id()));
1409        let _ = std::fs::remove_dir_all(&store);
1410        let e = at("s1-Tq", 5, None, "Exponential");
1411        let mut readied = 0;
1412        assert_eq!(record_new_in(&store, vec![e.clone(), e.clone()], |_| readied += 1).unwrap().len(), 1);
1413        assert!(record_new_in(&store, vec![e.clone()], |_| panic!("a held episode is not readied")).unwrap().is_empty());
1414        assert_eq!(readied, 1);
1415        assert!(Known::read(&store).holds(&e));
1416        assert_eq!(read_jsonl::<Episode>(&store.join("episodes.jsonl")).len(), 1);
1417        let _ = std::fs::remove_dir_all(&store);
1418    }
1419
1420    #[test]
1421    fn writers_at_once_append_an_episode_once() {
1422        let store = std::env::temp_dir().join(format!("borg-known-race-{}", std::process::id()));
1423        let _ = std::fs::remove_dir_all(&store);
1424        let e = Episode { id: "s1-Tx".into(), session: "s1".into(), correction: "keep the cache dir".into(), ..Episode::default() };
1425        let start = std::sync::Barrier::new(8);
1426        std::thread::scope(|s| {
1427            for _ in 0..8 {
1428                s.spawn(|| {
1429                    start.wait();
1430                    record_new_in(&store, vec![e.clone()], |_| std::thread::yield_now()).unwrap();
1431                });
1432            }
1433        });
1434        assert_eq!(read_jsonl::<Episode>(&store.join("episodes.jsonl")).len(), 1);
1435        let _ = std::fs::remove_dir_all(&store);
1436    }
1437
1438    #[test]
1439    fn an_answer_is_asked_as_an_answer_and_counted_as_one() {
1440        let answer = Episode { via: ANSWER.into(), agent: "Which backoff?\n  options: Exponential | Linear".into(), ..ep("a1", "Exponential") };
1441        let p = episode_prompt(&answer, &[]);
1442        assert!(p.contains(ANSWERED) && p.contains("## Engineer's correction\nExponential"), "{p}");
1443        assert!(!episode_prompt(&ep("e1", "no"), &[]).contains(ANSWERED));
1444        let store = std::env::temp_dir().join(format!("borg-answer-count-{}", std::process::id()));
1445        let _ = std::fs::remove_dir_all(&store);
1446        count_correction(&store, &answer);
1447        let ev = crate::stats::live(&store);
1448        assert_eq!((ev.len(), ev[0].why.as_str()), (1, ANSWER));
1449        let _ = std::fs::remove_dir_all(&store);
1450    }
1451
1452    fn ep(id: &str, correction: &str) -> Episode {
1453        Episode {
1454            id: id.into(),
1455            ms: 1,
1456            repo: "r".into(),
1457            session: "s".into(),
1458            task: "plan the relay".into(),
1459            agent: "one ReentrantLock guards delivery".into(),
1460            rejected_tool: None,
1461            correction: correction.into(),
1462            ..Episode::default()
1463        }
1464    }
1465
1466    /// The injected model: `same_as` is the lesson id after "merge:" in the correction, if any, and
1467    /// `supersedes` the one after "supersede:".
1468    fn fake_ask(p: &str) -> Option<Value> {
1469        let correction = p.split("## Engineer's correction\n").nth(1)?.lines().next()?;
1470        let after = |k: &str| correction.split(k).nth(1).and_then(|r| r.split_whitespace().next()).unwrap_or("").to_string();
1471        let supersedes: Vec<String> = Some(after("supersede:")).filter(|x| !x.is_empty()).into_iter().collect();
1472        Some(json!({"is_lesson": true, "question": format!("Q {correction}"), "situations": [], "consequence": "c",
1473            "same_as": after("merge:"), "supersedes": supersedes}))
1474    }
1475
1476    fn results(home: &Path) -> Vec<(String, String, String)> {
1477        outcome::read(&home.join("outcomes.jsonl")).into_iter().filter(|o| o.kind != outcome::ASKED).map(|o| (o.kind, o.session, o.lessons.join(","))).collect()
1478    }
1479
1480    #[test]
1481    fn every_model_call_is_reported_with_its_place_and_verdict() {
1482        let home = temp_home("progress");
1483        for e in [at("e0", "s0", 1, "ann@x", "use the lock on the flag"), at("e1", "s0", 2, "bob@x", "the lock again merge:Le0")] {
1484            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1485        }
1486        let mut steps = Vec::new();
1487        learn_in_reporting(&home, None, &fake_ask, false, 3, &mut |st| steps.push((st.done, st.total, st.verdict.split(':').next().unwrap().to_string())));
1488        assert_eq!(steps, [(1, 2, "new lesson Le0".to_string()), (2, 2, "merged into Le0".to_string())]);
1489        // A second run has nothing left to ask, so it reports nothing.
1490        steps.clear();
1491        learn_in_reporting(&home, None, &fake_ask, false, 4, &mut |st| steps.push((st.done, st.total, String::new())));
1492        assert!(steps.is_empty());
1493        let _ = std::fs::remove_dir_all(home);
1494    }
1495
1496    #[test]
1497    fn a_lesson_contradicted_after_asking_is_corrected_not_followed() {
1498        let home = temp_home("contradicted");
1499        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "use the lock on the flag")).unwrap();
1500        learn_in(&home, Some("s0"), &fake_ask, true, 2);
1501        // s1 asks Le0, then the engineer contradicts it: a new lesson superseding Le0.
1502        asked(&home, "s1", 10, &["Le0"]);
1503        append_jsonl(&home.join("episodes.jsonl"), &at("e1", "s1", 20, "bob@x", "no, CAS on the flag supersede:Le0")).unwrap();
1504        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, true, 30), (1, 0, 0));
1505        assert_eq!(results(&home), [(outcome::CORRECTED.into(), "s1".into(), "Le0".into())]);
1506        let _ = std::fs::remove_dir_all(home);
1507    }
1508
1509    #[test]
1510    fn a_correction_of_a_lesson_that_applied_but_was_not_asked_is_a_miss() {
1511        let home = temp_home("missed");
1512        for e in [at("e0", "s0", 1, "ann@x", "use the lock on the flag"), at("e1", "s0", 2, "bob@x", "retry with jitter")] {
1513            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1514        }
1515        learn_in(&home, Some("s0"), &fake_ask, true, 3);
1516        // s1's check graded both as applying and chose to ask only Le1; the engineer then corrects the
1517        // drone on Le0's concern: Le0 was needed and not asked.
1518        let graded = outcome::Outcome {
1519            kind: outcome::GRADED.into(),
1520            session: "s1".into(),
1521            lessons: vec!["Le0".into(), "Le1".into()],
1522            ms: 10,
1523            repo: "r".into(),
1524            grades: vec![2, 3],
1525            ranks: vec![0, 1],
1526            applied: 2,
1527            chosen: vec!["Le1".into()],
1528            ..Default::default()
1529        };
1530        outcome::append(&home.join("outcomes.jsonl"), &graded).unwrap();
1531        asked(&home, "s1", 11, &["Le1"]);
1532        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s1", 20, "cy@x", "no, the lock on the flag merge:Le0")).unwrap();
1533        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, true, 30), (0, 1, 0));
1534        let r = results(&home);
1535        assert!(r.contains(&(outcome::MISSED.into(), "s1".into(), "Le0".into())), "{r:?}");
1536        // The asked one is not a miss; a second run records nothing new.
1537        assert!(!r.iter().any(|(k, _, l)| k == outcome::MISSED && l == "Le1"), "{r:?}");
1538        learn_in(&home, Some("s1"), &fake_ask, true, 40);
1539        assert_eq!(results(&home).iter().filter(|(k, ..)| k == outcome::MISSED).count(), 1);
1540        let _ = std::fs::remove_dir_all(home);
1541    }
1542
1543    #[test]
1544    fn siding_with_one_side_of_a_disagreement_corrects_the_other() {
1545        let home = temp_home("sides");
1546        for e in [at("e0", "s0", 1, "ann@x", "use the lock on the flag"), at("e1", "s0", 2, "bob@x", "use CAS on the flag")] {
1547            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1548        }
1549        learn_in(&home, Some("s0"), &fake_ask, true, 3);
1550        // The conscience rendered Le0 and Le1 as one disagreement; the engineer sides with Le0.
1551        let o = outcome::Outcome {
1552            kind: outcome::ASKED.into(),
1553            session: "s1".into(),
1554            lessons: vec!["Le0".into(), "Le1".into()],
1555            ms: 10,
1556            repo: "r".into(),
1557            groups: vec![vec!["Le0".into(), "Le1".into()]],
1558            ..Default::default()
1559        };
1560        outcome::append(&home.join("outcomes.jsonl"), &o).unwrap();
1561        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s1", 20, "cy@x", "no, the lock on the flag merge:Le0")).unwrap();
1562        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, true, 30), (0, 1, 0));
1563        assert_eq!(results(&home), [(outcome::CORRECTED.into(), "s1".into(), "Le1".into()), (outcome::NOT_CORRECTED.into(), "s1".into(), "Le0".into())]);
1564        // cy joined Le0 at the correction; ann's earlier evidence is not his.
1565        let l0 = lessons(&home.join("lessons.jsonl")).into_iter().find(|l| l.id == "Le0").unwrap();
1566        assert_eq!(l0.joined.get("cy@x"), Some(&20));
1567        let _ = std::fs::remove_dir_all(home);
1568    }
1569
1570    #[test]
1571    fn the_learn_prompt_offers_at_most_merge_candidates_lessons_for_merging() {
1572        let lib: Vec<Lesson> = (0..MERGE_CANDIDATES + 2)
1573            .map(|i| Lesson {
1574                id: format!("L{i}"),
1575                origin_ms: i as i64,
1576                question: format!("Is the ReentrantLock held while delivery {i} runs?"),
1577                consequence: "c".into(),
1578                version: 1,
1579                ..Lesson::default()
1580            })
1581            .collect();
1582        let e = ep("e1", "no, the ReentrantLock must guard delivery");
1583        let offered = similar(&e, &lib);
1584        assert_eq!(offered.len(), MERGE_CANDIDATES, "every lesson matches; the prompt offers the best few");
1585        let prompt = std::cell::RefCell::new(String::new());
1586        let _ = generalise(&e, &lib, &|p| {
1587            *prompt.borrow_mut() = p.to_string();
1588            None
1589        });
1590        let named = lib.iter().filter(|l| prompt.borrow().contains(&format!("[{}]", l.id))).count();
1591        assert_eq!(named, MERGE_CANDIDATES, "{}", prompt.borrow());
1592    }
1593
1594    #[test]
1595    fn a_superseded_lesson_is_not_a_merge_target_its_successor_is_shown() {
1596        let lesson = |id: &str, ms: i64, q: &str, sup: &[&str]| Lesson {
1597            id: id.into(),
1598            origin_ms: ms,
1599            repo: "r".into(),
1600            question: q.into(),
1601            situations: vec![],
1602            consequence: "c".into(),
1603            support: 1,
1604            episodes: vec![],
1605            history: vec![],
1606            version: 1,
1607            engineers: vec!["ann@x".into()],
1608            joined: Default::default(),
1609            area: "concurrency".into(),
1610            supersedes: sup.iter().map(|s| s.to_string()).collect(),
1611            source: String::new(),
1612            scope: vec![],
1613            overrides: String::new(),
1614            origin: String::new(),
1615            facets: vec![],
1616            reach: String::new(),
1617        };
1618        let lib = [lesson("L0", 1, "Is the closed flag guarded by the ReentrantLock?", &[]), lesson("L1", 2, "Would a CAS suffice?", &["L0"])];
1619        // ann reverts to the lock: the model only sees L1 (in L0's place), contradicts it, and the
1620        // restored view becomes a new lesson that supersedes L1 and is asked again.
1621        let shown = std::cell::RefCell::new(String::new());
1622        let back = generalise(&ep("e9", "no, guard the closed flag with the ReentrantLock"), &lib, &|p| {
1623            *shown.borrow_mut() = p.to_string();
1624            Some(json!({"is_lesson": true, "question": "Is the closed flag guarded by the ReentrantLock?", "situations": [],
1625                "consequence": "c", "same_as": "L0", "area": "concurrency", "supersedes": ["L1"]}))
1626        })
1627        .unwrap()
1628        .unwrap();
1629        let shown = shown.into_inner();
1630        assert!(shown.contains("[L1]") && !shown.contains("[L0]"), "{shown}");
1631        assert_eq!((back.version, back.supersedes.clone()), (1, vec!["L1".to_string()]), "same_as on a hidden lesson is no merge");
1632        let all: Vec<Challenge> = lib
1633            .iter()
1634            .chain([&back])
1635            .map(|l| Challenge {
1636                id: l.id.clone(),
1637                origin_ms: l.origin_ms,
1638                question: l.question.clone(),
1639                engineers: l.engineers.clone(),
1640                supersedes: l.supersedes.clone(),
1641                ..Default::default()
1642            })
1643            .collect();
1644        assert_eq!(trust::successors(&all).get("L0").map(String::as_str), Some(back.id.as_str()));
1645    }
1646
1647    /// `fake_ask`, judging a correction that says "mine only" personal.
1648    fn fake_personal(p: &str) -> Option<Value> {
1649        let mut v = fake_ask(p)?;
1650        if p.split("## Engineer's correction\n").nth(1)?.lines().next()?.contains("mine only") {
1651            v["reach"] = json!(crate::reach::PERSONAL);
1652        }
1653        Some(v)
1654    }
1655
1656    #[test]
1657    fn a_personal_lesson_stays_in_its_collective_is_learned_once_and_delivered_only_there() {
1658        let base = temp_home("personal");
1659        let (work, oss) = (crate::collective::store(&base, "work"), crate::collective::store(&base, "oss"));
1660        std::fs::create_dir_all(&oss).unwrap();
1661        append_jsonl(&work.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "no co-author trailer, mine only")).unwrap();
1662        let calls = std::cell::Cell::new(0);
1663        let ask = |p: &str| {
1664            calls.set(calls.get() + 1);
1665            fake_personal(p)
1666        };
1667        assert_eq!(learn_in(&work, None, &ask, false, 3), (1, 0, 0));
1668        let personal = crate::reach::personal_lessons(&work);
1669        assert_eq!(personal.iter().map(|l| (l.id.as_str(), l.reach.as_str())).collect::<Vec<_>>(), [("Le0", crate::reach::PERSONAL)]);
1670        assert!(lessons(&work.join("lessons.jsonl")).is_empty(), "nothing in the team's lessons");
1671        assert_eq!(std::fs::read_dir(base.join("collectives")).unwrap().count(), 2, "no other store written");
1672        assert!(!oss.join("lessons.jsonl").exists() && !crate::reach::personal_path(&oss).exists());
1673        // Learned once: the second run finds its episode done and asks nothing.
1674        assert_eq!(learn_in(&work, None, &ask, false, 4), (0, 0, 0));
1675        assert_eq!(calls.get(), 1);
1676        // A later correction merging into it stays personal, whatever its own verdict: a merge never widens.
1677        append_jsonl(&work.join("episodes.jsonl"), &at("e1", "s1", 5, "ann@x", "the trailer again merge:Le0")).unwrap();
1678        assert_eq!(learn_in(&work, None, &ask, false, 6), (0, 1, 0));
1679        assert_eq!(crate::reach::personal_lessons(&work)[0].version, 2);
1680        assert!(lessons(&work.join("lessons.jsonl")).is_empty());
1681        assert_eq!(learned_episodes(&work), ["e0".to_string(), "e1".to_string()].into_iter().collect());
1682        // Delivered in this collective's sessions, as a team lesson for this engineer; in another
1683        // collective's never, nor in the team's own view of the store.
1684        let aliases = crate::collective::Aliases::default();
1685        let here = crate::conscience::load_store_with(&work.join("lessons.jsonl"), None, &aliases);
1686        assert!(here.iter().any(|c| c.id == "Le0" && crate::reach::deliverable(c, &["r".into()])), "{here:?}");
1687        assert!(crate::conscience::load_store_with(&oss.join("lessons.jsonl"), None, &aliases).is_empty());
1688        assert!(crate::conscience::load_with(&work.join("lessons.jsonl"), None, &aliases).is_empty());
1689        // Asked beside a team lesson: the team's synced logs name the team lesson only, never the
1690        // personal one (its id, when, which repo).
1691        for id in ["Le0", "Lteam"] {
1692            let o =
1693                outcome::Outcome { kind: outcome::ASKED.into(), session: "s9".into(), lessons: vec![id.into()], ms: 9, repo: "r".into(), ..Default::default() };
1694            outcome::append(&work.join("outcomes.jsonl"), &o).unwrap();
1695        }
1696        crate::stats::count(&work, crate::stats::LESSON_NEW, "s9", |ev| ev.lessons = vec!["Lteam".into()]);
1697        assert!(outcome::publish(&work) > 0 && crate::stats::rollup(&work) > 0);
1698        for f in [outcome::TEAM_FILE, "stats.jsonl"] {
1699            let text = std::fs::read_to_string(work.join(f)).unwrap();
1700            assert!(text.contains("Lteam") && !text.contains("Le0"), "{f}: {text}");
1701        }
1702        let _ = std::fs::remove_dir_all(base);
1703    }
1704
1705    #[test]
1706    fn a_personal_lesson_replaces_its_tombstone_where_it_is_delivered() {
1707        let base = temp_home("tombstone");
1708        let work = crate::collective::store(&base, "work");
1709        let l = Lesson { id: "L1".into(), question: "short commit subjects?".into(), version: 2, engineers: vec!["ann@x".into()], ..Lesson::default() };
1710        append_jsonl(&work.join("lessons.jsonl"), &crate::reach::tombstone(&l)).unwrap();
1711        append_jsonl(&crate::reach::personal_path(&work), &Lesson { reach: crate::reach::PERSONAL.into(), ..l }).unwrap();
1712        let cs = crate::conscience::load_store_with(&work.join("lessons.jsonl"), None, &crate::collective::Aliases::default());
1713        assert_eq!(cs.len(), 1);
1714        assert!(cs[0].question == "short commit subjects?" && crate::reach::deliverable(&cs[0], &[]));
1715        assert_eq!(store_lessons(&work).len(), 1);
1716        let _ = std::fs::remove_dir_all(base);
1717    }
1718
1719    #[test]
1720    fn a_personal_lesson_moved_elsewhere_is_neither_delivered_nor_merged_into_here() {
1721        let base = temp_home("moved-personal");
1722        let work = crate::collective::store(&base, "work");
1723        let l = Lesson {
1724            id: "Le0".into(),
1725            question: "short commit subjects?".into(),
1726            version: 1,
1727            episodes: vec!["e0".into()],
1728            reach: crate::reach::PERSONAL.into(),
1729            engineers: vec!["ann@x".into()],
1730            ..Lesson::default()
1731        };
1732        append_jsonl(&crate::reach::personal_path(&work), &l).unwrap();
1733        // What `borg move` leaves behind (moves.rs): the tombstone keeps the episodes.
1734        let t = Lesson { version: 2, question: crate::reach::MOVED.into(), consequence: String::new(), ..l.clone() };
1735        append_jsonl(&crate::reach::personal_path(&work), &t).unwrap();
1736        append_jsonl(&work.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "short subjects, mine only")).unwrap();
1737        let cs = crate::conscience::load_store_with(&work.join("lessons.jsonl"), None, &crate::collective::Aliases::default());
1738        assert!(cs.is_empty(), "the tombstone is never delivered: {cs:?}");
1739        assert!(store_lessons(&work).is_empty() && crate::reach::personal_lessons(&work).is_empty());
1740        assert!(learned_episodes(&work).contains("e0"), "its episodes stay learned");
1741        // A later correction that would merge into it makes a lesson of its own: the moved one stays gone.
1742        append_jsonl(&work.join("episodes.jsonl"), &at("e1", "s1", 2, "ann@x", "subjects moved to another collective again merge:Le0 mine only")).unwrap();
1743        assert_eq!(learn_in(&work, None, &fake_personal, false, 3), (1, 0, 0), "e0 is done; e1 cannot merge into Le0");
1744        let latest = crate::learn::lessons(&crate::reach::personal_path(&work));
1745        assert_eq!(latest.iter().find(|l| l.id == "Le0").map(|l| l.question.as_str()), Some(crate::reach::MOVED));
1746        let _ = std::fs::remove_dir_all(base);
1747    }
1748
1749    #[test]
1750    fn the_hooks_episode_waits_for_a_move_rewriting_the_log() {
1751        let home = temp_home("record-locked");
1752        let (held_tx, held_rx) = std::sync::mpsc::channel();
1753        let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
1754        let log = home.join("episodes.jsonl");
1755        let mover = {
1756            let log = log.clone();
1757            std::thread::spawn(move || {
1758                crate::live::locked(&log, || {
1759                    held_tx.send(()).unwrap();
1760                    go_rx.recv().unwrap();
1761                    // A move's rewrite: the log taken whole while the lock is held.
1762                    std::fs::write(&log, "").unwrap();
1763                })
1764            })
1765        };
1766        held_rx.recv().unwrap();
1767        let writer = {
1768            let home = home.clone();
1769            std::thread::spawn(move || record_episode_locked(&home, &at("e1", "s1", 1, "ann@x", "no, use the lock")).unwrap())
1770        };
1771        std::thread::sleep(std::time::Duration::from_millis(150));
1772        assert!(std::fs::read_to_string(&log).unwrap_or_default().is_empty(), "the append waits for the lock");
1773        go_tx.send(()).unwrap();
1774        mover.join().unwrap();
1775        writer.join().unwrap();
1776        assert!(std::fs::read_to_string(&log).unwrap().contains("\"e1\""), "and lands after the rewrite, not in it");
1777        let _ = std::fs::remove_dir_all(home);
1778    }
1779
1780    #[test]
1781    fn a_repo_reach_without_a_repo_is_the_teams() {
1782        let reach = |repo: &str, same_as: &str, lib: &[Lesson]| {
1783            let e = Episode { repo: repo.into(), ..ep("e1", "in the library keep the upstream grammar") };
1784            let answer = json!({"is_lesson": true, "question": "Q", "situations": [], "consequence": "c", "same_as": same_as, "area": "", "supersedes": [], "reach": "repo"});
1785            generalise(&e, lib, &|_| Some(answer.clone())).unwrap().unwrap().reach
1786        };
1787        assert_eq!(reach("", "", &[]), "", "a borg correct without --repo: heard by the team, not nowhere");
1788        assert_eq!(reach("lib", "", &[]), crate::reach::REPO);
1789        let old = Lesson { id: "L0".into(), question: "Does the library keep the upstream grammar?".into(), version: 1, ..Lesson::default() };
1790        assert_eq!(reach("lib", "L0", std::slice::from_ref(&old)), "", "merged into a lesson of no repo");
1791    }
1792
1793    #[test]
1794    fn an_episode_of_a_repo_that_routes_elsewhere_now_is_held_and_listed() {
1795        let base = temp_home("held");
1796        let repos = base.join("repos");
1797        for d in ["work/app", "oss/lib"] {
1798            std::fs::create_dir_all(repos.join(d)).unwrap();
1799        }
1800        let config = |oss: &str| -> crate::collective::Config {
1801            serde_json::from_value(json!({"collectives": [
1802                {"name": "work", "paths": [repos.join("work")]},
1803                {"name": "oss", "paths": [repos.join(oss)]}]}))
1804            .unwrap()
1805        };
1806        let cfg = config("oss/lib");
1807        let (work, oss) = (crate::collective::store(&base, "work"), crate::collective::store(&base, "oss"));
1808        let on = |id: &str, repo: &str, via: &str| Episode { repo: repo.into(), via: via.into(), ..at(id, "s0", 1, "ann@x", &format!("check {id}")) };
1809        for e in [on("e0", "app", ""), on("e1", "lib", ""), on("e2", "lib", CORRECT), on("e3", "elsewhere", ""), on("e4", "lib", "")] {
1810            append_jsonl(&work.join("episodes.jsonl"), &e).unwrap();
1811        }
1812        let calls = std::cell::Cell::new(0);
1813        let ask = |p: &str| {
1814            calls.set(calls.get() + 1);
1815            fake_ask(p)
1816        };
1817        // Learned here: its repo routes here, it was recorded here by name, or its route is unknown.
1818        assert_eq!(learn_in_config(&work, Some(&cfg), None, &ask, false, 3, &mut |_| {}), (3, 0, 0));
1819        let mut learned: Vec<String> = lessons(&work.join("lessons.jsonl")).into_iter().map(|l| l.id).collect();
1820        learned.sort();
1821        assert_eq!(learned, ["Le0", "Le2", "Le3"]);
1822        let route = crate::collective::Route::Collective { name: "oss".into(), home: oss.clone(), share: crate::collective::Share::Team };
1823        assert_eq!(held(&work, Some(&cfg)), [HeldRepo { repo: "lib".into(), route, episodes: vec!["e1".into(), "e4".into()] }]);
1824        // Held, not skipped: nothing marks them, and a second run asks nothing.
1825        assert!(!work.join("episodes-not-lessons.txt").exists());
1826        assert_eq!(learn_in_config(&work, Some(&cfg), None, &ask, false, 4, &mut |_| {}), (0, 0, 0));
1827        assert_eq!(calls.get(), 3);
1828        // No config, or a store that is no collective's: nothing is held.
1829        assert!(held(&work, None).is_empty() && held(&base, Some(&cfg)).is_empty());
1830        // Routed here again: learned here.
1831        let back = config("oss/none");
1832        assert!(held(&work, Some(&back)).is_empty());
1833        assert_eq!(learn_in_config(&work, Some(&back), None, &ask, false, 5, &mut |_| {}), (2, 0, 0));
1834        let _ = std::fs::remove_dir_all(base);
1835    }
1836
1837    fn temp_home(name: &str) -> PathBuf {
1838        let d = std::env::temp_dir().join(format!("borg-learn-{name}-{}", std::process::id()));
1839        let _ = std::fs::remove_dir_all(&d);
1840        std::fs::create_dir_all(&d).unwrap();
1841        d
1842    }
1843
1844    fn at(id: &str, session: &str, ms: i64, engineer: &str, correction: &str) -> Episode {
1845        Episode { ms, session: session.into(), engineer: engineer.into(), ..ep(id, correction) }
1846    }
1847
1848    fn asked(home: &Path, session: &str, ms: i64, ids: &[&str]) {
1849        let o = outcome::Outcome {
1850            kind: outcome::ASKED.into(),
1851            session: session.into(),
1852            lessons: ids.iter().map(|i| i.to_string()).collect(),
1853            ms,
1854            repo: "r".into(),
1855            ..Default::default()
1856        };
1857        outcome::append(&home.join("outcomes.jsonl"), &o).unwrap();
1858    }
1859
1860    fn regret_at(id: &str, decision_ms: i64) -> Episode {
1861        let r = regret::Regret { decision_session: "s-dec".into(), decision_ms, signals: vec!["subject".into()], ..regret::Regret::default() };
1862        Episode { kind: regret::KIND.into(), regret: Some(r), ..at(id, "s-fix", 100, "bob@x", "Fixed later (3d, subject): fix: take the lock") }
1863    }
1864
1865    /// The model's verdict on a regret: a lesson, or (`lesson` false) not one.
1866    fn regret_ask(lesson: bool) -> impl Fn(&str) -> Option<Value> {
1867        move |_| {
1868            Some(json!({"is_lesson": lesson, "question": "Before reading a shared flag, has a writer been considered?", "situations": [],
1869            "consequence": "a race", "same_as": "", "supersedes": []}))
1870        }
1871    }
1872
1873    #[test]
1874    fn a_settled_lesson_says_why_the_judge_gave_it_no_verdict() {
1875        let home = temp_home("unjudged");
1876        asked(&home, "s1", 10, &["A", "B", "C", "D"]);
1877        let ignored =
1878            outcome::Outcome { kind: outcome::IGNORED.into(), session: "s1".into(), lessons: vec!["A".into()], ms: 12, repo: "r".into(), ..Default::default() };
1879        outcome::append(&home.join("outcomes.jsonl"), &ignored).unwrap();
1880        std::fs::create_dir_all(home.join("state")).unwrap();
1881        let ctx = "#borg-asked A,B,C,D @0123456789ab\n#borg-judged B=pending\n#borg-judged B=pending\n#borg-unjudged C why=slots\n";
1882        std::fs::write(home.join("state/s1.ctx"), ctx).unwrap();
1883        learn_in(&home, Some("s1"), &fake_ask, true, 100);
1884        let why: Vec<(String, String)> = outcome::read(&home.join("outcomes.jsonl"))
1885            .into_iter()
1886            .filter(|o| o.kind == outcome::NOT_CORRECTED)
1887            .map(|o| (o.lessons.join(","), o.reason))
1888            .collect();
1889        let want = [("A", outcome::UNJUDGED_NONE), ("B", outcome::UNJUDGED_TRIES), ("C", outcome::UNJUDGED_SLOTS), ("D", outcome::UNJUDGED_NO_CALL)];
1890        assert_eq!(why, want.map(|(l, r)| (l.to_string(), r.to_string())));
1891        let _ = std::fs::remove_dir_all(home);
1892    }
1893
1894    /// Settle waits for a session's end: idle by the log (no ask or episode for a day) is not enough while
1895    /// its state file is still being written.
1896    #[test]
1897    fn an_idle_session_still_working_is_not_settled() {
1898        let home = temp_home("open");
1899        asked(&home, "s1", 10, &["A"]);
1900        std::fs::create_dir_all(home.join("state")).unwrap();
1901        std::fs::write(home.join("state/s1.ctx"), "a prompt just now\n").unwrap();
1902        let now = now_ms();
1903        learn_in(&home, None, &fake_ask, true, now);
1904        assert!(results(&home).is_empty(), "still open: {:?}", results(&home));
1905        // A day after its last line, it ended.
1906        learn_in(&home, None, &fake_ask, true, now + outcome::IDLE_MS + 60_000);
1907        assert_eq!(results(&home), [(outcome::NOT_CORRECTED.into(), "s1".into(), "A".into())]);
1908        let _ = std::fs::remove_dir_all(home);
1909    }
1910
1911    /// A regret is a correction of the deciding session's work too: the lesson it merges into, graded
1912    /// applying in that session before the decision and never asked there, was a question needed and not
1913    /// asked.
1914    #[test]
1915    fn a_regret_merged_into_a_lesson_graded_but_not_asked_before_the_decision_is_a_miss() {
1916        let home = temp_home("regret-miss");
1917        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "use the lock on the flag")).unwrap();
1918        learn_in(&home, Some("s0"), &fake_ask, true, 2);
1919        let graded = |ms: i64| outcome::Outcome {
1920            kind: outcome::GRADED.into(),
1921            session: "s-dec".into(),
1922            lessons: vec!["Le0".into()],
1923            ms,
1924            repo: "r".into(),
1925            grades: vec![2],
1926            ..Default::default()
1927        };
1928        for g in [graded(10), graded(30)] {
1929            outcome::append(&home.join("outcomes.jsonl"), &g).unwrap();
1930        }
1931        append_jsonl(&home.join("episodes.jsonl"), &regret_at("R1", 20)).unwrap();
1932        let merge = |_: &str| Some(json!({"is_lesson": true, "question": "Q", "situations": [], "consequence": "c", "same_as": "Le0", "supersedes": []}));
1933        learn_in(&home, None, &merge, true, 200);
1934        let missed: Vec<(String, String, i64, String)> = outcome::read(&home.join("outcomes.jsonl"))
1935            .into_iter()
1936            .filter(|o| o.kind == outcome::MISSED)
1937            .map(|o| (o.lessons.join(","), o.session, o.ms, o.cause))
1938            .collect();
1939        assert_eq!(missed, [("Le0".to_string(), "s-dec".to_string(), 20, "R1".to_string())]);
1940        learn_in(&home, None, &merge, true, 300);
1941        assert_eq!(outcome::read(&home.join("outcomes.jsonl")).iter().filter(|o| o.kind == outcome::MISSED).count(), 1, "once");
1942        let _ = std::fs::remove_dir_all(home);
1943    }
1944
1945    #[test]
1946    fn a_regret_blames_lessons_asked_before_the_decision_once() {
1947        let regretted = |home: &Path| -> Vec<(String, String, f64, String)> {
1948            outcome::read(&home.join("outcomes.jsonl"))
1949                .into_iter()
1950                .filter(|o| o.kind == outcome::REGRETTED)
1951                .map(|o| (o.lessons.join(","), o.session, o.credit, o.cause))
1952                .collect()
1953        };
1954        let setup = |name: &str, e: Episode| {
1955            let home = temp_home(name);
1956            asked(&home, "s-dec", 10, &["Le0", "Le1"]);
1957            asked(&home, "s-dec", 50, &["Le2"]);
1958            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1959            home
1960        };
1961        let home = setup("regret", regret_at("R1", 20));
1962        assert_eq!(learn_in(&home, None, &regret_ask(true), true, 200), (1, 0, 0));
1963        let got = regretted(&home);
1964        assert_eq!(
1965            got,
1966            [("Le0".into(), "s-dec".into(), 0.25, "R1".into()), ("Le1".into(), "s-dec".into(), 0.25, "R1".into())],
1967            "Le2 was asked after the decision"
1968        );
1969        let before = std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap();
1970        learn_in(&home, None, &regret_ask(true), true, 300);
1971        assert_eq!(std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap(), before, "credited once");
1972        let _ = std::fs::remove_dir_all(home);
1973        // Not a lesson, no decision time, not tracking: nothing is blamed.
1974        let home = setup("regret-no", regret_at("R1", 20));
1975        learn_in(&home, None, &regret_ask(false), true, 200);
1976        assert!(regretted(&home).is_empty(), "not a lesson");
1977        let _ = std::fs::remove_dir_all(home);
1978        let home = setup("regret-old", regret_at("R1", 0));
1979        learn_in(&home, None, &regret_ask(true), true, 200);
1980        assert!(regretted(&home).is_empty(), "a regret from before decision times were kept");
1981        let _ = std::fs::remove_dir_all(home);
1982        let home = setup("regret-untracked", regret_at("R1", 20));
1983        learn_in(&home, None, &regret_ask(true), false, 200);
1984        assert!(regretted(&home).is_empty(), "BORG_LEARN=off writes nothing");
1985        let _ = std::fs::remove_dir_all(home);
1986    }
1987
1988    #[test]
1989    fn records_outcomes_of_asked_lessons() {
1990        let home = temp_home("outcomes");
1991        // Session s0 teaches lessons Le0 (TOCTOU) and Le1 (spec).
1992        for e in [at("e0", "s0", 1, "ann@x", "check TOCTOU on the flag"), at("e1", "s0", 2, "", "check against the spec")] {
1993            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1994        }
1995        assert_eq!(learn_in(&home, Some("s0"), &fake_ask, true, 3), (2, 0, 0));
1996        assert!(outcome::read(&home.join("outcomes.jsonl")).is_empty(), "nothing asked, nothing settled");
1997        // s1: both asked at 10; the TOCTOU concern is corrected again at 20 (merged into Le0).
1998        // Le1 asked again after that correction, which must not count as corrected.
1999        asked(&home, "s1", 10, &["Le0", "Le1"]);
2000        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s1", 20, "bob@x", "flag still racy merge:Le0")).unwrap();
2001        asked(&home, "s1", 30, &["Le1"]);
2002        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, true, 40), (0, 1, 0));
2003        let result: Vec<(String, String, i64)> =
2004            outcome::read(&home.join("outcomes.jsonl")).into_iter().filter(|o| o.kind != outcome::ASKED).map(|o| (o.kind, o.lessons.join(","), o.ms)).collect();
2005        assert_eq!(result, [(outcome::CORRECTED.into(), "Le0".into(), 20), (outcome::NOT_CORRECTED.into(), "Le1".into(), 40)]);
2006        // Re-running learn for the same session appends nothing: deterministic and idempotent.
2007        let before = std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap();
2008        learn_in(&home, Some("s1"), &fake_ask, true, 50);
2009        assert_eq!(std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap(), before);
2010        // Engineers accumulate on the merged lesson.
2011        let l0 = lessons(&home.join("lessons.jsonl")).into_iter().find(|l| l.id == "Le0").unwrap();
2012        assert_eq!(l0.engineers, ["ann@x", "bob@x"]);
2013        // The same email in another case is the same engineer: not added, no join recorded.
2014        append_jsonl(&home.join("episodes.jsonl"), &at("e3", "s2", 60, "Ann@X", "flag racy again merge:Le0")).unwrap();
2015        assert_eq!(learn_in(&home, Some("s2"), &fake_ask, true, 70), (0, 1, 0));
2016        let l0 = lessons(&home.join("lessons.jsonl")).into_iter().find(|l| l.id == "Le0").unwrap();
2017        assert_eq!((l0.engineers.as_slice(), l0.joined.get("Ann@X")), (&["ann@x".to_string(), "bob@x".to_string()][..], None));
2018        let _ = std::fs::remove_dir_all(home);
2019    }
2020
2021    #[test]
2022    fn idle_sessions_settle_without_their_end_hook() {
2023        let home = temp_home("idle");
2024        for e in [at("e0", "s0", 1, "", "check TOCTOU on the flag"), at("e1", "s0", 2, "", "check against the spec")] {
2025            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
2026        }
2027        learn_in(&home, Some("s0"), &fake_ask, true, 3);
2028        // s1 and s3 never send `end`. s1 asks both and is corrected on Le0; s3 asks Le0, no correction.
2029        asked(&home, "s1", 10, &["Le0", "Le1"]);
2030        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s1", 20, "", "flag still racy merge:Le0")).unwrap();
2031        asked(&home, "s3", 5, &["Le0"]);
2032        let idle = 20 + outcome::IDLE_MS;
2033        let results = || -> Vec<(String, String, String)> {
2034            outcome::read(&home.join("outcomes.jsonl"))
2035                .into_iter()
2036                .filter(|o| o.kind != outcome::ASKED)
2037                .map(|o| (o.kind, o.session, o.lessons.join(",")))
2038                .collect()
2039        };
2040        let not = |s: &str, l: &str| (outcome::NOT_CORRECTED.to_string(), s.to_string(), l.to_string());
2041        // s2 ends a day later: its own ask settles, and idle s3; s1 not: it is still open (its state file
2042        // is fresh), so its episode is still pending.
2043        let ctx = home.join("state/s1.ctx");
2044        std::fs::create_dir_all(ctx.parent().unwrap()).unwrap();
2045        std::fs::write(&ctx, "").unwrap();
2046        asked(&home, "s2", idle - 1, &["Le1"]);
2047        learn_in(&home, Some("s2"), &fake_ask, true, idle);
2048        assert_eq!(results(), [not("s3", "Le0"), not("s2", "Le1")]);
2049        // s1 goes quiet; a plain `borg learn` folds e2 in and settles s1 too, so s1 gives both kinds of outcome.
2050        std::fs::remove_file(&ctx).unwrap();
2051        assert_eq!(learn_in(&home, None, &fake_ask, true, idle), (0, 1, 0));
2052        let corrected = (outcome::CORRECTED.to_string(), "s1".to_string(), "Le0".to_string());
2053        assert_eq!(results(), [not("s3", "Le0"), not("s2", "Le1"), corrected.clone(), not("s1", "Le1")]);
2054        // A fresh session is not settled, and re-running appends nothing.
2055        asked(&home, "s4", idle, &["Le1"]);
2056        learn_in(&home, None, &fake_ask, true, idle + 1);
2057        assert_eq!(results().len(), 4);
2058        let _ = std::fs::remove_dir_all(home);
2059    }
2060
2061    #[test]
2062    fn a_quiet_sessions_episodes_are_learned_by_another_sessions_end() {
2063        let home = temp_home("quiet");
2064        // s1 never ends; the transcript sweep added its last correction after it went quiet (sweep.rs `idle`).
2065        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s1", 10, "", "check TOCTOU on the flag")).unwrap();
2066        // s9 is busy (an episode an hour ago) and open; s2 ends now.
2067        append_jsonl(&home.join("episodes.jsonl"), &at("e1", "s9", 10 + outcome::IDLE_MS, "", "check against the spec")).unwrap();
2068        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s2", 20 + outcome::IDLE_MS, "", "no, keep the cache")).unwrap();
2069        let now = 30 + outcome::IDLE_MS;
2070        // While s1's state file is fresh it is open, and waits for its own end.
2071        let ctx = home.join("state/s1.ctx");
2072        std::fs::create_dir_all(ctx.parent().unwrap()).unwrap();
2073        std::fs::write(&ctx, "").unwrap();
2074        assert_eq!(learn_in(&home, Some("s2"), &fake_ask, true, now), (1, 0, 0), "s2's own episode only");
2075        // Quiet: s2's end learns it too; busy s9 still waits.
2076        std::fs::remove_file(&ctx).unwrap();
2077        append_jsonl(&home.join("episodes.jsonl"), &at("e3", "s3", 25 + outcome::IDLE_MS, "", "no, the other crate")).unwrap();
2078        assert_eq!(learn_in(&home, Some("s3"), &fake_ask, true, now), (2, 0, 0), "s3's own and quiet s1's");
2079        let learned: HashSet<String> = lessons(&home.join("lessons.jsonl")).into_iter().flat_map(|l| l.episodes).collect();
2080        assert!(learned.contains("e0") && !learned.contains("e1"), "{learned:?}");
2081        let _ = std::fs::remove_dir_all(home);
2082    }
2083
2084    #[test]
2085    fn no_outcomes_written_without_tracking() {
2086        let home = temp_home("off");
2087        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s0", 1, "", "check TOCTOU")).unwrap();
2088        learn_in(&home, Some("s0"), &fake_ask, true, 2);
2089        asked(&home, "s1", 10, &["Le0"]);
2090        let before = std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap();
2091        append_jsonl(&home.join("episodes.jsonl"), &at("e1", "s1", 20, "", "TOCTOU again merge:Le0")).unwrap();
2092        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, false, 30), (0, 1, 0));
2093        assert_eq!(std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap(), before);
2094        let _ = std::fs::remove_dir_all(home);
2095    }
2096
2097    #[test]
2098    fn failed_model_calls_leave_episodes_waiting_and_stop_early() {
2099        let home = temp_home("failed");
2100        for i in 0..5 {
2101            append_jsonl(&home.join("episodes.jsonl"), &at(&format!("e{i}"), "s0", i, "", &format!("check case {i}"))).unwrap();
2102        }
2103        asked(&home, "s0", 0, &["Lx"]);
2104        let calls = std::cell::Cell::new(0);
2105        let down = |_: &str| -> Option<Value> {
2106            calls.set(calls.get() + 1);
2107            None
2108        };
2109        // Quota hit: nothing is marked "not a lesson", the run gives up after MAX_FAILURES calls,
2110        // and the session is not settled while its episodes wait.
2111        assert_eq!(learn_in(&home, Some("s0"), &down, true, 1 + outcome::IDLE_MS), (0, 0, 5));
2112        assert_eq!(calls.get(), MAX_FAILURES);
2113        assert!(!home.join("episodes-not-lessons.txt").exists());
2114        assert!(outcome::read(&home.join("outcomes.jsonl")).iter().all(|o| o.kind == outcome::ASKED));
2115        // The model is back: the next run retries every episode.
2116        assert_eq!(learn_in(&home, Some("s0"), &fake_ask, true, 2 + outcome::IDLE_MS), (5, 0, 0));
2117        let _ = std::fs::remove_dir_all(home);
2118    }
2119
2120    #[test]
2121    fn area_and_supersedes_come_from_the_same_call() {
2122        let lib = vec![
2123            generalise(&ep("e1", "use a lock here"), &[], &|_| {
2124                Some(json!({"is_lesson": true, "question": "Is the flag guarded by a lock?", "situations": ["flag across threads"],
2125                    "consequence": "race", "same_as": "", "area": "Concurrency", "supersedes": ["Lnope"]}))
2126            })
2127            .unwrap()
2128            .unwrap(),
2129        ];
2130        assert_eq!(lib[0].area, "concurrency", "case-insensitive; normalised");
2131        assert!(lib[0].supersedes.is_empty(), "an id the model was not shown is dropped");
2132        // A lesson without an area (older store, or a model that ignores it) is "other".
2133        let old: Lesson = serde_json::from_str(
2134            r#"{"id":"L","origin_ms":1,"repo":"r","question":"q","situations":[],"consequence":"c",
2135            "support":1,"episodes":[],"history":[],"version":1}"#,
2136        )
2137        .unwrap();
2138        assert_eq!((old.area.as_str(), old.supersedes.len()), ("other", 0));
2139        let id = lib[0].id.clone();
2140        let reversed = generalise(&ep("e2", "no, the lock is wrong here, use the atomic flag"), &lib, &move |_| {
2141            Some(json!({"is_lesson": true, "question": "Is a lock-free atomic enough for the flag?", "situations": ["flag across threads"],
2142                "consequence": "lock contention", "same_as": "", "area": "made-up", "supersedes": [id.clone()]}))
2143        })
2144        .unwrap()
2145        .unwrap();
2146        assert_eq!((reversed.area.as_str(), reversed.supersedes.clone()), ("other", vec![lib[0].id.clone()]));
2147        assert!(!serde_json::to_string(&lib[0]).unwrap().contains("supersedes"), "empty supersedes stays off the line");
2148        // The merge target is never superseded; a merge keeps what the old version superseded.
2149        let (rid, lid) = (reversed.id.clone(), lib[0].id.clone());
2150        let merged = generalise(&ep("e3", "again: atomic, not a lock"), &[lib[0].clone(), reversed.clone()], &move |_| {
2151            Some(json!({"is_lesson": true, "question": "Is a lock-free atomic enough?", "situations": ["flag across threads"],
2152                "consequence": "lock contention", "same_as": rid.clone(), "area": "concurrency", "supersedes": [rid.clone(), lid.clone()]}))
2153        })
2154        .unwrap()
2155        .unwrap();
2156        assert_eq!((merged.id.as_str(), merged.version, merged.supersedes.clone()), (reversed.id.as_str(), 2, vec![lib[0].id.clone()]));
2157    }
2158
2159    #[test]
2160    fn new_lesson_then_merge_keeps_history() {
2161        let first = generalise(&ep("e1", "carefully check TOCTOU on the atomic flags"), &[], &|_| {
2162            Some(json!({"is_lesson": true, "question": "Is every check-then-act on a shared flag TOCTOU-safe?",
2163                "situations": ["check-then-act on a shared mutable flag across threads"], "consequence": "race", "same_as": ""}))
2164        })
2165        .unwrap()
2166        .unwrap();
2167        assert_eq!((first.version, first.support), (1, 1));
2168        let id = first.id.clone();
2169        let merged = generalise(&ep("e2", "again: the closed flag check is racy"), std::slice::from_ref(&first), &move |p| {
2170            assert!(p.contains(&id), "the similar lesson must be offered for merging");
2171            Some(json!({"is_lesson": true, "question": "Is each check-then-act on shared flags atomic or harmless on race?",
2172                "situations": ["check-then-act on a shared mutable flag across threads"], "consequence": "race", "same_as": id}))
2173        })
2174        .unwrap()
2175        .unwrap();
2176        assert_eq!((merged.id.as_str(), merged.version, merged.support, merged.history.len()), (first.id.as_str(), 2, 2, 1));
2177        let skipped =
2178            generalise(&ep("e3", "stop"), &[], &|_| Some(json!({"is_lesson": false, "question": "", "situations": [], "consequence": "", "same_as": ""})));
2179        assert!(matches!(skipped, Ok(None)), "a verdict: not a lesson");
2180        assert_eq!(generalise(&ep("e4", "no, the lock"), &[], &|_| None).map(|_| ()), Err(AskFailed), "no answer is no verdict");
2181        let malformed = generalise(&ep("e5", "no, the lock"), &[], &|_| Some(json!({"error": "rate limited"})));
2182        assert_eq!(malformed.map(|_| ()), Err(AskFailed));
2183    }
2184}