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.
726pub(crate) fn 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            // Its settle's time: after a verdict the session-end judge gives here.
1171            let mut at = now;
1172            // An idle session's end hook never ran: the session-end judge (hook.rs `judge_session`) gives
1173            // its open deliveries their last verdict here, before its tests are credited and the rest is
1174            // settled, as `borg learn --session` does for the session that ended (main.rs `learn_cmd`).
1175            // It writes to the hooks' store and reads their state file, so only for those; what it
1176            // judged it marks (`END_JUDGED`), so never twice.
1177            if Some(s.as_str()) != session && home == self::home().as_path() && ctx(s) == crate::hook::state_file(s) && crate::hook::judge_session(s) > 0 {
1178                outcomes = outcome::read(&outcomes_path);
1179                at = at.max(now_ms());
1180            }
1181            // The session's own tests that went green after an ask (hook.rs `capture_test`) credit the
1182            // lessons asked, once each, as it settles.
1183            if test_credit() {
1184                let tests = std::fs::read_to_string(state.join(format!("{}.tests", crate::notes::safe(s)))).unwrap_or_default();
1185                for o in outcome::tested(&outcomes, s, &tests) {
1186                    let _ = outcome::append(&outcomes_path, &o);
1187                    outcomes.push(o);
1188                }
1189            }
1190            // Each lesson left without a verdict says why (hook.rs `unjudged`, from the state file):
1191            // censored, never an ignore (memory.rs).
1192            let why = crate::hook::unjudged(&std::fs::read_to_string(ctx(s)).unwrap_or_default());
1193            for o in outcome::settle_with(&outcomes, s, at, &|l| why.get(l).copied().unwrap_or(outcome::UNJUDGED_NO_CALL)) {
1194                let _ = outcome::append(&outcomes_path, &o);
1195                outcomes.push(o);
1196            }
1197        }
1198    }
1199    (new, merged, failed)
1200}
1201
1202#[cfg(test)]
1203mod tests {
1204    use super::*;
1205
1206    #[test]
1207    fn concurrent_jsonl_appends_keep_every_line() {
1208        let dir = std::env::temp_dir().join(format!("borg-learn-append-{}", std::process::id()));
1209        let _ = std::fs::remove_dir_all(&dir);
1210        let p = dir.join("episodes.jsonl");
1211        let (writers, each) = (8, 2000);
1212        std::thread::scope(|scope| {
1213            for w in 0..writers {
1214                let p = &p;
1215                scope.spawn(move || (0..each).for_each(|i| append_jsonl(p, &serde_json::json!({"w": w, "i": i})).unwrap()));
1216            }
1217        });
1218        assert_eq!(read_jsonl::<Value>(&p).len(), writers * each);
1219        let _ = std::fs::remove_dir_all(dir);
1220    }
1221
1222    #[test]
1223    fn a_regret_is_asked_with_its_own_prompt_and_the_shared_rules() {
1224        let r = regret::Regret {
1225            decision_task: "read the flag in b".into(),
1226            fix_subject: "fix: take the lock".into(),
1227            signals: vec!["subject".into()],
1228            age_days: 3,
1229            ..regret::Regret::default()
1230        };
1231        let e = Episode {
1232            kind: regret::KIND.into(),
1233            regret: Some(r),
1234            task: "make the flag safe".into(),
1235            ..ep("Rdddd-ffff", "Fixed later (3d, subject): fix: take the lock")
1236        };
1237        let shown = std::cell::RefCell::new(String::new());
1238        let l = generalise(&e, &[], &|p| {
1239            *shown.borrow_mut() = p.to_string();
1240            Some(json!({"is_lesson": true, "question": "Before reading a shared flag without a lock, has a concurrent writer been considered?",
1241                "situations": ["reading a shared flag across threads"], "consequence": "a race", "same_as": "", "area": "concurrency", "supersedes": []}))
1242        })
1243        .unwrap()
1244        .unwrap();
1245        let p = shown.into_inner();
1246        assert!(p.starts_with("A coding agent made a decision in an earlier session") && p.contains("3 days later"), "{p}");
1247        for part in [
1248            regret::neutral(REACH_RULES).as_str(),
1249            regret::FIELDS,
1250            AREA,
1251            regret::neutral(MERGE_RULES).as_str(),
1252            "## The decision (task)\nread the flag in b",
1253            "## The fix (subject, task)\nfix: take the lock\nmake the flag safe",
1254        ] {
1255            assert!(p.contains(part), "{part}");
1256        }
1257        assert!(!p.contains("## Engineer's correction") && !p.contains(OPENING) && !p.contains("correction"), "{p}");
1258        assert_eq!((l.id.as_str(), l.area.as_str(), l.episodes.as_slice()), ("LRdddd-ffff", "concurrency", &["Rdddd-ffff".to_string()][..]));
1259        // A correction keeps its prompt; a kind without its regret is asked as a correction.
1260        assert!(episode_prompt(&ep("e1", "no, the lock"), &[]).starts_with(OPENING));
1261        assert!(episode_prompt(&Episode { kind: regret::KIND.into(), ..ep("e2", "no") }, &[]).starts_with(OPENING));
1262    }
1263
1264    /// The injected model for vetoes: like `fake_ask` on the veto's section, plus `invariant:<rest>`.
1265    fn fake_veto_ask(p: &str) -> Option<Value> {
1266        let reason = p.split("## Engineer's veto\n").nth(1)?.lines().next()?;
1267        let after = |k: &str| reason.split(k).nth(1).and_then(|r| r.split_whitespace().next()).unwrap_or("").to_string();
1268        let invariant = reason.split("invariant:").nth(1).unwrap_or("").trim().to_string();
1269        Some(json!({"is_lesson": true, "question": format!("Q {reason}"), "situations": [], "consequence": "c",
1270            "same_as": after("merge:"), "supersedes": [], "invariant": invariant}))
1271    }
1272
1273    fn veto(id: &str, session: &str, ms: i64, reason: &str) -> Episode {
1274        Episode { kind: crate::veto::KIND.into(), ..at(id, session, ms, "ann@x", reason) }
1275    }
1276
1277    #[test]
1278    fn a_veto_is_asked_with_its_own_prompt_and_schema() {
1279        let p = episode_prompt(&veto("no-s-1", "s", 1, "never read the commit log for merges"), &[]);
1280        assert!(p.starts_with(crate::veto::OPENING), "{p}");
1281        for part in [
1282            "## Engineer's veto\nnever read the commit log for merges",
1283            crate::veto::INVARIANT,
1284            REACH_RULES,
1285            FIELDS,
1286            MERGE_RULES,
1287            "## Task the agent had\nplan the relay",
1288        ] {
1289            assert!(p.contains(part), "{part}");
1290        }
1291        assert!(!p.contains(OPENING) && !p.contains("## Engineer's correction"));
1292        let without = episode_prompt(&Episode { agent: String::new(), ..veto("no-s-2", "s", 1, "no") }, &[]);
1293        assert!(without.contains("## What the agent proposed (excerpt)\n(not available)"), "{without}");
1294        assert!(schema_for(&p)["required"].as_array().unwrap().contains(&json!("invariant")));
1295        assert!(schema_for(&p)["properties"]["invariant"].is_object());
1296        let correction = episode_prompt(&ep("e1", "no, the lock"), &[]);
1297        assert_eq!(schema_for(&correction), schema(), "a correction's call is unchanged");
1298        // The invariant comes back with the lesson; a correction's answer has none.
1299        let (l, inv) =
1300            generalise_with(&veto("no-s-3", "s", 1, "merge lookups invariant: lookups go through the review API"), &[], &fake_veto_ask).unwrap().unwrap();
1301        assert_eq!((l.id.as_str(), inv.as_str()), ("Lno-s-3", "lookups go through the review API"));
1302        let (_, none) = generalise_with(&ep("e2", "no, the lock merge:x"), &[], &fake_ask).unwrap().unwrap();
1303        assert!(none.is_empty());
1304    }
1305
1306    #[test]
1307    fn a_veto_is_learned_at_any_sessions_end_and_never_counted_as_a_correction() {
1308        let home = temp_home("veto-any");
1309        crate::learn::record_episode_in(&home, &veto("no-s1-1", "s1", 1, "never read the commit log for merges")).unwrap();
1310        append_jsonl(&home.join("episodes.jsonl"), &at("e1", "s1", 2, "ann@x", "a correction of s1")).unwrap();
1311        assert!(!crate::stats::events(&home).iter().any(|e| e.kind == crate::stats::CORRECTION), "count_correction skips a veto");
1312        // s2 ends: the veto of s1 is learned, s1's correction waits for its own session.
1313        assert_eq!(learn_in(&home, Some("s2"), &fake_veto_ask, true, 3), (1, 0, 0));
1314        let ls = lessons(&home.join("lessons.jsonl"));
1315        assert_eq!(ls.iter().map(|l| l.id.as_str()).collect::<Vec<_>>(), ["Lno-s1-1"]);
1316        let news: Vec<crate::stats::Event> = crate::stats::events(&home).into_iter().filter(|e| e.kind == crate::stats::LESSON_NEW).collect();
1317        assert_eq!(news[0].why, "veto");
1318        let _ = std::fs::remove_dir_all(home);
1319    }
1320
1321    #[test]
1322    fn a_veto_merged_into_an_earlier_vetos_lesson_is_a_repeat() {
1323        let home = temp_home("veto-repeat");
1324        let repeats = |home: &Path| crate::stats::events(home).iter().filter(|e| e.kind == crate::stats::VETO_REPEAT).count();
1325        // A lesson from a correction, then a veto merged into it: no repeat (the first "no").
1326        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "use the lock on the flag")).unwrap();
1327        append_jsonl(&home.join("episodes.jsonl"), &veto("no-s1-2", "s1", 2, "the lock again merge:Le0")).unwrap();
1328        // Le0 was asked in s1 before the veto: the veto credits it (veto.rs), learning never adds a correction.
1329        let asked = outcome::Outcome { kind: outcome::ASKED.into(), session: "s1".into(), lessons: vec!["Le0".into()], ms: 1, ..Default::default() };
1330        outcome::append(&home.join("outcomes.jsonl"), &asked).unwrap();
1331        learn_in(&home, None, &|p| if p.starts_with(crate::veto::OPENING) { fake_veto_ask(p) } else { fake_ask(p) }, true, 3);
1332        assert_eq!(repeats(&home), 0);
1333        let results = outcome::read(&home.join("outcomes.jsonl"));
1334        assert!(!results.iter().any(|o| o.kind == outcome::CORRECTED || o.kind == outcome::MISSED), "{results:?}");
1335        assert!(!crate::stats::events(&home).iter().any(|e| e.kind == crate::stats::CORRECTED));
1336        // A second veto with the same reason: merged into the lesson a veto is part of.
1337        append_jsonl(&home.join("episodes.jsonl"), &veto("no-s2-4", "s2", 4, "the lock, third time merge:Le0")).unwrap();
1338        assert_eq!(learn_in(&home, Some("s2"), &fake_veto_ask, true, 5), (0, 1, 0));
1339        assert_eq!(repeats(&home), 1);
1340        let r = crate::stats::events(&home).into_iter().find(|e| e.kind == crate::stats::VETO_REPEAT).unwrap();
1341        assert_eq!((r.session.as_str(), r.lessons.clone()), ("s2", vec!["Le0".to_string()]));
1342        assert_eq!(r.ms, 4, "dated when the veto was said, the week of its own veto");
1343        let _ = std::fs::remove_dir_all(home);
1344    }
1345
1346    #[test]
1347    fn an_invariant_of_a_veto_becomes_a_proposed_constraint_never_a_constraint() {
1348        let home = temp_home("veto-invariant");
1349        append_jsonl(&home.join("episodes.jsonl"), &veto("no-s1-1", "s1", 1, "no commit log invariant: merge lookups use the review API")).unwrap();
1350        append_jsonl(&home.join("episodes.jsonl"), &veto("no-s1-2", "s1", 2, "not now, later")).unwrap();
1351        learn_in(&home, Some("s1"), &fake_veto_ask, true, 3);
1352        let queue = crate::queen::entries(&home);
1353        assert_eq!(queue.len(), 1, "only the veto that named an invariant");
1354        assert_eq!((queue[0].kind, queue[0].session.as_str()), (crate::queen::Kind::Constraint, "s1"));
1355        assert!(
1356            queue[0].evidence.contains(&"invariant: merge lookups use the review API".to_string())
1357                && queue[0].evidence.contains(&"lesson Lno-s1-1".to_string())
1358        );
1359        assert!(!crate::veto::constraints_path(&home).exists());
1360        // A personal lesson never proposes; nor does one without an invariant.
1361        let l = Lesson { id: "L".into(), ..Lesson::default() };
1362        let personal = crate::reach::Placed::Personal { lesson: Box::new(l.clone()), withdraw: None };
1363        assert!(proposes(&crate::reach::Placed::Here(Box::new(l)), "x") && !proposes(&personal, "x"));
1364        assert!(!proposes(&crate::reach::Placed::Here(Box::default()), " "));
1365        let _ = std::fs::remove_dir_all(home);
1366    }
1367
1368    #[test]
1369    fn detects_corrections_and_rejections() {
1370        assert!(is_correction("double check against spec document"));
1371        assert!(is_correction("No, let's not move this into the net"));
1372        assert!(!is_correction("let's pick up the gpt live plan"));
1373        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";
1374        assert_eq!(rejection(err).as_deref(), Some("carefully check TOCTOU"));
1375        assert_eq!(rejection("Exit code 1\nTraceback"), None);
1376        // omp's refusals carry no words; the reason follows as the next prompt.
1377        assert!(denied("Tool call denied by user: bash"));
1378        assert!(denied("Tool call rejected by user (edit)"));
1379        assert!(denied(
1380            "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."
1381        ));
1382        assert!(!denied(err), "a rejection with words is captured directly");
1383        assert!(!denied("Exit code 1\nTool call denied by user: bash"), "only the harness's own message, not tool output");
1384    }
1385
1386    #[test]
1387    fn known_holds_an_id_the_same_words_or_a_prompt_moments_apart() {
1388        let at = |id: &str, ms: i64, tool: Option<&str>, said: &str| Episode {
1389            id: id.into(),
1390            ms,
1391            session: "s1".into(),
1392            rejected_tool: tool.map(String::from),
1393            correction: said.into(),
1394            ..Episode::default()
1395        };
1396        let mut k = Known::default();
1397        // What the hook recorded: a rejection at capture time, a prompt.
1398        k.add(&at("s1-100000", 100_000, Some("Edit {}"), "use backoff,\n  not a fixed sleep"));
1399        k.add(&at("s1-200000", 200_000, None, "no, the other crate"));
1400        assert!(k.holds(&at("s1-Ttoolu_1", 70_000, Some("Edit {}"), "use backoff, not a fixed sleep")), "same words, whitespace aside");
1401        assert!(k.holds(&at("s1-100000", 1, None, "anything")), "same id");
1402        assert!(k.holds(&at("s1-201500", 201_500, None, "no, the other crate!")), "a prompt within SAME_MS");
1403        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");
1404        assert!(!k.holds(&Episode { via: ANSWER.into(), ..at("s1-Ttoolu_3", 200_500, None, "Exponential") }), "nor does an answer");
1405        assert!(!k.holds(&Episode { session: "s2".into(), ..at("s2-Tx", 100_000, Some("Edit {}"), "use backoff, not a fixed sleep") }));
1406        // Two calls the transcript named are two events, though their words match: a second rejection
1407        // with the same words, the same pick to another question.
1408        let mut t = Known::default();
1409        t.add(&at("s1-Ttoolu_4", 300_000, Some("Edit {}"), "keep it in the relay crate"));
1410        t.add(&Episode { via: ANSWER.into(), ..at("s1-Ttoolu_5", 400_000, None, "Create, no parent") });
1411        assert!(!t.holds(&at("s1-Ttoolu_6", 900_000, Some("Edit {}"), "keep it in the relay crate")), "another rejected call");
1412        assert!(!t.holds(&Episode { via: ANSWER.into(), ..at("s1-Ttoolu_7", 900_000, None, "Create, no parent") }), "another question");
1413        // An answer is never matched to a hook's episode by words.
1414        assert!(!k.holds(&Episode { via: ANSWER.into(), ..at("s1-Ttoolu_8", 900_000, None, "no, the other crate") }));
1415        assert_eq!(transcript_id("abcdefghij", "toolu_9", 5), "abcdefgh-Ttoolu_9");
1416        assert_eq!(transcript_id("abcdefghij", "", 5), "abcdefgh-5");
1417
1418        // record_new_in appends once, and once within one batch.
1419        let store = std::env::temp_dir().join(format!("borg-known-{}", std::process::id()));
1420        let _ = std::fs::remove_dir_all(&store);
1421        let e = at("s1-Tq", 5, None, "Exponential");
1422        let mut readied = 0;
1423        assert_eq!(record_new_in(&store, vec![e.clone(), e.clone()], |_| readied += 1).unwrap().len(), 1);
1424        assert!(record_new_in(&store, vec![e.clone()], |_| panic!("a held episode is not readied")).unwrap().is_empty());
1425        assert_eq!(readied, 1);
1426        assert!(Known::read(&store).holds(&e));
1427        assert_eq!(read_jsonl::<Episode>(&store.join("episodes.jsonl")).len(), 1);
1428        let _ = std::fs::remove_dir_all(&store);
1429    }
1430
1431    #[test]
1432    fn writers_at_once_append_an_episode_once() {
1433        let store = std::env::temp_dir().join(format!("borg-known-race-{}", std::process::id()));
1434        let _ = std::fs::remove_dir_all(&store);
1435        let e = Episode { id: "s1-Tx".into(), session: "s1".into(), correction: "keep the cache dir".into(), ..Episode::default() };
1436        let start = std::sync::Barrier::new(8);
1437        std::thread::scope(|s| {
1438            for _ in 0..8 {
1439                s.spawn(|| {
1440                    start.wait();
1441                    record_new_in(&store, vec![e.clone()], |_| std::thread::yield_now()).unwrap();
1442                });
1443            }
1444        });
1445        assert_eq!(read_jsonl::<Episode>(&store.join("episodes.jsonl")).len(), 1);
1446        let _ = std::fs::remove_dir_all(&store);
1447    }
1448
1449    #[test]
1450    fn an_answer_is_asked_as_an_answer_and_counted_as_one() {
1451        let answer = Episode { via: ANSWER.into(), agent: "Which backoff?\n  options: Exponential | Linear".into(), ..ep("a1", "Exponential") };
1452        let p = episode_prompt(&answer, &[]);
1453        assert!(p.contains(ANSWERED) && p.contains("## Engineer's correction\nExponential"), "{p}");
1454        assert!(!episode_prompt(&ep("e1", "no"), &[]).contains(ANSWERED));
1455        let store = std::env::temp_dir().join(format!("borg-answer-count-{}", std::process::id()));
1456        let _ = std::fs::remove_dir_all(&store);
1457        count_correction(&store, &answer);
1458        let ev = crate::stats::live(&store);
1459        assert_eq!((ev.len(), ev[0].why.as_str()), (1, ANSWER));
1460        let _ = std::fs::remove_dir_all(&store);
1461    }
1462
1463    fn ep(id: &str, correction: &str) -> Episode {
1464        Episode {
1465            id: id.into(),
1466            ms: 1,
1467            repo: "r".into(),
1468            session: "s".into(),
1469            task: "plan the relay".into(),
1470            agent: "one ReentrantLock guards delivery".into(),
1471            rejected_tool: None,
1472            correction: correction.into(),
1473            ..Episode::default()
1474        }
1475    }
1476
1477    /// The injected model: `same_as` is the lesson id after "merge:" in the correction, if any, and
1478    /// `supersedes` the one after "supersede:".
1479    fn fake_ask(p: &str) -> Option<Value> {
1480        let correction = p.split("## Engineer's correction\n").nth(1)?.lines().next()?;
1481        let after = |k: &str| correction.split(k).nth(1).and_then(|r| r.split_whitespace().next()).unwrap_or("").to_string();
1482        let supersedes: Vec<String> = Some(after("supersede:")).filter(|x| !x.is_empty()).into_iter().collect();
1483        Some(json!({"is_lesson": true, "question": format!("Q {correction}"), "situations": [], "consequence": "c",
1484            "same_as": after("merge:"), "supersedes": supersedes}))
1485    }
1486
1487    fn results(home: &Path) -> Vec<(String, String, String)> {
1488        outcome::read(&home.join("outcomes.jsonl")).into_iter().filter(|o| o.kind != outcome::ASKED).map(|o| (o.kind, o.session, o.lessons.join(","))).collect()
1489    }
1490
1491    #[test]
1492    fn every_model_call_is_reported_with_its_place_and_verdict() {
1493        let home = temp_home("progress");
1494        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")] {
1495            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1496        }
1497        let mut steps = Vec::new();
1498        learn_in_reporting(&home, None, &fake_ask, false, 3, &mut |st| steps.push((st.done, st.total, st.verdict.split(':').next().unwrap().to_string())));
1499        assert_eq!(steps, [(1, 2, "new lesson Le0".to_string()), (2, 2, "merged into Le0".to_string())]);
1500        // A second run has nothing left to ask, so it reports nothing.
1501        steps.clear();
1502        learn_in_reporting(&home, None, &fake_ask, false, 4, &mut |st| steps.push((st.done, st.total, String::new())));
1503        assert!(steps.is_empty());
1504        let _ = std::fs::remove_dir_all(home);
1505    }
1506
1507    #[test]
1508    fn a_lesson_contradicted_after_asking_is_corrected_not_followed() {
1509        let home = temp_home("contradicted");
1510        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "use the lock on the flag")).unwrap();
1511        learn_in(&home, Some("s0"), &fake_ask, true, 2);
1512        // s1 asks Le0, then the engineer contradicts it: a new lesson superseding Le0.
1513        asked(&home, "s1", 10, &["Le0"]);
1514        append_jsonl(&home.join("episodes.jsonl"), &at("e1", "s1", 20, "bob@x", "no, CAS on the flag supersede:Le0")).unwrap();
1515        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, true, 30), (1, 0, 0));
1516        assert_eq!(results(&home), [(outcome::CORRECTED.into(), "s1".into(), "Le0".into())]);
1517        let _ = std::fs::remove_dir_all(home);
1518    }
1519
1520    #[test]
1521    fn a_correction_of_a_lesson_that_applied_but_was_not_asked_is_a_miss() {
1522        let home = temp_home("missed");
1523        for e in [at("e0", "s0", 1, "ann@x", "use the lock on the flag"), at("e1", "s0", 2, "bob@x", "retry with jitter")] {
1524            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1525        }
1526        learn_in(&home, Some("s0"), &fake_ask, true, 3);
1527        // s1's check graded both as applying and chose to ask only Le1; the engineer then corrects the
1528        // drone on Le0's concern: Le0 was needed and not asked.
1529        let graded = outcome::Outcome {
1530            kind: outcome::GRADED.into(),
1531            session: "s1".into(),
1532            lessons: vec!["Le0".into(), "Le1".into()],
1533            ms: 10,
1534            repo: "r".into(),
1535            grades: vec![2, 3],
1536            ranks: vec![0, 1],
1537            applied: 2,
1538            chosen: vec!["Le1".into()],
1539            ..Default::default()
1540        };
1541        outcome::append(&home.join("outcomes.jsonl"), &graded).unwrap();
1542        asked(&home, "s1", 11, &["Le1"]);
1543        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s1", 20, "cy@x", "no, the lock on the flag merge:Le0")).unwrap();
1544        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, true, 30), (0, 1, 0));
1545        let r = results(&home);
1546        assert!(r.contains(&(outcome::MISSED.into(), "s1".into(), "Le0".into())), "{r:?}");
1547        // The asked one is not a miss; a second run records nothing new.
1548        assert!(!r.iter().any(|(k, _, l)| k == outcome::MISSED && l == "Le1"), "{r:?}");
1549        learn_in(&home, Some("s1"), &fake_ask, true, 40);
1550        assert_eq!(results(&home).iter().filter(|(k, ..)| k == outcome::MISSED).count(), 1);
1551        let _ = std::fs::remove_dir_all(home);
1552    }
1553
1554    #[test]
1555    fn siding_with_one_side_of_a_disagreement_corrects_the_other() {
1556        let home = temp_home("sides");
1557        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")] {
1558            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1559        }
1560        learn_in(&home, Some("s0"), &fake_ask, true, 3);
1561        // The conscience rendered Le0 and Le1 as one disagreement; the engineer sides with Le0.
1562        let o = outcome::Outcome {
1563            kind: outcome::ASKED.into(),
1564            session: "s1".into(),
1565            lessons: vec!["Le0".into(), "Le1".into()],
1566            ms: 10,
1567            repo: "r".into(),
1568            groups: vec![vec!["Le0".into(), "Le1".into()]],
1569            ..Default::default()
1570        };
1571        outcome::append(&home.join("outcomes.jsonl"), &o).unwrap();
1572        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s1", 20, "cy@x", "no, the lock on the flag merge:Le0")).unwrap();
1573        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, true, 30), (0, 1, 0));
1574        assert_eq!(results(&home), [(outcome::CORRECTED.into(), "s1".into(), "Le1".into()), (outcome::NOT_CORRECTED.into(), "s1".into(), "Le0".into())]);
1575        // cy joined Le0 at the correction; ann's earlier evidence is not his.
1576        let l0 = lessons(&home.join("lessons.jsonl")).into_iter().find(|l| l.id == "Le0").unwrap();
1577        assert_eq!(l0.joined.get("cy@x"), Some(&20));
1578        let _ = std::fs::remove_dir_all(home);
1579    }
1580
1581    #[test]
1582    fn the_learn_prompt_offers_at_most_merge_candidates_lessons_for_merging() {
1583        let lib: Vec<Lesson> = (0..MERGE_CANDIDATES + 2)
1584            .map(|i| Lesson {
1585                id: format!("L{i}"),
1586                origin_ms: i as i64,
1587                question: format!("Is the ReentrantLock held while delivery {i} runs?"),
1588                consequence: "c".into(),
1589                version: 1,
1590                ..Lesson::default()
1591            })
1592            .collect();
1593        let e = ep("e1", "no, the ReentrantLock must guard delivery");
1594        let offered = similar(&e, &lib);
1595        assert_eq!(offered.len(), MERGE_CANDIDATES, "every lesson matches; the prompt offers the best few");
1596        let prompt = std::cell::RefCell::new(String::new());
1597        let _ = generalise(&e, &lib, &|p| {
1598            *prompt.borrow_mut() = p.to_string();
1599            None
1600        });
1601        let named = lib.iter().filter(|l| prompt.borrow().contains(&format!("[{}]", l.id))).count();
1602        assert_eq!(named, MERGE_CANDIDATES, "{}", prompt.borrow());
1603    }
1604
1605    #[test]
1606    fn a_superseded_lesson_is_not_a_merge_target_its_successor_is_shown() {
1607        let lesson = |id: &str, ms: i64, q: &str, sup: &[&str]| Lesson {
1608            id: id.into(),
1609            origin_ms: ms,
1610            repo: "r".into(),
1611            question: q.into(),
1612            situations: vec![],
1613            consequence: "c".into(),
1614            support: 1,
1615            episodes: vec![],
1616            history: vec![],
1617            version: 1,
1618            engineers: vec!["ann@x".into()],
1619            joined: Default::default(),
1620            area: "concurrency".into(),
1621            supersedes: sup.iter().map(|s| s.to_string()).collect(),
1622            source: String::new(),
1623            scope: vec![],
1624            overrides: String::new(),
1625            origin: String::new(),
1626            facets: vec![],
1627            reach: String::new(),
1628        };
1629        let lib = [lesson("L0", 1, "Is the closed flag guarded by the ReentrantLock?", &[]), lesson("L1", 2, "Would a CAS suffice?", &["L0"])];
1630        // ann reverts to the lock: the model only sees L1 (in L0's place), contradicts it, and the
1631        // restored view becomes a new lesson that supersedes L1 and is asked again.
1632        let shown = std::cell::RefCell::new(String::new());
1633        let back = generalise(&ep("e9", "no, guard the closed flag with the ReentrantLock"), &lib, &|p| {
1634            *shown.borrow_mut() = p.to_string();
1635            Some(json!({"is_lesson": true, "question": "Is the closed flag guarded by the ReentrantLock?", "situations": [],
1636                "consequence": "c", "same_as": "L0", "area": "concurrency", "supersedes": ["L1"]}))
1637        })
1638        .unwrap()
1639        .unwrap();
1640        let shown = shown.into_inner();
1641        assert!(shown.contains("[L1]") && !shown.contains("[L0]"), "{shown}");
1642        assert_eq!((back.version, back.supersedes.clone()), (1, vec!["L1".to_string()]), "same_as on a hidden lesson is no merge");
1643        let all: Vec<Challenge> = lib
1644            .iter()
1645            .chain([&back])
1646            .map(|l| Challenge {
1647                id: l.id.clone(),
1648                origin_ms: l.origin_ms,
1649                question: l.question.clone(),
1650                engineers: l.engineers.clone(),
1651                supersedes: l.supersedes.clone(),
1652                ..Default::default()
1653            })
1654            .collect();
1655        assert_eq!(trust::successors(&all).get("L0").map(String::as_str), Some(back.id.as_str()));
1656    }
1657
1658    /// `fake_ask`, judging a correction that says "mine only" personal.
1659    fn fake_personal(p: &str) -> Option<Value> {
1660        let mut v = fake_ask(p)?;
1661        if p.split("## Engineer's correction\n").nth(1)?.lines().next()?.contains("mine only") {
1662            v["reach"] = json!(crate::reach::PERSONAL);
1663        }
1664        Some(v)
1665    }
1666
1667    #[test]
1668    fn a_personal_lesson_stays_in_its_collective_is_learned_once_and_delivered_only_there() {
1669        let base = temp_home("personal");
1670        let (work, oss) = (crate::collective::store(&base, "work"), crate::collective::store(&base, "oss"));
1671        std::fs::create_dir_all(&oss).unwrap();
1672        append_jsonl(&work.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "no co-author trailer, mine only")).unwrap();
1673        let calls = std::cell::Cell::new(0);
1674        let ask = |p: &str| {
1675            calls.set(calls.get() + 1);
1676            fake_personal(p)
1677        };
1678        assert_eq!(learn_in(&work, None, &ask, false, 3), (1, 0, 0));
1679        let personal = crate::reach::personal_lessons(&work);
1680        assert_eq!(personal.iter().map(|l| (l.id.as_str(), l.reach.as_str())).collect::<Vec<_>>(), [("Le0", crate::reach::PERSONAL)]);
1681        assert!(lessons(&work.join("lessons.jsonl")).is_empty(), "nothing in the team's lessons");
1682        assert_eq!(std::fs::read_dir(base.join("collectives")).unwrap().count(), 2, "no other store written");
1683        assert!(!oss.join("lessons.jsonl").exists() && !crate::reach::personal_path(&oss).exists());
1684        // Learned once: the second run finds its episode done and asks nothing.
1685        assert_eq!(learn_in(&work, None, &ask, false, 4), (0, 0, 0));
1686        assert_eq!(calls.get(), 1);
1687        // A later correction merging into it stays personal, whatever its own verdict: a merge never widens.
1688        append_jsonl(&work.join("episodes.jsonl"), &at("e1", "s1", 5, "ann@x", "the trailer again merge:Le0")).unwrap();
1689        assert_eq!(learn_in(&work, None, &ask, false, 6), (0, 1, 0));
1690        assert_eq!(crate::reach::personal_lessons(&work)[0].version, 2);
1691        assert!(lessons(&work.join("lessons.jsonl")).is_empty());
1692        assert_eq!(learned_episodes(&work), ["e0".to_string(), "e1".to_string()].into_iter().collect());
1693        // Delivered in this collective's sessions, as a team lesson for this engineer; in another
1694        // collective's never, nor in the team's own view of the store.
1695        let aliases = crate::collective::Aliases::default();
1696        let here = crate::conscience::load_store_with(&work.join("lessons.jsonl"), None, &aliases);
1697        assert!(here.iter().any(|c| c.id == "Le0" && crate::reach::deliverable(c, &["r".into()])), "{here:?}");
1698        assert!(crate::conscience::load_store_with(&oss.join("lessons.jsonl"), None, &aliases).is_empty());
1699        assert!(crate::conscience::load_with(&work.join("lessons.jsonl"), None, &aliases).is_empty());
1700        // Asked beside a team lesson: the team's synced logs name the team lesson only, never the
1701        // personal one (its id, when, which repo).
1702        for id in ["Le0", "Lteam"] {
1703            let o =
1704                outcome::Outcome { kind: outcome::ASKED.into(), session: "s9".into(), lessons: vec![id.into()], ms: 9, repo: "r".into(), ..Default::default() };
1705            outcome::append(&work.join("outcomes.jsonl"), &o).unwrap();
1706        }
1707        crate::stats::count(&work, crate::stats::LESSON_NEW, "s9", |ev| ev.lessons = vec!["Lteam".into()]);
1708        assert!(outcome::publish(&work) > 0 && crate::stats::rollup(&work) > 0);
1709        for f in [outcome::TEAM_FILE, "stats.jsonl"] {
1710            let text = std::fs::read_to_string(work.join(f)).unwrap();
1711            assert!(text.contains("Lteam") && !text.contains("Le0"), "{f}: {text}");
1712        }
1713        let _ = std::fs::remove_dir_all(base);
1714    }
1715
1716    #[test]
1717    fn a_personal_lesson_replaces_its_tombstone_where_it_is_delivered() {
1718        let base = temp_home("tombstone");
1719        let work = crate::collective::store(&base, "work");
1720        let l = Lesson { id: "L1".into(), question: "short commit subjects?".into(), version: 2, engineers: vec!["ann@x".into()], ..Lesson::default() };
1721        append_jsonl(&work.join("lessons.jsonl"), &crate::reach::tombstone(&l)).unwrap();
1722        append_jsonl(&crate::reach::personal_path(&work), &Lesson { reach: crate::reach::PERSONAL.into(), ..l }).unwrap();
1723        let cs = crate::conscience::load_store_with(&work.join("lessons.jsonl"), None, &crate::collective::Aliases::default());
1724        assert_eq!(cs.len(), 1);
1725        assert!(cs[0].question == "short commit subjects?" && crate::reach::deliverable(&cs[0], &[]));
1726        assert_eq!(store_lessons(&work).len(), 1);
1727        let _ = std::fs::remove_dir_all(base);
1728    }
1729
1730    #[test]
1731    fn a_personal_lesson_moved_elsewhere_is_neither_delivered_nor_merged_into_here() {
1732        let base = temp_home("moved-personal");
1733        let work = crate::collective::store(&base, "work");
1734        let l = Lesson {
1735            id: "Le0".into(),
1736            question: "short commit subjects?".into(),
1737            version: 1,
1738            episodes: vec!["e0".into()],
1739            reach: crate::reach::PERSONAL.into(),
1740            engineers: vec!["ann@x".into()],
1741            ..Lesson::default()
1742        };
1743        append_jsonl(&crate::reach::personal_path(&work), &l).unwrap();
1744        // What `borg move` leaves behind (moves.rs): the tombstone keeps the episodes.
1745        let t = Lesson { version: 2, question: crate::reach::MOVED.into(), consequence: String::new(), ..l.clone() };
1746        append_jsonl(&crate::reach::personal_path(&work), &t).unwrap();
1747        append_jsonl(&work.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "short subjects, mine only")).unwrap();
1748        let cs = crate::conscience::load_store_with(&work.join("lessons.jsonl"), None, &crate::collective::Aliases::default());
1749        assert!(cs.is_empty(), "the tombstone is never delivered: {cs:?}");
1750        assert!(store_lessons(&work).is_empty() && crate::reach::personal_lessons(&work).is_empty());
1751        assert!(learned_episodes(&work).contains("e0"), "its episodes stay learned");
1752        // A later correction that would merge into it makes a lesson of its own: the moved one stays gone.
1753        append_jsonl(&work.join("episodes.jsonl"), &at("e1", "s1", 2, "ann@x", "subjects moved to another collective again merge:Le0 mine only")).unwrap();
1754        assert_eq!(learn_in(&work, None, &fake_personal, false, 3), (1, 0, 0), "e0 is done; e1 cannot merge into Le0");
1755        let latest = crate::learn::lessons(&crate::reach::personal_path(&work));
1756        assert_eq!(latest.iter().find(|l| l.id == "Le0").map(|l| l.question.as_str()), Some(crate::reach::MOVED));
1757        let _ = std::fs::remove_dir_all(base);
1758    }
1759
1760    #[test]
1761    fn the_hooks_episode_waits_for_a_move_rewriting_the_log() {
1762        let home = temp_home("record-locked");
1763        let (held_tx, held_rx) = std::sync::mpsc::channel();
1764        let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
1765        let log = home.join("episodes.jsonl");
1766        let mover = {
1767            let log = log.clone();
1768            std::thread::spawn(move || {
1769                crate::live::locked(&log, || {
1770                    held_tx.send(()).unwrap();
1771                    go_rx.recv().unwrap();
1772                    // A move's rewrite: the log taken whole while the lock is held.
1773                    std::fs::write(&log, "").unwrap();
1774                })
1775            })
1776        };
1777        held_rx.recv().unwrap();
1778        let writer = {
1779            let home = home.clone();
1780            std::thread::spawn(move || record_episode_locked(&home, &at("e1", "s1", 1, "ann@x", "no, use the lock")).unwrap())
1781        };
1782        std::thread::sleep(std::time::Duration::from_millis(150));
1783        assert!(std::fs::read_to_string(&log).unwrap_or_default().is_empty(), "the append waits for the lock");
1784        go_tx.send(()).unwrap();
1785        mover.join().unwrap();
1786        writer.join().unwrap();
1787        assert!(std::fs::read_to_string(&log).unwrap().contains("\"e1\""), "and lands after the rewrite, not in it");
1788        let _ = std::fs::remove_dir_all(home);
1789    }
1790
1791    #[test]
1792    fn a_repo_reach_without_a_repo_is_the_teams() {
1793        let reach = |repo: &str, same_as: &str, lib: &[Lesson]| {
1794            let e = Episode { repo: repo.into(), ..ep("e1", "in the library keep the upstream grammar") };
1795            let answer = json!({"is_lesson": true, "question": "Q", "situations": [], "consequence": "c", "same_as": same_as, "area": "", "supersedes": [], "reach": "repo"});
1796            generalise(&e, lib, &|_| Some(answer.clone())).unwrap().unwrap().reach
1797        };
1798        assert_eq!(reach("", "", &[]), "", "a borg correct without --repo: heard by the team, not nowhere");
1799        assert_eq!(reach("lib", "", &[]), crate::reach::REPO);
1800        let old = Lesson { id: "L0".into(), question: "Does the library keep the upstream grammar?".into(), version: 1, ..Lesson::default() };
1801        assert_eq!(reach("lib", "L0", std::slice::from_ref(&old)), "", "merged into a lesson of no repo");
1802    }
1803
1804    #[test]
1805    fn an_episode_of_a_repo_that_routes_elsewhere_now_is_held_and_listed() {
1806        let base = temp_home("held");
1807        let repos = base.join("repos");
1808        for d in ["work/app", "oss/lib"] {
1809            std::fs::create_dir_all(repos.join(d)).unwrap();
1810        }
1811        let config = |oss: &str| -> crate::collective::Config {
1812            serde_json::from_value(json!({"collectives": [
1813                {"name": "work", "paths": [repos.join("work")]},
1814                {"name": "oss", "paths": [repos.join(oss)]}]}))
1815            .unwrap()
1816        };
1817        let cfg = config("oss/lib");
1818        let (work, oss) = (crate::collective::store(&base, "work"), crate::collective::store(&base, "oss"));
1819        let on = |id: &str, repo: &str, via: &str| Episode { repo: repo.into(), via: via.into(), ..at(id, "s0", 1, "ann@x", &format!("check {id}")) };
1820        for e in [on("e0", "app", ""), on("e1", "lib", ""), on("e2", "lib", CORRECT), on("e3", "elsewhere", ""), on("e4", "lib", "")] {
1821            append_jsonl(&work.join("episodes.jsonl"), &e).unwrap();
1822        }
1823        let calls = std::cell::Cell::new(0);
1824        let ask = |p: &str| {
1825            calls.set(calls.get() + 1);
1826            fake_ask(p)
1827        };
1828        // Learned here: its repo routes here, it was recorded here by name, or its route is unknown.
1829        assert_eq!(learn_in_config(&work, Some(&cfg), None, &ask, false, 3, &mut |_| {}), (3, 0, 0));
1830        let mut learned: Vec<String> = lessons(&work.join("lessons.jsonl")).into_iter().map(|l| l.id).collect();
1831        learned.sort();
1832        assert_eq!(learned, ["Le0", "Le2", "Le3"]);
1833        let route = crate::collective::Route::Collective { name: "oss".into(), home: oss.clone(), share: crate::collective::Share::Team };
1834        assert_eq!(held(&work, Some(&cfg)), [HeldRepo { repo: "lib".into(), route, episodes: vec!["e1".into(), "e4".into()] }]);
1835        // Held, not skipped: nothing marks them, and a second run asks nothing.
1836        assert!(!work.join("episodes-not-lessons.txt").exists());
1837        assert_eq!(learn_in_config(&work, Some(&cfg), None, &ask, false, 4, &mut |_| {}), (0, 0, 0));
1838        assert_eq!(calls.get(), 3);
1839        // No config, or a store that is no collective's: nothing is held.
1840        assert!(held(&work, None).is_empty() && held(&base, Some(&cfg)).is_empty());
1841        // Routed here again: learned here.
1842        let back = config("oss/none");
1843        assert!(held(&work, Some(&back)).is_empty());
1844        assert_eq!(learn_in_config(&work, Some(&back), None, &ask, false, 5, &mut |_| {}), (2, 0, 0));
1845        let _ = std::fs::remove_dir_all(base);
1846    }
1847
1848    fn temp_home(name: &str) -> PathBuf {
1849        let d = std::env::temp_dir().join(format!("borg-learn-{name}-{}", std::process::id()));
1850        let _ = std::fs::remove_dir_all(&d);
1851        std::fs::create_dir_all(&d).unwrap();
1852        d
1853    }
1854
1855    fn at(id: &str, session: &str, ms: i64, engineer: &str, correction: &str) -> Episode {
1856        Episode { ms, session: session.into(), engineer: engineer.into(), ..ep(id, correction) }
1857    }
1858
1859    fn asked(home: &Path, session: &str, ms: i64, ids: &[&str]) {
1860        let o = outcome::Outcome {
1861            kind: outcome::ASKED.into(),
1862            session: session.into(),
1863            lessons: ids.iter().map(|i| i.to_string()).collect(),
1864            ms,
1865            repo: "r".into(),
1866            ..Default::default()
1867        };
1868        outcome::append(&home.join("outcomes.jsonl"), &o).unwrap();
1869    }
1870
1871    fn regret_at(id: &str, decision_ms: i64) -> Episode {
1872        let r = regret::Regret { decision_session: "s-dec".into(), decision_ms, signals: vec!["subject".into()], ..regret::Regret::default() };
1873        Episode { kind: regret::KIND.into(), regret: Some(r), ..at(id, "s-fix", 100, "bob@x", "Fixed later (3d, subject): fix: take the lock") }
1874    }
1875
1876    /// The model's verdict on a regret: a lesson, or (`lesson` false) not one.
1877    fn regret_ask(lesson: bool) -> impl Fn(&str) -> Option<Value> {
1878        move |_| {
1879            Some(json!({"is_lesson": lesson, "question": "Before reading a shared flag, has a writer been considered?", "situations": [],
1880            "consequence": "a race", "same_as": "", "supersedes": []}))
1881        }
1882    }
1883
1884    #[test]
1885    fn a_settled_lesson_says_why_the_judge_gave_it_no_verdict() {
1886        let home = temp_home("unjudged");
1887        asked(&home, "s1", 10, &["A", "B", "C", "D"]);
1888        let ignored =
1889            outcome::Outcome { kind: outcome::IGNORED.into(), session: "s1".into(), lessons: vec!["A".into()], ms: 12, repo: "r".into(), ..Default::default() };
1890        outcome::append(&home.join("outcomes.jsonl"), &ignored).unwrap();
1891        std::fs::create_dir_all(home.join("state")).unwrap();
1892        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";
1893        std::fs::write(home.join("state/s1.ctx"), ctx).unwrap();
1894        learn_in(&home, Some("s1"), &fake_ask, true, 100);
1895        let why: Vec<(String, String)> = outcome::read(&home.join("outcomes.jsonl"))
1896            .into_iter()
1897            .filter(|o| o.kind == outcome::NOT_CORRECTED)
1898            .map(|o| (o.lessons.join(","), o.reason))
1899            .collect();
1900        let want = [("A", outcome::UNJUDGED_NONE), ("B", outcome::UNJUDGED_TRIES), ("C", outcome::UNJUDGED_SLOTS), ("D", outcome::UNJUDGED_NO_CALL)];
1901        assert_eq!(why, want.map(|(l, r)| (l.to_string(), r.to_string())));
1902        let _ = std::fs::remove_dir_all(home);
1903    }
1904
1905    /// Settle waits for a session's end: idle by the log (no ask or episode for a day) is not enough while
1906    /// its state file is still being written.
1907    #[test]
1908    fn an_idle_session_still_working_is_not_settled() {
1909        let home = temp_home("open");
1910        asked(&home, "s1", 10, &["A"]);
1911        std::fs::create_dir_all(home.join("state")).unwrap();
1912        std::fs::write(home.join("state/s1.ctx"), "a prompt just now\n").unwrap();
1913        let now = now_ms();
1914        learn_in(&home, None, &fake_ask, true, now);
1915        assert!(results(&home).is_empty(), "still open: {:?}", results(&home));
1916        // A day after its last line, it ended.
1917        learn_in(&home, None, &fake_ask, true, now + outcome::IDLE_MS + 60_000);
1918        assert_eq!(results(&home), [(outcome::NOT_CORRECTED.into(), "s1".into(), "A".into())]);
1919        let _ = std::fs::remove_dir_all(home);
1920    }
1921
1922    /// A regret is a correction of the deciding session's work too: the lesson it merges into, graded
1923    /// applying in that session before the decision and never asked there, was a question needed and not
1924    /// asked.
1925    #[test]
1926    fn a_regret_merged_into_a_lesson_graded_but_not_asked_before_the_decision_is_a_miss() {
1927        let home = temp_home("regret-miss");
1928        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s0", 1, "ann@x", "use the lock on the flag")).unwrap();
1929        learn_in(&home, Some("s0"), &fake_ask, true, 2);
1930        let graded = |ms: i64| outcome::Outcome {
1931            kind: outcome::GRADED.into(),
1932            session: "s-dec".into(),
1933            lessons: vec!["Le0".into()],
1934            ms,
1935            repo: "r".into(),
1936            grades: vec![2],
1937            ..Default::default()
1938        };
1939        for g in [graded(10), graded(30)] {
1940            outcome::append(&home.join("outcomes.jsonl"), &g).unwrap();
1941        }
1942        append_jsonl(&home.join("episodes.jsonl"), &regret_at("R1", 20)).unwrap();
1943        let merge = |_: &str| Some(json!({"is_lesson": true, "question": "Q", "situations": [], "consequence": "c", "same_as": "Le0", "supersedes": []}));
1944        learn_in(&home, None, &merge, true, 200);
1945        let missed: Vec<(String, String, i64, String)> = outcome::read(&home.join("outcomes.jsonl"))
1946            .into_iter()
1947            .filter(|o| o.kind == outcome::MISSED)
1948            .map(|o| (o.lessons.join(","), o.session, o.ms, o.cause))
1949            .collect();
1950        assert_eq!(missed, [("Le0".to_string(), "s-dec".to_string(), 20, "R1".to_string())]);
1951        learn_in(&home, None, &merge, true, 300);
1952        assert_eq!(outcome::read(&home.join("outcomes.jsonl")).iter().filter(|o| o.kind == outcome::MISSED).count(), 1, "once");
1953        let _ = std::fs::remove_dir_all(home);
1954    }
1955
1956    #[test]
1957    fn a_regret_blames_lessons_asked_before_the_decision_once() {
1958        let regretted = |home: &Path| -> Vec<(String, String, f64, String)> {
1959            outcome::read(&home.join("outcomes.jsonl"))
1960                .into_iter()
1961                .filter(|o| o.kind == outcome::REGRETTED)
1962                .map(|o| (o.lessons.join(","), o.session, o.credit, o.cause))
1963                .collect()
1964        };
1965        let setup = |name: &str, e: Episode| {
1966            let home = temp_home(name);
1967            asked(&home, "s-dec", 10, &["Le0", "Le1"]);
1968            asked(&home, "s-dec", 50, &["Le2"]);
1969            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
1970            home
1971        };
1972        let home = setup("regret", regret_at("R1", 20));
1973        assert_eq!(learn_in(&home, None, &regret_ask(true), true, 200), (1, 0, 0));
1974        let got = regretted(&home);
1975        assert_eq!(
1976            got,
1977            [("Le0".into(), "s-dec".into(), 0.25, "R1".into()), ("Le1".into(), "s-dec".into(), 0.25, "R1".into())],
1978            "Le2 was asked after the decision"
1979        );
1980        let before = std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap();
1981        learn_in(&home, None, &regret_ask(true), true, 300);
1982        assert_eq!(std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap(), before, "credited once");
1983        let _ = std::fs::remove_dir_all(home);
1984        // Not a lesson, no decision time, not tracking: nothing is blamed.
1985        let home = setup("regret-no", regret_at("R1", 20));
1986        learn_in(&home, None, &regret_ask(false), true, 200);
1987        assert!(regretted(&home).is_empty(), "not a lesson");
1988        let _ = std::fs::remove_dir_all(home);
1989        let home = setup("regret-old", regret_at("R1", 0));
1990        learn_in(&home, None, &regret_ask(true), true, 200);
1991        assert!(regretted(&home).is_empty(), "a regret from before decision times were kept");
1992        let _ = std::fs::remove_dir_all(home);
1993        let home = setup("regret-untracked", regret_at("R1", 20));
1994        learn_in(&home, None, &regret_ask(true), false, 200);
1995        assert!(regretted(&home).is_empty(), "BORG_LEARN=off writes nothing");
1996        let _ = std::fs::remove_dir_all(home);
1997    }
1998
1999    #[test]
2000    fn records_outcomes_of_asked_lessons() {
2001        let home = temp_home("outcomes");
2002        // Session s0 teaches lessons Le0 (TOCTOU) and Le1 (spec).
2003        for e in [at("e0", "s0", 1, "ann@x", "check TOCTOU on the flag"), at("e1", "s0", 2, "", "check against the spec")] {
2004            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
2005        }
2006        assert_eq!(learn_in(&home, Some("s0"), &fake_ask, true, 3), (2, 0, 0));
2007        assert!(outcome::read(&home.join("outcomes.jsonl")).is_empty(), "nothing asked, nothing settled");
2008        // s1: both asked at 10; the TOCTOU concern is corrected again at 20 (merged into Le0).
2009        // Le1 asked again after that correction, which must not count as corrected.
2010        asked(&home, "s1", 10, &["Le0", "Le1"]);
2011        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s1", 20, "bob@x", "flag still racy merge:Le0")).unwrap();
2012        asked(&home, "s1", 30, &["Le1"]);
2013        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, true, 40), (0, 1, 0));
2014        let result: Vec<(String, String, i64)> =
2015            outcome::read(&home.join("outcomes.jsonl")).into_iter().filter(|o| o.kind != outcome::ASKED).map(|o| (o.kind, o.lessons.join(","), o.ms)).collect();
2016        assert_eq!(result, [(outcome::CORRECTED.into(), "Le0".into(), 20), (outcome::NOT_CORRECTED.into(), "Le1".into(), 40)]);
2017        // Re-running learn for the same session appends nothing: deterministic and idempotent.
2018        let before = std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap();
2019        learn_in(&home, Some("s1"), &fake_ask, true, 50);
2020        assert_eq!(std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap(), before);
2021        // Engineers accumulate on the merged lesson.
2022        let l0 = lessons(&home.join("lessons.jsonl")).into_iter().find(|l| l.id == "Le0").unwrap();
2023        assert_eq!(l0.engineers, ["ann@x", "bob@x"]);
2024        // The same email in another case is the same engineer: not added, no join recorded.
2025        append_jsonl(&home.join("episodes.jsonl"), &at("e3", "s2", 60, "Ann@X", "flag racy again merge:Le0")).unwrap();
2026        assert_eq!(learn_in(&home, Some("s2"), &fake_ask, true, 70), (0, 1, 0));
2027        let l0 = lessons(&home.join("lessons.jsonl")).into_iter().find(|l| l.id == "Le0").unwrap();
2028        assert_eq!((l0.engineers.as_slice(), l0.joined.get("Ann@X")), (&["ann@x".to_string(), "bob@x".to_string()][..], None));
2029        let _ = std::fs::remove_dir_all(home);
2030    }
2031
2032    #[test]
2033    fn idle_sessions_settle_without_their_end_hook() {
2034        let home = temp_home("idle");
2035        for e in [at("e0", "s0", 1, "", "check TOCTOU on the flag"), at("e1", "s0", 2, "", "check against the spec")] {
2036            append_jsonl(&home.join("episodes.jsonl"), &e).unwrap();
2037        }
2038        learn_in(&home, Some("s0"), &fake_ask, true, 3);
2039        // s1 and s3 never send `end`. s1 asks both and is corrected on Le0; s3 asks Le0, no correction.
2040        asked(&home, "s1", 10, &["Le0", "Le1"]);
2041        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s1", 20, "", "flag still racy merge:Le0")).unwrap();
2042        asked(&home, "s3", 5, &["Le0"]);
2043        let idle = 20 + outcome::IDLE_MS;
2044        let results = || -> Vec<(String, String, String)> {
2045            outcome::read(&home.join("outcomes.jsonl"))
2046                .into_iter()
2047                .filter(|o| o.kind != outcome::ASKED)
2048                .map(|o| (o.kind, o.session, o.lessons.join(",")))
2049                .collect()
2050        };
2051        let not = |s: &str, l: &str| (outcome::NOT_CORRECTED.to_string(), s.to_string(), l.to_string());
2052        // s2 ends a day later: its own ask settles, and idle s3; s1 not: it is still open (its state file
2053        // is fresh), so its episode is still pending.
2054        let ctx = home.join("state/s1.ctx");
2055        std::fs::create_dir_all(ctx.parent().unwrap()).unwrap();
2056        std::fs::write(&ctx, "").unwrap();
2057        asked(&home, "s2", idle - 1, &["Le1"]);
2058        learn_in(&home, Some("s2"), &fake_ask, true, idle);
2059        assert_eq!(results(), [not("s3", "Le0"), not("s2", "Le1")]);
2060        // s1 goes quiet; a plain `borg learn` folds e2 in and settles s1 too, so s1 gives both kinds of outcome.
2061        std::fs::remove_file(&ctx).unwrap();
2062        assert_eq!(learn_in(&home, None, &fake_ask, true, idle), (0, 1, 0));
2063        let corrected = (outcome::CORRECTED.to_string(), "s1".to_string(), "Le0".to_string());
2064        assert_eq!(results(), [not("s3", "Le0"), not("s2", "Le1"), corrected.clone(), not("s1", "Le1")]);
2065        // A fresh session is not settled, and re-running appends nothing.
2066        asked(&home, "s4", idle, &["Le1"]);
2067        learn_in(&home, None, &fake_ask, true, idle + 1);
2068        assert_eq!(results().len(), 4);
2069        let _ = std::fs::remove_dir_all(home);
2070    }
2071
2072    #[test]
2073    fn a_quiet_sessions_episodes_are_learned_by_another_sessions_end() {
2074        let home = temp_home("quiet");
2075        // s1 never ends; the transcript sweep added its last correction after it went quiet (sweep.rs `idle`).
2076        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s1", 10, "", "check TOCTOU on the flag")).unwrap();
2077        // s9 is busy (an episode an hour ago) and open; s2 ends now.
2078        append_jsonl(&home.join("episodes.jsonl"), &at("e1", "s9", 10 + outcome::IDLE_MS, "", "check against the spec")).unwrap();
2079        append_jsonl(&home.join("episodes.jsonl"), &at("e2", "s2", 20 + outcome::IDLE_MS, "", "no, keep the cache")).unwrap();
2080        let now = 30 + outcome::IDLE_MS;
2081        // While s1's state file is fresh it is open, and waits for its own end.
2082        let ctx = home.join("state/s1.ctx");
2083        std::fs::create_dir_all(ctx.parent().unwrap()).unwrap();
2084        std::fs::write(&ctx, "").unwrap();
2085        assert_eq!(learn_in(&home, Some("s2"), &fake_ask, true, now), (1, 0, 0), "s2's own episode only");
2086        // Quiet: s2's end learns it too; busy s9 still waits.
2087        std::fs::remove_file(&ctx).unwrap();
2088        append_jsonl(&home.join("episodes.jsonl"), &at("e3", "s3", 25 + outcome::IDLE_MS, "", "no, the other crate")).unwrap();
2089        assert_eq!(learn_in(&home, Some("s3"), &fake_ask, true, now), (2, 0, 0), "s3's own and quiet s1's");
2090        let learned: HashSet<String> = lessons(&home.join("lessons.jsonl")).into_iter().flat_map(|l| l.episodes).collect();
2091        assert!(learned.contains("e0") && !learned.contains("e1"), "{learned:?}");
2092        let _ = std::fs::remove_dir_all(home);
2093    }
2094
2095    #[test]
2096    fn no_outcomes_written_without_tracking() {
2097        let home = temp_home("off");
2098        append_jsonl(&home.join("episodes.jsonl"), &at("e0", "s0", 1, "", "check TOCTOU")).unwrap();
2099        learn_in(&home, Some("s0"), &fake_ask, true, 2);
2100        asked(&home, "s1", 10, &["Le0"]);
2101        let before = std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap();
2102        append_jsonl(&home.join("episodes.jsonl"), &at("e1", "s1", 20, "", "TOCTOU again merge:Le0")).unwrap();
2103        assert_eq!(learn_in(&home, Some("s1"), &fake_ask, false, 30), (0, 1, 0));
2104        assert_eq!(std::fs::read_to_string(home.join("outcomes.jsonl")).unwrap(), before);
2105        let _ = std::fs::remove_dir_all(home);
2106    }
2107
2108    #[test]
2109    fn failed_model_calls_leave_episodes_waiting_and_stop_early() {
2110        let home = temp_home("failed");
2111        for i in 0..5 {
2112            append_jsonl(&home.join("episodes.jsonl"), &at(&format!("e{i}"), "s0", i, "", &format!("check case {i}"))).unwrap();
2113        }
2114        asked(&home, "s0", 0, &["Lx"]);
2115        let calls = std::cell::Cell::new(0);
2116        let down = |_: &str| -> Option<Value> {
2117            calls.set(calls.get() + 1);
2118            None
2119        };
2120        // Quota hit: nothing is marked "not a lesson", the run gives up after MAX_FAILURES calls,
2121        // and the session is not settled while its episodes wait.
2122        assert_eq!(learn_in(&home, Some("s0"), &down, true, 1 + outcome::IDLE_MS), (0, 0, 5));
2123        assert_eq!(calls.get(), MAX_FAILURES);
2124        assert!(!home.join("episodes-not-lessons.txt").exists());
2125        assert!(outcome::read(&home.join("outcomes.jsonl")).iter().all(|o| o.kind == outcome::ASKED));
2126        // The model is back: the next run retries every episode.
2127        assert_eq!(learn_in(&home, Some("s0"), &fake_ask, true, 2 + outcome::IDLE_MS), (5, 0, 0));
2128        let _ = std::fs::remove_dir_all(home);
2129    }
2130
2131    #[test]
2132    fn area_and_supersedes_come_from_the_same_call() {
2133        let lib = vec![
2134            generalise(&ep("e1", "use a lock here"), &[], &|_| {
2135                Some(json!({"is_lesson": true, "question": "Is the flag guarded by a lock?", "situations": ["flag across threads"],
2136                    "consequence": "race", "same_as": "", "area": "Concurrency", "supersedes": ["Lnope"]}))
2137            })
2138            .unwrap()
2139            .unwrap(),
2140        ];
2141        assert_eq!(lib[0].area, "concurrency", "case-insensitive; normalised");
2142        assert!(lib[0].supersedes.is_empty(), "an id the model was not shown is dropped");
2143        // A lesson without an area (older store, or a model that ignores it) is "other".
2144        let old: Lesson = serde_json::from_str(
2145            r#"{"id":"L","origin_ms":1,"repo":"r","question":"q","situations":[],"consequence":"c",
2146            "support":1,"episodes":[],"history":[],"version":1}"#,
2147        )
2148        .unwrap();
2149        assert_eq!((old.area.as_str(), old.supersedes.len()), ("other", 0));
2150        let id = lib[0].id.clone();
2151        let reversed = generalise(&ep("e2", "no, the lock is wrong here, use the atomic flag"), &lib, &move |_| {
2152            Some(json!({"is_lesson": true, "question": "Is a lock-free atomic enough for the flag?", "situations": ["flag across threads"],
2153                "consequence": "lock contention", "same_as": "", "area": "made-up", "supersedes": [id.clone()]}))
2154        })
2155        .unwrap()
2156        .unwrap();
2157        assert_eq!((reversed.area.as_str(), reversed.supersedes.clone()), ("other", vec![lib[0].id.clone()]));
2158        assert!(!serde_json::to_string(&lib[0]).unwrap().contains("supersedes"), "empty supersedes stays off the line");
2159        // The merge target is never superseded; a merge keeps what the old version superseded.
2160        let (rid, lid) = (reversed.id.clone(), lib[0].id.clone());
2161        let merged = generalise(&ep("e3", "again: atomic, not a lock"), &[lib[0].clone(), reversed.clone()], &move |_| {
2162            Some(json!({"is_lesson": true, "question": "Is a lock-free atomic enough?", "situations": ["flag across threads"],
2163                "consequence": "lock contention", "same_as": rid.clone(), "area": "concurrency", "supersedes": [rid.clone(), lid.clone()]}))
2164        })
2165        .unwrap()
2166        .unwrap();
2167        assert_eq!((merged.id.as_str(), merged.version, merged.supersedes.clone()), (reversed.id.as_str(), 2, vec![lib[0].id.clone()]));
2168    }
2169
2170    #[test]
2171    fn new_lesson_then_merge_keeps_history() {
2172        let first = generalise(&ep("e1", "carefully check TOCTOU on the atomic flags"), &[], &|_| {
2173            Some(json!({"is_lesson": true, "question": "Is every check-then-act on a shared flag TOCTOU-safe?",
2174                "situations": ["check-then-act on a shared mutable flag across threads"], "consequence": "race", "same_as": ""}))
2175        })
2176        .unwrap()
2177        .unwrap();
2178        assert_eq!((first.version, first.support), (1, 1));
2179        let id = first.id.clone();
2180        let merged = generalise(&ep("e2", "again: the closed flag check is racy"), std::slice::from_ref(&first), &move |p| {
2181            assert!(p.contains(&id), "the similar lesson must be offered for merging");
2182            Some(json!({"is_lesson": true, "question": "Is each check-then-act on shared flags atomic or harmless on race?",
2183                "situations": ["check-then-act on a shared mutable flag across threads"], "consequence": "race", "same_as": id}))
2184        })
2185        .unwrap()
2186        .unwrap();
2187        assert_eq!((merged.id.as_str(), merged.version, merged.support, merged.history.len()), (first.id.as_str(), 2, 2, 1));
2188        let skipped =
2189            generalise(&ep("e3", "stop"), &[], &|_| Some(json!({"is_lesson": false, "question": "", "situations": [], "consequence": "", "same_as": ""})));
2190        assert!(matches!(skipped, Ok(None)), "a verdict: not a lesson");
2191        assert_eq!(generalise(&ep("e4", "no, the lock"), &[], &|_| None).map(|_| ()), Err(AskFailed), "no answer is no verdict");
2192        let malformed = generalise(&ep("e5", "no, the lock"), &[], &|_| Some(json!({"error": "rate limited"})));
2193        assert_eq!(malformed.map(|_| ()), Err(AskFailed));
2194    }
2195}