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