Skip to main content

borg/
conscience.rs

1//! The conscience: challenges learned from engineers' corrections, asked at
2//! decision points when what the drone is working on matches.
3//!
4//! A challenge is a question, never an answer. It is recalled only when it
5//! matches the drone's prompt, touches and plan (BM25 over the question text),
6//! so a drone working on something unrelated pays zero tokens.
7
8use std::collections::HashSet;
9use std::path::Path;
10
11use serde::Deserialize;
12
13use crate::collective::{self, Aliases};
14use crate::trust;
15
16#[derive(Debug, Clone, Deserialize)]
17pub struct Challenge {
18    pub id: String,
19    /// Epoch ms of the correction this challenge was learned from.
20    pub origin_ms: i64,
21    pub question: String,
22    /// World-model form of the lesson (see predict.rs); empty for question-only lessons.
23    #[serde(default)]
24    pub situations: Vec<String>,
25    #[serde(default)]
26    pub consequence: String,
27    /// Kind of concern (trust.rs `AREAS`); "other" for lessons learned before areas existed.
28    #[serde(default)]
29    pub area: String,
30    /// Engineers whose corrections the lesson was learned from (git user.email).
31    #[serde(default)]
32    pub engineers: Vec<String>,
33    /// When each later engineer joined the lesson (learn.rs `Lesson::joined`).
34    #[serde(default)]
35    pub joined: std::collections::BTreeMap<String, i64>,
36    /// Lessons this one replaces or contradicts (set by `borg learn` or a queen answer).
37    #[serde(default)]
38    pub supersedes: Vec<String>,
39    /// "queen" for a queen answer (queen.rs `lesson`), empty otherwise.
40    #[serde(default)]
41    pub source: String,
42    /// Names the lesson is limited to (learn.rs `Lesson::scope`); empty: unscoped.
43    #[serde(default)]
44    pub scope: Vec<String>,
45    /// The outside rule this lesson replaces (learn.rs `Lesson::overrides`), shown with the question.
46    #[serde(default)]
47    pub overrides: String,
48    /// Alternative phrasings for search (learn.rs `Lesson::facets`): each is its own BM25 document of
49    /// this lesson (`rank`), never shown.
50    #[serde(default)]
51    pub facets: Vec<String>,
52    /// The repo the lesson was learned in (for an import: where the knowledge was written down).
53    #[serde(default)]
54    pub repo: String,
55    /// Who should hear it (reach.rs): empty for the team, `repo`, or `personal` (a withdrawn tombstone).
56    #[serde(default)]
57    pub reach: String,
58    /// Scoped to systems none of which is the work's known system (systems.rs `gate`): scores 0.
59    #[serde(skip)]
60    pub off_system: bool,
61    /// Memory weight (memory.rs: activation × usefulness belief), multiplies the BM25 score; 1 for a
62    /// new lesson without outcomes.
63    #[serde(skip, default = "one")]
64    pub weight: f64,
65    /// Dormant (memory.rs): recalled only on a strong match (`rank`).
66    #[serde(skip)]
67    pub dormant: bool,
68    /// Consolidated (memory.rs): may be delivered early without a scope (`early`).
69    #[serde(skip)]
70    pub consolidated: bool,
71    /// This session's Thompson draw of the lesson's usefulness relative to its mean (memory.rs): orders
72    /// the lessons that cleared the bar when there are more than the slots (`budget`, `early`); 1
73    /// without a session.
74    #[serde(skip, default = "one")]
75    pub explore: f64,
76    /// The usefulness belief behind `explore` (memory.rs `Memory::alpha`, `beta`): Beta(α, β), (1, 1)
77    /// without outcomes. For the propensity of a slot (`propensity`).
78    #[serde(skip, default = "uniform")]
79    pub belief: (f64, f64),
80    /// Mean trust of the lesson's authors in its area (trust.rs), 0.5 without evidence.
81    #[serde(skip, default = "neutral")]
82    pub trust: f64,
83}
84
85fn one() -> f64 {
86    1.0
87}
88
89fn uniform() -> (f64, f64) {
90    (1.0, 1.0)
91}
92
93fn neutral() -> f64 {
94    trust::NEUTRAL
95}
96
97impl Default for Challenge {
98    fn default() -> Self {
99        Challenge {
100            id: String::new(),
101            origin_ms: 0,
102            question: String::new(),
103            situations: Vec::new(),
104            consequence: String::new(),
105            area: trust::OTHER.into(),
106            engineers: Vec::new(),
107            joined: Default::default(),
108            supersedes: Vec::new(),
109            source: String::new(),
110            scope: Vec::new(),
111            overrides: String::new(),
112            facets: Vec::new(),
113            repo: String::new(),
114            reach: String::new(),
115            off_system: false,
116            weight: 1.0,
117            dormant: false,
118            consolidated: false,
119            explore: 1.0,
120            belief: uniform(),
121            trust: trust::NEUTRAL,
122        }
123    }
124}
125
126/// Lessons known before `before_ms`. The store is append-only: when a lesson was consolidated,
127/// a later line carries the same id, and the latest version wins. Each carries its weight from
128/// `outcomes.jsonl` beside the lessons file and the team's synced outcomes (outcome.rs `read_team`;
129/// absent, e.g. for eval challenge files: all 1) and its authors' trust in its area, computed from
130/// this store alone (trust.rs). Engineers are
131/// canonical under this machine's aliases (collective.rs "Engineers").
132pub fn load(path: &Path, before_ms: Option<i64>) -> Vec<Challenge> {
133    load_with(path, before_ms, collective::aliases())
134}
135
136/// `load` under explicit aliases.
137pub fn load_with(path: &Path, before_ms: Option<i64>, aliases: &Aliases) -> Vec<Challenge> {
138    load_as(path, before_ms, aliases, None)
139}
140
141/// `load` as seen from `session`: each weight takes that session's Thompson sample of the lesson's
142/// usefulness (memory.rs), stable within the session. Without a session, the belief's mean.
143pub fn load_for(path: &Path, before_ms: Option<i64>, session: Option<&str>) -> Vec<Challenge> {
144    load_as(path, before_ms, collective::aliases(), session)
145}
146
147fn load_as(path: &Path, before_ms: Option<i64>, aliases: &Aliases, session: Option<&str>) -> Vec<Challenge> {
148    let outcomes = crate::outcome::read_team(path);
149    let mut out = load_unweighted_with(path, before_ms, aliases);
150    let memory = crate::memory::derive(&outcomes, &out, session);
151    let trust = trust::Trust::compute(&out, &outcomes);
152    for c in &mut out {
153        if let Some(m) = memory.get(&c.id) {
154            // The bar (`RELATIVE`) is set on the expected weight; the session's draw only decides which
155            // of the lessons over the bar get the limited slots, so a new lesson's uncertainty cannot drop
156            // a strong match below the bar.
157            c.weight = m.weight(&c.id, None);
158            c.explore = if session.is_some() { m.weight(&c.id, session) / c.weight } else { 1.0 };
159            c.belief = (m.alpha(), m.beta());
160            c.dormant = m.dormant;
161            c.consolidated = m.consolidated;
162        }
163        c.trust = trust.lesson(c);
164    }
165    out.extend(constraints(path, before_ms, aliases, &out));
166    out
167}
168
169/// `source` of a ratified constraint loaded as a lesson (`constraints`).
170pub const CONSTRAINT: &str = "constraint";
171
172impl Challenge {
173    /// A standing lesson: a constraint an engineer ratified (veto.rs `ratify`). Consolidated, never
174    /// dormant, its weight and trust fixed (no outcome or author moves them), and delivered early
175    /// whenever its scope is in play, whatever the match, on every harness that takes prompt context
176    /// (`standing_pool`, hook.rs `early`).
177    pub fn standing(&self) -> bool {
178        self.source == CONSTRAINT
179    }
180}
181
182/// The ratified constraints beside the lessons file `path` (veto.rs `constraints_path`) known before
183/// `before_ms`, as standing lessons: the invariant is the question, the scope and repo are those of the
184/// lesson it was proposed from (in `lessons`), its reach the narrower of the line's and the lesson's
185/// (reach.rs `narrower`): a lesson withdrawn or made a repo convention takes its constraint along. With
186/// the lesson unknown here (quarantined, not synced yet, after `before_ms`), the line's own scope and
187/// repo, bound to that repo; a line that names no repo either is left out, never delivered everywhere.
188/// One per id, the earliest ratification (by time, then author), so nodes that both ratified it read
189/// the same line after a sync, in whatever order it came.
190fn constraints(path: &Path, before_ms: Option<i64>, aliases: &Aliases, lessons: &[Challenge]) -> Vec<Challenge> {
191    let Some(dir) = path.parent() else { return Vec::new() };
192    let Ok(text) = std::fs::read_to_string(crate::veto::constraints_path(dir)) else { return Vec::new() };
193    let mut by: std::collections::BTreeMap<String, (i64, String, Challenge)> = std::collections::BTreeMap::new();
194    for v in text.lines().filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok()) {
195        let s = |k: &str| v[k].as_str().unwrap_or_default().trim().to_string();
196        let (id, question, ms) = (s("id"), s("text"), v["ms"].as_i64().unwrap_or(0));
197        if id.is_empty() || question.is_empty() || before_ms.is_some_and(|b| ms >= b) {
198            continue;
199        }
200        let author = aliases.canon(&s("by"));
201        if by.get(&id).is_some_and(|(m, a, _)| (*m, a.as_str()) <= (ms, author.as_str())) {
202            continue;
203        }
204        let line_scope: Vec<String> = v["scope"].as_array().into_iter().flatten().filter_map(|x| x.as_str()).map(str::to_string).collect();
205        let (scope, repo, reach, area) = match lessons.iter().find(|l| l.id == s("lesson")) {
206            Some(l) => {
207                let repo = if l.repo.is_empty() { s("repo") } else { l.repo.clone() };
208                (l.scope.clone(), repo, crate::reach::narrower(&s("reach"), &l.reach).to_string(), l.area.clone())
209            }
210            None if s("repo").is_empty() => continue,
211            None => (line_scope, s("repo"), crate::reach::narrower(&s("reach"), crate::reach::REPO).to_string(), trust::OTHER.into()),
212        };
213        let c = Challenge {
214            id: id.clone(),
215            origin_ms: ms,
216            question,
217            source: CONSTRAINT.into(),
218            engineers: Some(author.clone()).filter(|a| !a.is_empty()).into_iter().collect(),
219            scope,
220            repo,
221            reach,
222            area,
223            consolidated: true,
224            ..Challenge::default()
225        };
226        by.insert(id, (ms, author, c));
227    }
228    by.into_values().map(|(_, _, c)| c).collect()
229}
230
231/// The lessons as stored (latest version per id, area normalised, engineers canonical), without
232/// weight or trust.
233pub fn load_unweighted(path: &Path, before_ms: Option<i64>) -> Vec<Challenge> {
234    load_unweighted_with(path, before_ms, collective::aliases())
235}
236
237/// `load_unweighted` under explicit aliases.
238pub fn load_unweighted_with(path: &Path, before_ms: Option<i64>, aliases: &Aliases) -> Vec<Challenge> {
239    let Ok(text) = std::fs::read_to_string(path) else { return Vec::new() };
240    // Index by id: a linear scan per line made loading O(n²) (29 s at 100k lessons).
241    let mut out: Vec<Challenge> = Vec::new();
242    let mut at: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
243    for mut c in text.lines().filter_map(|l| serde_json::from_str::<Challenge>(l).ok()) {
244        c.area = trust::area(&c.area).into();
245        canonical(&mut c, aliases);
246        if before_ms.is_some_and(|b| c.origin_ms >= b) {
247            continue;
248        }
249        match at.get(&c.id) {
250            Some(&i) => out[i] = c,
251            None => {
252                at.insert(c.id.clone(), out.len());
253                out.push(c);
254            }
255        }
256    }
257    out
258}
259
260/// Map a lesson's engineers to who they are (`Aliases::canon`), at read time: the store keeps the
261/// raw emails. Several emails of one engineer become one author; that author joined when the
262/// earliest of them did, and not at all (counts from the start) if any of them is the first
263/// contributor.
264fn canonical(c: &mut Challenge, aliases: &Aliases) {
265    let mut engineers: Vec<String> = Vec::new();
266    for e in c.engineers.iter().map(|e| aliases.canon(e)).filter(|e| !e.is_empty()) {
267        if !engineers.contains(&e) {
268            engineers.push(e);
269        }
270    }
271    let joined = engineers
272        .iter()
273        .filter_map(|who| {
274            let raws = c.engineers.iter().filter(|r| aliases.canon(r) == *who);
275            let at: Option<Vec<i64>> = raws.map(|r| c.joined.get(r).copied()).collect();
276            Some((who.clone(), at?.into_iter().min()?))
277        })
278        .collect();
279    (c.engineers, c.joined) = (engineers, joined);
280}
281
282/// Lowercased words of 3+ characters, plus the parts of camelCase words.
283pub fn tokens(text: &str) -> Vec<String> {
284    let mut out = Vec::new();
285    for raw in text.split(|c: char| !c.is_alphanumeric() && c != '_') {
286        if raw.len() < 3 {
287            continue;
288        }
289        out.push(raw.to_lowercase());
290        let mut word = String::new();
291        for ch in raw.chars() {
292            if ch.is_uppercase() && !word.is_empty() {
293                if word.len() >= 3 && word.len() < raw.len() {
294                    out.push(word.to_lowercase());
295                }
296                word.clear();
297            }
298            word.push(ch);
299        }
300        if word.len() >= 3 && word.len() < raw.len() {
301            out.push(word.to_lowercase());
302        }
303    }
304    out
305}
306
307/// BM25 over the challenges' own question text, queried with the drone's
308/// context (prompt, touches, its plan). Evaluated against keyword-IDF, dense
309/// and reranked retrieval on graded qrels (internal evaluation "retrieval-plan-queries", not published):
310/// BM25 ranked the relevant lessons highest. Each score is multiplied by the
311/// challenge's outcome weight, so a lesson that keeps being asked and then
312/// corrected anyway sinks below equally relevant ones, and by its authors'
313/// trust in its area relative to neutral (trust / 0.5: no evidence leaves the
314/// score unchanged). A lesson hidden by its successor is never ranked; the live
315/// successor inherits its relevance (trust.rs `successors`), so the replacing
316/// claim is asked where the replaced one would have been. A supersession that
317/// does not hide (a less trusted engineer contradicting another) keeps both
318/// live, and `render` shows them as a disagreement. A scoped lesson whose scope
319/// the context never names scores 0 (`in_scope`): it is neither asked nor passes
320/// its relevance on. Returns every challenge with score > 0, best first.
321///
322/// A lesson with facets (facets.rs) is several documents: its question and each facet. Its score is its
323/// best document's (`bm25_groups`), with idf counted over lessons, so a store without facets ranks
324/// exactly as BM25 over the questions, and the prefilter's normalisation by the largest idf stays valid.
325pub fn rank<'a>(challenges: &'a [Challenge], context: &str) -> Vec<(f64, &'a Challenge)> {
326    rank_scoped(challenges, context, context)
327}
328
329/// The drone's work in `context` (a session's state file plus its work text) as word matching, the
330/// vectors and the consequence model read it: without borg's own bookkeeping lines (`#borg-asked`,
331/// `#borg-p`, `#borg-pool`, every `#borg-` marker). They carry lesson ids, scores and costs, not work.
332pub fn work_text(context: &str) -> std::borrow::Cow<'_, str> {
333    if !context.contains("#borg-") {
334        return std::borrow::Cow::Borrowed(context);
335    }
336    std::borrow::Cow::Owned(context.split_inclusive('\n').filter(|l| !l.starts_with("#borg-")).collect())
337}
338
339/// `rank`, with scopes judged against `scope_text` (where the session works) instead of the whole
340/// context: a system the conversation only talks about is not one the drone works on.
341pub fn rank_scoped<'a>(challenges: &'a [Challenge], context: &str, scope_text: &str) -> Vec<(f64, &'a Challenge)> {
342    let groups: Vec<Vec<Vec<String>>> = challenges.iter().map(documents).collect();
343    let mut raw = bm25_groups(&groups, context, 0.0);
344    if challenges.iter().any(|c| !c.scope.is_empty()) {
345        let have = Names::of(scope_text);
346        for (r, c) in raw.iter_mut().zip(challenges) {
347            if !in_scope(c, &have) || c.off_system {
348                *r = 0.0;
349            }
350        }
351    }
352    // A dormant lesson (memory.rs) is recalled only on a strong match: `STRONG` × the best match.
353    let best = raw.iter().copied().fold(0.0, f64::max);
354    for (r, c) in raw.iter_mut().zip(challenges) {
355        if c.dormant && *r < STRONG * best {
356            *r = 0.0;
357        }
358    }
359    let successors = trust::successors(challenges);
360    let mut relevance = raw.clone();
361    if !successors.is_empty() {
362        let at: std::collections::HashMap<&str, usize> = challenges.iter().enumerate().map(|(i, c)| (c.id.as_str(), i)).collect();
363        for (i, c) in challenges.iter().enumerate() {
364            if let Some(&j) = successors.get(&c.id).and_then(|s| at.get(s.as_str())) {
365                relevance[j] = relevance[j].max(raw[i]);
366            }
367        }
368    }
369    let mut scored: Vec<(f64, &Challenge)> = relevance
370        .into_iter()
371        .zip(challenges)
372        .filter(|(_, c)| !successors.contains_key(&c.id))
373        .map(|(s, c)| (s * c.weight * c.trust / trust::NEUTRAL, c))
374        .filter(|(s, _)| *s > 0.0)
375        .collect();
376    scored.sort_by(|a, b| b.0.total_cmp(&a.0).then(b.1.origin_ms.cmp(&a.1.origin_ms)));
377    scored
378}
379
380/// A dormant lesson needs at least this share of the best match to be recalled (`rank`). Baseline:
381/// design-chosen with dormancy (memory.rs `DORMANT_BELOW`), part of today's ranking; the same value as
382/// `BLOCK`, a different bar.
383pub const STRONG: f64 = 0.8;
384
385/// Whether a lesson applies to a context: unscoped, or one of its scope names occurs in it as a
386/// contiguous phrase or identifier (`Names::contains`). "Answer Guard" needs "answer guard" (or
387/// `AnswerGuard`), never "output" in one sentence and "guard" in another; "Orion" matches a path
388/// `orion-text/` and `OrionConfig`; no part of a name is ever dropped for being short.
389pub fn in_scope(c: &Challenge, have: &Names) -> bool {
390    c.scope.is_empty() || c.scope.iter().any(|s| have.contains(s))
391}
392
393/// Lowercased name parts in order: split at every non-alphanumeric character and at camelCase
394/// humps (`HTTPClientFactory` -> http, client, factory), digits kept with their letters (`v2`, `sr3`).
395pub fn segments(text: &str) -> Vec<String> {
396    let mut out = Vec::new();
397    for raw in text.split(|c: char| !c.is_alphanumeric()).filter(|r| !r.is_empty()) {
398        let cs: Vec<char> = raw.chars().collect();
399        let mut word = String::new();
400        for (i, &ch) in cs.iter().enumerate() {
401            let hump = i > 0
402                && ch.is_uppercase()
403                && (cs[i - 1].is_lowercase() || cs[i - 1].is_numeric() || (cs[i - 1].is_uppercase() && cs.get(i + 1).is_some_and(|n| n.is_lowercase())));
404            if hump && !word.is_empty() {
405                out.push(std::mem::take(&mut word).to_lowercase());
406            }
407            word.push(ch);
408        }
409        out.push(word.to_lowercase());
410    }
411    out
412}
413
414/// A text as its name parts, indexed for contiguous lookups.
415pub struct Names {
416    seq: Vec<String>,
417    at: std::collections::HashMap<String, Vec<usize>>,
418}
419
420impl Names {
421    pub fn of(text: &str) -> Self {
422        Self::of_all([text])
423    }
424
425    /// Several texts, none adjacent to the next: a name never matches across two of them.
426    pub fn of_all<'a>(texts: impl IntoIterator<Item = &'a str>) -> Self {
427        let mut seq = Vec::new();
428        for t in texts {
429            seq.extend(segments(t));
430            seq.push(String::new()); // a part no name has
431        }
432        let mut at: std::collections::HashMap<String, Vec<usize>> = std::collections::HashMap::new();
433        for (i, s) in seq.iter().enumerate() {
434            at.entry(s.clone()).or_default().push(i);
435        }
436        Names { seq, at }
437    }
438
439    /// Whether every part of `name` occurs here, in order and adjacent. A name without parts never matches.
440    pub fn contains(&self, name: &str) -> bool {
441        let need = segments(name);
442        let Some(first) = need.first() else { return false };
443        self.at.get(first).is_some_and(|starts| starts.iter().any(|&i| self.seq.get(i..i + need.len()).is_some_and(|w| w == need.as_slice())))
444    }
445}
446
447/// Okapi BM25's term-frequency saturation and length normalisation (`bm25`, `bm25_groups`). Method:
448/// the standard parameters (Robertson and Zaragoza, "The Probabilistic Relevance Framework: BM25 and
449/// Beyond", 2009); never tuned on borg's data.
450pub const BM25_K1: f64 = 1.2;
451pub const BM25_B: f64 = 0.75;
452
453/// Okapi BM25 (`BM25_K1`, `BM25_B`) of each tokenised document against the query text, in document order.
454pub fn bm25(docs: &[Vec<String>], query: &str) -> Vec<f64> {
455    let (k1, b) = (BM25_K1, BM25_B);
456    let n = docs.len().max(1) as f64;
457    let avg = docs.iter().map(Vec::len).sum::<usize>() as f64 / n;
458    let mut df: std::collections::HashMap<&str, f64> = std::collections::HashMap::new();
459    for d in docs {
460        for t in d.iter().map(String::as_str).collect::<HashSet<_>>() {
461            *df.entry(t).or_default() += 1.0;
462        }
463    }
464    let query: HashSet<String> = tokens(query).into_iter().collect();
465    docs.iter()
466        .map(|d| {
467            let mut tf: std::collections::HashMap<&str, f64> = std::collections::HashMap::new();
468            for t in d {
469                *tf.entry(t.as_str()).or_default() += 1.0;
470            }
471            query
472                .iter()
473                .filter_map(|t| tf.get(t.as_str()).map(|f| (t, *f)))
474                .map(|(t, f)| {
475                    let dft = df[t.as_str()];
476                    let idf = (1.0 + (n - dft + 0.5) / (dft + 0.5)).ln();
477                    idf * f * (k1 + 1.0) / (f + k1 * (1.0 - b + b * d.len() as f64 / avg))
478                })
479                .sum()
480        })
481        .collect()
482}
483
484/// A lesson's search documents: its question, then each facet (`Challenge::facets`).
485pub fn documents(c: &Challenge) -> Vec<Vec<String>> {
486    std::iter::once(tokens(&c.question)).chain(c.facets.iter().map(|f| tokens(f)).filter(|d| !d.is_empty())).collect()
487}
488
489/// BM25 (`BM25_K1`, `BM25_B`) of groups of documents, one group per lesson, against the query text: a
490/// group scores its best document plus `second` × its second best (0: the best alone). Document
491/// frequencies count groups (a word in three facets of one lesson is one lesson), so idf means what it
492/// means in `bm25`; term frequency and length are per document. Groups of one document score as `bm25`
493/// does. Only query words are counted, which keeps a 1k-lesson store with facets fast.
494pub fn bm25_groups(groups: &[Vec<Vec<String>>], query: &str, second: f64) -> Vec<f64> {
495    let (k1, b) = (BM25_K1, BM25_B);
496    let n = groups.len().max(1) as f64;
497    let ndocs = groups.iter().map(Vec::len).sum::<usize>().max(1) as f64;
498    let avg = groups.iter().flatten().map(Vec::len).sum::<usize>() as f64 / ndocs;
499    let mut index: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
500    for t in tokens(query) {
501        let next = index.len();
502        index.entry(t).or_insert(next);
503    }
504    // Per document: (query word, tf), ordered by query word, so equal documents sum in the same order.
505    let counted: Vec<Vec<Vec<(usize, f64)>>> = groups
506        .iter()
507        .map(|g| {
508            g.iter()
509                .map(|d| {
510                    let mut tf: Vec<(usize, f64)> = Vec::new();
511                    for q in d.iter().filter_map(|t| index.get(t.as_str())) {
512                        match tf.iter_mut().find(|(x, _)| x == q) {
513                            Some((_, f)) => *f += 1.0,
514                            None => tf.push((*q, 1.0)),
515                        }
516                    }
517                    tf.sort_by_key(|(q, _)| *q);
518                    tf
519                })
520                .collect()
521        })
522        .collect();
523    let mut df = vec![0.0f64; index.len()];
524    let mut seen: Vec<usize> = Vec::new();
525    for g in &counted {
526        seen.clear();
527        for &(q, _) in g.iter().flatten() {
528            if !seen.contains(&q) {
529                seen.push(q);
530                df[q] += 1.0;
531            }
532        }
533    }
534    let idf: Vec<f64> = df.iter().map(|&d| (1.0 + (n - d + 0.5) / (d + 0.5)).ln()).collect();
535    counted
536        .iter()
537        .zip(groups)
538        .map(|(g, docs)| {
539            let (mut best, mut next) = (0.0f64, 0.0f64);
540            for (tf, d) in g.iter().zip(docs) {
541                let norm = k1 * (1.0 - b + b * d.len() as f64 / avg);
542                let s: f64 = tf.iter().map(|&(q, f)| idf[q] * f * (k1 + 1.0) / (f + norm)).sum();
543                if s > best {
544                    (best, next) = (s, best);
545                } else if s > next {
546                    next = s;
547                }
548            }
549            best + second * next
550        })
551        .collect()
552}
553
554/// The top `k` ranked challenges.
555pub fn select<'a>(challenges: &'a [Challenge], context: &str, k: usize) -> Vec<&'a Challenge> {
556    select_scoped(challenges, context, context, k)
557}
558
559/// `select` with scopes judged against `scope_text` (`rank_scoped`).
560pub fn select_scoped<'a>(challenges: &'a [Challenge], context: &str, scope_text: &str, k: usize) -> Vec<&'a Challenge> {
561    rank_scoped(challenges, context, scope_text).into_iter().take(k).map(|(_, c)| c).collect()
562}
563
564/// An early delivery takes lessons scoring at least this share of the best on-topic match (`early`).
565/// Baseline: today's early rule (R3b, internal evaluation "phase-r"), kept until a learned early rule
566/// is fitted on the share each early delivery's record carries per lesson (outcome.rs `rel`, hook.rs
567/// `early_rel`; empty when no plain lesson was on topic). Those records hold only delivered lessons, and
568/// every plain one scored at least this bar, so a rule fitted on them alone can learn to raise it, not
569/// what a lower bar would admit.
570pub const RELATIVE: f64 = 0.5;
571/// The Stop blocks only when a lesson not yet done scores at least this share of the best match
572/// (`budget`): a block is an extra round, the expensive part. Baseline: the R3b word-matching rule
573/// (`BORG_MATCH=bm25`), not the default path.
574pub const BLOCK: f64 = 0.8;
575/// Once the Stop blocks, every lesson not done scoring at least this share of the best match is asked
576/// (`budget`): more questions in a round that happens anyway cost little. Baseline: as `BLOCK`.
577pub const LOW: f64 = 0.3;
578/// At most this many lessons per Stop block. Baseline: the fixed graded rule's block and free hand-over
579/// (`graded_capped`), the reference the learned policy is gated against (select.rs); it also bounds a
580/// block's length.
581pub const CAP: usize = 10;
582/// At most this many unscoped (generic) lessons per block: generic hygiene does not fill the block.
583/// Baseline: part of the R3b rule (`in_scope_first`).
584pub const GENERIC_CAP: usize = 3;
585
586/// The Stop's two decisions over a ranking of the whole store (best first, as `rank` returns it; the
587/// top is the store's best match, done or not), with `done` the lessons this session already asked,
588/// or delivered early and acted on (R3b, internal evaluation "phase-r", not published):
589/// - **whether to block** (the cost: one more round): only when a lesson not done scores at least
590///   `BLOCK` × the top. A context whose best lessons were delivered early and acted on does not block.
591/// - **what to ask once blocking** (cheap): every lesson not done scoring at least `LOW` × the top,
592///   scoped lessons first (`rank` already dropped those out of scope), at most `GENERIC_CAP` unscoped,
593///   `CAP` in all, ordered by score × the session's usefulness draw (R1, `explored`).
594pub fn budget<'a>(ranked: &[(f64, &'a Challenge)], done: &HashSet<&str>) -> Vec<&'a Challenge> {
595    in_scope_first(explored(budget_pool(ranked, done)))
596}
597
598/// `budget`'s pool before the slots: every lesson not done over `LOW` × the top, with its score; empty
599/// when none not done clears `BLOCK` × the top.
600pub fn budget_pool<'a>(ranked: &[(f64, &'a Challenge)], done: &HashSet<&str>) -> Vec<(f64, &'a Challenge)> {
601    let Some(&(top, _)) = ranked.first() else { return Vec::new() };
602    if !ranked.iter().any(|(s, c)| *s >= BLOCK * top && !done.contains(c.id.as_str())) {
603        return Vec::new();
604    }
605    ranked.iter().copied().filter(|(s, c)| *s >= LOW * top && !done.contains(c.id.as_str())).collect()
606}
607
608/// The consequence model decided to block (`predicted`, non-empty): ask its lessons and every other
609/// lesson not done over `LOW` × the best match, in-scope first, ordered by score × draw, at most `CAP`.
610pub fn widen<'a>(ranked: &[(f64, &'a Challenge)], predicted: &[&'a Challenge], done: &HashSet<&str>) -> Vec<&'a Challenge> {
611    in_scope_first(explored(widen_pool(ranked, predicted, done)))
612}
613
614/// `widen`'s pool before the slots: the model's picks (at least the top score) and every other lesson
615/// not done over `LOW` × the top, with their scores; empty when the model picked none.
616pub fn widen_pool<'a>(ranked: &[(f64, &'a Challenge)], predicted: &[&'a Challenge], done: &HashSet<&str>) -> Vec<(f64, &'a Challenge)> {
617    if predicted.is_empty() {
618        return Vec::new();
619    }
620    let top = ranked.first().map_or(0.0, |r| r.0);
621    let score = |c: &Challenge| ranked.iter().find(|(_, x)| x.id == c.id).map_or(0.0, |r| r.0);
622    // The model's picks stay in even below the bar; they lead ties.
623    let mut pool: Vec<(f64, &Challenge)> = predicted.iter().map(|c| (score(c).max(top), *c)).collect();
624    for &(s, c) in ranked {
625        if s >= LOW * top && !done.contains(c.id.as_str()) && !pool.iter().any(|(_, x)| x.id == c.id) {
626            pool.push((s, c));
627        }
628    }
629    pool
630}
631
632/// The graded Stop decision (the default, unless `BORG_STOP_GRADED=off`; internal evaluation "whole-store", "Graded follow-up", not published) over the
633/// model's graded applies, in its order (3 certain, 2 likely, 1 worth a thought). Returns what to ask in
634/// a block and what to hand over free:
635/// - **block** (an extra round) only when at least one lesson is graded 3; then ask every 3 and 2, and
636///   the 1s while the block has fewer than `CAP` lessons. 2s and 1s alone never block.
637/// - **without a block**, the 2s and then the 1s, at most `CAP`, go to the drone free as early context at
638///   its next prompt or touch (hook.rs `queued`).
639pub fn graded<'a>(applied: &[(&'a Challenge, u8)]) -> (Vec<&'a Challenge>, Vec<&'a Challenge>) {
640    graded_capped(applied, ask_cap())
641}
642
643/// `BORG_STOP_ASK_CAP=N` (evaluation only): a block asks only the 3s, the first `N` in the model's
644/// order; without a 3 nothing changes. Unset, a block asks as `graded` says.
645pub fn ask_cap() -> Option<usize> {
646    std::env::var("BORG_STOP_ASK_CAP").ok().and_then(|v| v.trim().parse().ok()).filter(|n| *n > 0)
647}
648
649/// `graded` with an explicit cap on a block (`ask_cap`).
650pub fn graded_capped<'a>(applied: &[(&'a Challenge, u8)], cap: Option<usize>) -> (Vec<&'a Challenge>, Vec<&'a Challenge>) {
651    graded_without(applied, cap, &[])
652}
653
654/// `graded_capped` for a session that already had the lessons `had` delivered (ids in any order,
655/// select.rs `Ctx::had`): such a lesson may still be asked, but never takes a free slot, which the
656/// delivery would drop as given before (hook.rs `queued`); the next 2 or 1 takes it. With `had` empty
657/// this is `graded_capped`, the rule every record before select.rs `nofree` was decided by.
658pub fn graded_without<'a>(applied: &[(&'a Challenge, u8)], cap: Option<usize>, had: &[String]) -> (Vec<&'a Challenge>, Vec<&'a Challenge>) {
659    let of = |g: u8| applied.iter().filter(move |(_, x)| *x == g).map(|(c, _)| *c);
660    if of(3).next().is_none() {
661        return (Vec::new(), of(2).chain(of(1)).filter(|c| !had.contains(&c.id)).take(CAP).collect());
662    }
663    if let Some(n) = cap {
664        return (of(3).take(n).collect(), Vec::new());
665    }
666    let mut ask: Vec<&Challenge> = of(3).chain(of(2)).collect();
667    let room = CAP.saturating_sub(ask.len());
668    ask.extend(of(1).take(room));
669    (ask, Vec::new())
670}
671
672/// Lessons that cleared the bar, in the order of score × the session's usefulness draw (`explore`):
673/// Thompson sampling over the slots. Without a session every draw is 1 and this is the score order.
674pub fn explored<'a>(passed: impl IntoIterator<Item = (f64, &'a Challenge)>) -> Vec<&'a Challenge> {
675    let mut v: Vec<(f64, &Challenge)> = passed.into_iter().map(|(s, c)| (s * c.explore, c)).collect();
676    v.sort_by(|a, b| b.0.total_cmp(&a.0));
677    v.into_iter().map(|(_, c)| c).collect()
678}
679
680/// Candidates in their order, scoped ones first, at most `GENERIC_CAP` unscoped, `CAP` in all.
681pub fn in_scope_first<'a>(candidates: impl IntoIterator<Item = &'a Challenge>) -> Vec<&'a Challenge> {
682    let (scoped, generic): (Vec<&Challenge>, Vec<&Challenge>) = candidates.into_iter().partition(|c| !c.scope.is_empty());
683    scoped.into_iter().chain(generic.into_iter().take(GENERIC_CAP)).take(CAP).collect()
684}
685
686/// Method: the draws behind a propensity estimate (`propensity`): precision, not a tuning knob
687/// (standard error ≤ 1/(2√P_DRAWS) ≈ 0.022).
688pub const P_DRAWS: usize = 512;
689
690/// Each pooled lesson's chance of a slot under the session's posterior (`budget`, `widen`): the share of
691/// `P_DRAWS` alternative draws in which `in_scope_first`, over the pool ordered by score × draw, keeps
692/// it. A draw is the ratio `explore` is (memory.rs `Memory::weight`): (0.5 + x) / (0.5 + mean), x from
693/// the lesson's belief, seeded by (`session#p<i>`, id). Exactly 1 for every lesson when the pool fits the
694/// slots, without a draw. Deterministic.
695pub fn propensity(pool: &[(f64, &Challenge)], session: &str) -> std::collections::HashMap<String, f64> {
696    if pool.iter().filter(|(_, c)| c.scope.is_empty()).count() <= GENERIC_CAP && pool.len() <= CAP {
697        return pool.iter().map(|(_, c)| (c.id.clone(), 1.0)).collect();
698    }
699    kept_share(pool, session, |order| in_scope_first(order).into_iter().map(|c| c.id.clone()).collect())
700}
701
702/// The share of `P_DRAWS` draws (`propensity`) in which `keep`, given the pool ordered by score × draw,
703/// keeps each pooled lesson.
704fn kept_share(pool: &[(f64, &Challenge)], session: &str, keep: impl Fn(Vec<&Challenge>) -> Vec<String>) -> std::collections::HashMap<String, f64> {
705    let draw = |c: &Challenge, i: usize| {
706        let (a, b) = c.belief;
707        let x = crate::memory::draw(a, b, crate::memory::seed(&format!("{session}#p{i}"), &c.id));
708        (0.5 + x) / (0.5 + a / (a + b))
709    };
710    let mut kept: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
711    for i in 0..P_DRAWS {
712        let mut v: Vec<(f64, &Challenge)> = pool.iter().map(|&(s, c)| (s * draw(c, i), c)).collect();
713        v.sort_by(|a, b| b.0.total_cmp(&a.0));
714        for id in keep(v.into_iter().map(|(_, c)| c).collect()) {
715            *kept.entry(id).or_default() += 1;
716        }
717    }
718    pool.iter().map(|(_, c)| (c.id.clone(), kept.get(&c.id).copied().unwrap_or(0) as f64 / P_DRAWS as f64)).collect()
719}
720
721/// A pooled lesson's score without its usefulness factor: s / (0.5 + mean belief) = relevance ×
722/// squash(A) × trust / NEUTRAL (`rank`, memory.rs `Memory::weight`). Under another belief the score is
723/// base × (0.5 + its mean), and `propensity` orders by base × (0.5 + draw), so `borg debug ope` (ope.rs) can
724/// replay a slot under other weights.
725pub fn pool_base(s: f64, c: &Challenge) -> f64 {
726    let (a, b) = c.belief;
727    s / (0.5 + a / (a + b))
728}
729
730/// At most this many lessons per early delivery (`early`). Baseline: today's early rule, as `RELATIVE`.
731pub const EARLY_CAP: usize = 5;
732/// An early delivery's text stops before this many characters (about 500 tokens), a free hand-over's
733/// too (hook.rs `queued`), less the lines handed over in place of questions (`render_owing`). Guard: bounds the context one delivery adds to the drone's turn; what it
734/// cuts is logged (`dropped_chars`, outcome.rs `DELIVERY`), so its hit rate is measured.
735pub const EARLY_CHARS: usize = 2000;
736/// The characters of a lesson's question an early delivery's line shows at most, then `…`
737/// (`render_early`). Display: short enough that `EARLY_CHARS` holds several lessons, long enough for
738/// a question.
739pub const EARLY_QUESTION_CHARS: usize = 300;
740/// The characters of its consequence the line shows at most. Display: the consequence explains the
741/// question, so it gets less room.
742pub const EARLY_CONSEQUENCE_CHARS: usize = 200;
743/// The characters of the team rule it replaces the line shows at most. Display: a pointer to the old
744/// rule, not the rule itself.
745pub const EARLY_OVERRIDES_CHARS: usize = 150;
746
747/// The scope names of `challenges` that `text` names (`Names::contains`), unique, in store order.
748pub fn named_scopes(challenges: &[Challenge], text: &str) -> Vec<String> {
749    let have = Names::of(text);
750    let mut out: Vec<String> = Vec::new();
751    for s in challenges.iter().flat_map(|c| &c.scope) {
752        if !out.contains(s) && have.contains(s) {
753            out.push(s.clone());
754        }
755    }
756    out
757}
758
759/// Early delivery: the scoped lessons a context brings into scope through one of `topics` (scope names
760/// it just named for the first time), ranked over the whole `context`, scoring at least `RELATIVE` × the
761/// best of them (done or not), minus those already delivered or asked (`done`), at most `EARLY_CAP`. Unscoped lessons
762/// never come early: generic hygiene has no topic, and only a named system says the drone is on one. Standing
763/// lessons (ratified constraints, `Challenge::standing`) come first on their topic, matched or not (`standing_pool`).
764pub fn early<'a>(challenges: &'a [Challenge], context: &str, topics: &[String], done: &HashSet<&str>) -> Vec<&'a Challenge> {
765    let pool: Vec<(f64, &Challenge)> = standing_pool(challenges, topics, done).into_iter().chain(early_pool(challenges, context, topics, done)).collect();
766    explored(pool).into_iter().take(EARLY_CAP).collect()
767}
768
769/// `early`'s pool of plain lessons before the slots: every on-topic lesson not done over `RELATIVE` ×
770/// the best of them, with its score. Never a standing lesson: those need no match (`standing_pool`).
771pub fn early_pool<'a>(challenges: &'a [Challenge], context: &str, topics: &[String], done: &HashSet<&str>) -> Vec<(f64, &'a Challenge)> {
772    let on_topic = Names::of_all(topics.iter().map(String::as_str));
773    let any = topics.iter().any(|t| t == ANY);
774    let ranked: Vec<(f64, &Challenge)> = rank(challenges, context)
775        .into_iter()
776        .filter(|(_, c)| !c.standing() && ((!c.scope.is_empty() && c.scope.iter().any(|s| on_topic.contains(s))) || (any && c.consolidated)))
777        .collect();
778    // The best on-topic match, done or not, sets the bar (as in `budget`).
779    let Some(&(top, _)) = ranked.first() else { return Vec::new() };
780    ranked.into_iter().filter(|(s, c)| *s >= RELATIVE * top && !done.contains(c.id.as_str())).collect()
781}
782
783/// The standing lessons on `topics` not done (a named scope's; with `ANY`, the unscoped ones), each
784/// with an infinite score: it comes ahead of every match and of every draw, matched or not.
785pub fn standing_pool<'a>(challenges: &'a [Challenge], topics: &[String], done: &HashSet<&str>) -> Vec<(f64, &'a Challenge)> {
786    let on_topic = Names::of_all(topics.iter().map(String::as_str));
787    let any = topics.iter().any(|t| t == ANY);
788    challenges
789        .iter()
790        .filter(|c| c.standing() && !c.off_system && !done.contains(c.id.as_str()))
791        .filter(|c| c.scope.iter().any(|s| on_topic.contains(s)) || (any && c.scope.is_empty()))
792        .map(|c| (f64::INFINITY, c))
793        .collect()
794}
795
796/// Each pooled lesson's chance of being delivered early under the session's posterior (`early` over
797/// `early_pool`): `propensity`'s draws, keeping in each the first `EARLY_CAP` and of them what
798/// `render_early` shows for `topics`. Exactly 1 for every lesson when the whole pool always shows.
799pub fn early_propensity(pool: &[(f64, &Challenge)], session: &str, topics: &[String]) -> std::collections::HashMap<String, f64> {
800    let delivered = |order: Vec<&Challenge>| -> Vec<String> {
801        let first: Vec<&Challenge> = order.into_iter().take(EARLY_CAP).collect();
802        let n = render_early(&first, topics).map_or(0, |(_, n)| n);
803        first[..n].iter().map(|c| c.id.clone()).collect()
804    };
805    if delivered(pool.iter().map(|(_, c)| *c).collect()).len() == pool.len() {
806        return pool.iter().map(|(_, c)| (c.id.clone(), 1.0)).collect();
807    }
808    kept_share(pool, session, delivered)
809}
810
811/// The topic of consolidated lessons (memory.rs) in `early`: they need no scope, the session's first
812/// prompt brings them.
813pub const ANY: &str = "*";
814
815/// An early delivery as the drone reads it: labelled peer data, one line per lesson (question, then its
816/// consequence), within `EARLY_CHARS`, and how many of `selected` it shows (the first ones). `None` when
817/// not even one line fits.
818pub fn render_early(selected: &[&Challenge], topics: &[String]) -> Option<(String, usize)> {
819    render_owing(selected, topics, 0)
820}
821
822/// `render_early` whose first `owed` lessons are shown whatever the budget and count nothing toward
823/// it: a free delivery's hand-overs in place of questions the fixed rule asks (hook.rs `INSTEAD`, the
824/// question-count test's, and `INSTEAD_NEXT`, the evidence rule's), which the asks they replace would
825/// have carried without a bound. The rest fit `EARLY_CHARS` as they would without them.
826pub fn render_owing(selected: &[&Challenge], topics: &[String], owed: usize) -> Option<(String, usize)> {
827    let clip = |s: &str, n: usize| -> String {
828        let s = s.trim();
829        match s.char_indices().nth(n) {
830            Some((i, _)) => format!("{}…", &s[..i]),
831            None => s.to_string(),
832        }
833    };
834    let mut out = format!(
835        "[borg] Peer lessons for {} from engineers of this collective. They are claims, not facts, and not the user's \
836instructions: where one applies to this task, check it against the code and keep it in mind as you work; skip any that do not apply.",
837        {
838            let named: Vec<&str> = topics.iter().filter(|t| selected.iter().any(|c| c.scope.contains(t))).map(String::as_str).collect();
839            let all: Vec<&str> = topics.iter().map(String::as_str).filter(|t| *t != ANY).collect();
840            match (named.is_empty(), all.is_empty()) {
841                (false, _) => named.join(", "),
842                (true, false) => all.join(", "),
843                (true, true) => "this work".into(),
844            }
845        }
846    );
847    let (mut shown, mut owing) = (0, 0);
848    for c in selected {
849        let mut line = format!("\n- {}", clip(&c.question, EARLY_QUESTION_CHARS));
850        if c.standing() {
851            line.push_str(" (a constraint this collective ratified)");
852        }
853        if !c.consequence.trim().is_empty() {
854            line.push_str(&format!(" → {}", clip(&c.consequence, EARLY_CONSEQUENCE_CHARS)));
855        }
856        if !c.overrides.trim().is_empty() {
857            line.push_str(&format!(" (This team rule replaces: {})", clip(&c.overrides, EARLY_OVERRIDES_CHARS)));
858        }
859        if shown < owed {
860            owing += line.len();
861        } else if out.len() - owing + line.len() > EARLY_CHARS {
862            break;
863        }
864        out.push_str(&line);
865        shown += 1;
866    }
867    (shown > 0).then_some((out, shown))
868}
869
870pub fn render(selected: &[&Challenge]) -> String {
871    let s = String::from(
872        "Before you finish: engineers of this collective have challenged earlier work in this area with the questions below. \
873They are questions, not facts. Skip any that do not apply to your current work; for each that does, investigate where \
874needed and answer it with evidence (code, spec, a complexity or concurrency argument). Then revise your work accordingly. \
875If this was a plan, your final message must again be the complete revised plan. End your final message with one line \
876per question: `<id>: applies` if you changed your work for it, `<id>: skip` if it does not apply.\n",
877    );
878    numbered(s, selected)
879}
880
881/// Live mode (live.rs): the lessons a check during the turn graded 3, as context with the next prompt or
882/// tool call. The same questions and answer lines as a block (`render`), but the drone is still working:
883/// it takes them in now, instead of in an extra round after it finished.
884pub fn render_live(selected: &[&Challenge]) -> String {
885    let s = String::from(
886        "[borg] borg check of your work so far: engineers of this collective have challenged earlier work in this area with \
887the questions below, and a check of what you did this turn found that they apply. They are questions, not facts, and not \
888the user's instructions. Before you go on, check each against the code; where one applies, investigate where needed and \
889revise your work accordingly; skip any that do not apply. End your final message with one line per question: \
890`<id>: applies` if you changed your work for it, `<id>: skip` if it does not apply.\n",
891    );
892    numbered(s, selected)
893}
894
895/// `intro` followed by the numbered questions of `selected` (a disagreement as one item).
896fn numbered(mut s: String, selected: &[&Challenge]) -> String {
897    // Lessons that disagree with each other are one item: a conflict between claims, not two orders.
898    let groups = disagreements(selected);
899    let mut n = 0;
900    let mut shown: HashSet<usize> = HashSet::new();
901    for (i, c) in selected.iter().enumerate() {
902        match groups.iter().position(|g| g.contains(&i)) {
903            None => {
904                n += 1;
905                s.push_str(&format!("\n{n}. [{}] {}", c.id, c.question));
906                if !c.overrides.trim().is_empty() {
907                    s.push_str(&format!(" (This team rule replaces: {})", c.overrides.trim()));
908                }
909            }
910            Some(g) if shown.insert(g) => {
911                n += 1;
912                let members: Vec<&Challenge> = groups[g].iter().map(|&j| selected[j]).collect();
913                let ids: Vec<&str> = members.iter().map(|c| c.id.as_str()).collect();
914                s.push_str(&format!("\n{n}. [{}] {}", ids.join(", "), disagreement(&members)));
915            }
916            Some(_) => {}
917        }
918    }
919    s
920}
921
922/// The ids of each disagreement `render` shows, for the `asked` outcome record (outcome.rs).
923pub fn disagreement_ids(selected: &[&Challenge]) -> Vec<Vec<String>> {
924    disagreements(selected).into_iter().map(|g| g.into_iter().map(|i| selected[i].id.clone()).collect()).collect()
925}
926
927/// Groups (indices into `selected`, in selection order) of lessons that disagree: the same situation
928/// with different consequences (queen.rs `conflict_pairs`), or one lists the other in `supersedes`
929/// while both are still live (a supersession cycle, or one that does not hide: trust.rs `successors`).
930pub fn disagreements(selected: &[&Challenge]) -> Vec<Vec<usize>> {
931    let mut pairs = crate::queen::conflict_pairs(selected);
932    for (i, a) in selected.iter().enumerate() {
933        for (j, b) in selected.iter().enumerate().skip(i + 1) {
934            if a.supersedes.contains(&b.id) || b.supersedes.contains(&a.id) {
935                pairs.push((i, j));
936            }
937        }
938    }
939    // Union the pairs; each group keeps selection order.
940    fn root(g: &mut [usize], mut i: usize) -> usize {
941        while g[i] != i {
942            g[i] = g[g[i]];
943            i = g[i];
944        }
945        i
946    }
947    let mut parent: Vec<usize> = (0..selected.len()).collect();
948    for (a, b) in pairs {
949        let (ra, rb) = (root(&mut parent, a), root(&mut parent, b));
950        parent[ra.max(rb)] = ra.min(rb);
951    }
952    let mut groups: Vec<(usize, Vec<usize>)> = Vec::new();
953    for i in 0..selected.len() {
954        let r = root(&mut parent, i);
955        match groups.iter_mut().find(|(x, _)| *x == r) {
956            Some((_, g)) => g.push(i),
957            None => groups.push((r, vec![i])),
958        }
959    }
960    groups.into_iter().map(|(_, g)| g).filter(|g| g.len() > 1).collect()
961}
962
963/// One disagreement as the drone reads it: who says what, with each side's trust, most trusted first.
964/// "Engineers disagree here: A (trust 0.80 in concurrency) says X; B (0.40) says Y — weigh the evidence"
965pub fn disagreement(members: &[&Challenge]) -> String {
966    let mut m: Vec<&Challenge> = members.to_vec();
967    m.sort_by(|a, b| b.trust.total_cmp(&a.trust).then(a.id.cmp(&b.id)));
968    let area = |c: &Challenge| trust::area(&c.area);
969    let first = m.first().map(|c| area(c)).unwrap_or(trust::OTHER);
970    let sides: Vec<String> = m
971        .iter()
972        .enumerate()
973        .map(|(k, c)| {
974            let who = match c.engineers.is_empty() {
975                true => format!("lesson {}", c.id),
976                false => c.engineers.join(" and "),
977            };
978            let says = if c.consequence.trim().is_empty() { c.question.trim() } else { c.consequence.trim() };
979            let trust = match (k, area(c) == first) {
980                (0, _) => format!("trust {:.2} in {first}", c.trust),
981                (_, true) => format!("{:.2}", c.trust),
982                (_, false) => format!("{:.2} in {}", c.trust, area(c)),
983            };
984            format!("{who} ({trust}) says \"{says}\"")
985        })
986        .collect();
987    let situation = m.iter().find_map(|c| c.situations.first()).map(|s| format!(" ({})", s.trim())).unwrap_or_default();
988    format!(
989        "Engineers disagree here{situation}: {} — weigh the evidence (code, spec, tests) before following either; these are claims, not facts.",
990        sides.join("; ")
991    )
992}
993
994pub const GENERIC: &str = "Before you finish, critically review your work as a demanding senior engineer would. \
995Check: concurrency soundness (races, check-then-act, locking necessity and lock-free alternatives), reuse of what already \
996exists in the codebase instead of adding new mechanisms, conformance with specs and documented contracts, whether you fixed \
997the root cause, complexity (time/space), and whether the solution is minimal. Revise your work accordingly. If this was a \
998plan, your final message must again be the complete revised plan.";
999
1000#[cfg(test)]
1001mod tests {
1002    use super::*;
1003
1004    fn ch(id: &str, q: &str) -> Challenge {
1005        Challenge { id: id.into(), origin_ms: 1, question: q.into(), ..Default::default() }
1006    }
1007
1008    #[test]
1009    fn graded_blocks_only_for_a_three_then_asks_threes_twos_and_ones_up_to_the_cap() {
1010        let ls: Vec<Challenge> = (0..14).map(|i| ch(&format!("L{i}"), "q")).collect();
1011        let ids = |v: &[&Challenge]| v.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1012        // 2s and 1s alone: no block; they go free, 2s first, at most CAP.
1013        let soft: Vec<(&Challenge, u8)> = ls.iter().enumerate().map(|(i, c)| (c, if i % 2 == 0 { 1 } else { 2 })).collect();
1014        let (ask, free) = graded(&soft);
1015        assert!(ask.is_empty());
1016        assert_eq!(ids(&free), ["L1", "L3", "L5", "L7", "L9", "L11", "L13", "L0", "L2", "L4"]);
1017        // One 3: block with the 3, every 2, and 1s until CAP; nothing free.
1018        let mixed = vec![(&ls[0], 1), (&ls[1], 2), (&ls[2], 3), (&ls[3], 1), (&ls[4], 2)];
1019        let (ask, free) = graded(&mixed);
1020        assert_eq!((ids(&ask), free.len()), (vec!["L2".to_string(), "L1".into(), "L4".into(), "L0".into(), "L3".into()], 0));
1021        // Twos are never cut for ones; ones fill only the room left.
1022        let full: Vec<(&Challenge, u8)> = ls
1023            .iter()
1024            .enumerate()
1025            .map(|(i, c)| {
1026                (
1027                    c,
1028                    match i {
1029                        0 => 3,
1030                        1..=9 => 2,
1031                        _ => 1,
1032                    },
1033                )
1034            })
1035            .collect();
1036        assert_eq!(ids(&graded(&full).0), ids(&ls[..10].iter().collect::<Vec<_>>()));
1037        // A cap keeps only the first 3s; no 3, no change.
1038        let two_threes = vec![(&ls[0], 2), (&ls[1], 3), (&ls[2], 1), (&ls[3], 3)];
1039        let (ask, free) = graded_capped(&two_threes, Some(1));
1040        assert_eq!((ids(&ask), free.len()), (vec!["L1".to_string()], 0));
1041        assert_eq!(ids(&graded_capped(&two_threes, Some(5)).0), ["L1", "L3"]);
1042        let (ask, free) = graded_capped(&soft, Some(1));
1043        assert!(ask.is_empty() && free.len() == CAP);
1044        let (ask, free) = graded(&[]);
1045        assert!(ask.is_empty() && free.is_empty());
1046    }
1047
1048    #[test]
1049    fn outcome_weight_reorders_the_shortlist() {
1050        use crate::outcome::{ASKED, CORRECTED, IGNORED, NOT_CORRECTED, Outcome, append, path_beside};
1051        let dir = std::env::temp_dir().join(format!("borg-conscience-{}", std::process::id()));
1052        let _ = std::fs::remove_dir_all(&dir);
1053        let lessons = dir.join("lessons.jsonl");
1054        std::fs::create_dir_all(&dir).unwrap();
1055        // Two equally relevant lessons; "generic" is newer, so it wins the tie without outcomes.
1056        let line =
1057            |id: &str, ms: i64| format!("{}\n", serde_json::json!({"id": id, "origin_ms": ms, "question": "Is the check-then-act on the shared flag atomic?"}));
1058        std::fs::write(&lessons, line("specific", 1) + &line("generic", 2)).unwrap();
1059        let plan = "check-then-act on the shared closed flag";
1060        let ids = |cs: &[Challenge]| select(cs, plan, 2).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1061        assert_eq!(ids(&load(&lessons, None)), ["generic", "specific"]);
1062        // Asked twice: corrected anyway in s1, ignored (judged unchanged) in s2: Beta(1, 4), mean 0.2; s2's
1063        // settle (not corrected, censored) adds nothing. Two sessions on the clock: "specific" (born
1064        // before s1) is 3 ticks old, "generic" 2.
1065        let o = |kind: &str, s: &str, ms, l: &str| Outcome {
1066            kind: kind.into(),
1067            session: s.into(),
1068            lessons: vec![l.into()],
1069            ms,
1070            repo: "r".into(),
1071            ..Default::default()
1072        };
1073        for x in [
1074            o(ASKED, "s1", 1, "generic"),
1075            o(CORRECTED, "s1", 2, "generic"),
1076            o(ASKED, "s2", 3, "generic"),
1077            o(IGNORED, "s2", 4, "generic"),
1078            o(NOT_CORRECTED, "s2", 4, "generic"),
1079        ] {
1080            append(&path_beside(&lessons), &x).unwrap();
1081        }
1082        let cs = load(&lessons, None);
1083        let w = |cs: &[Challenge], id: &str| cs.iter().find(|c| c.id == id).unwrap().weight;
1084        let sq = |age: f64| crate::memory::squash(age.powf(-0.5).ln());
1085        assert!((w(&cs, "generic") - sq(2.0) * 0.7).abs() < 1e-12 && (w(&cs, "specific") - sq(3.0)).abs() < 1e-12);
1086        assert_eq!(ids(&cs), ["specific", "generic"]);
1087        // A change (a use) lifts a lesson above 1 and back to the top: Beta(2, 4) and a fresh deposit.
1088        for x in [
1089            o(ASKED, "s3", 5, "generic"),
1090            o(crate::outcome::CHANGED, "s3", 6, "generic"),
1091            o(ASKED, "s4", 7, "generic"),
1092            o(crate::outcome::CHANGED, "s4", 8, "generic"),
1093        ] {
1094            append(&path_beside(&lessons), &x).unwrap();
1095        }
1096        let cs = load(&lessons, None);
1097        assert!(w(&cs, "generic") > w(&cs, "specific"), "{} {}", w(&cs, "generic"), w(&cs, "specific"));
1098        assert_eq!(ids(&cs), ["generic", "specific"]);
1099        let _ = std::fs::remove_dir_all(dir);
1100    }
1101
1102    fn store(name: &str, lines: &[serde_json::Value], outcomes: &[(&str, &str, &str)]) -> std::path::PathBuf {
1103        let dir = std::env::temp_dir().join(format!("borg-conscience-{name}-{}", std::process::id()));
1104        let _ = std::fs::remove_dir_all(&dir);
1105        std::fs::create_dir_all(&dir).unwrap();
1106        let text: String = lines.iter().map(|l| format!("{l}\n")).collect();
1107        std::fs::write(dir.join("lessons.jsonl"), text).unwrap();
1108        for (kind, session, id) in outcomes {
1109            let o = crate::outcome::Outcome {
1110                kind: kind.to_string(),
1111                session: session.to_string(),
1112                lessons: vec![id.to_string()],
1113                ms: 1,
1114                repo: "r".into(),
1115                ..Default::default()
1116            };
1117            crate::outcome::append(&dir.join("outcomes.jsonl"), &o).unwrap();
1118        }
1119        dir
1120    }
1121
1122    #[test]
1123    fn author_trust_in_the_area_reorders_the_shortlist() {
1124        use crate::outcome::{CORRECTED, NOT_CORRECTED};
1125        use serde_json::json;
1126        let q = "Is the check-then-act on the shared flag atomic?";
1127        // Equally relevant; "weak" is newer and wins the tie without evidence. Their authors' other
1128        // concurrency lessons differ in outcome: bob's keep being corrected anyway, ann's are followed.
1129        // (Their own lessons have no outcomes, so the per-lesson outcome weight is 1 for both.)
1130        let lines = [
1131            json!({"id": "strong", "origin_ms": 1, "question": q, "area": "concurrency", "engineers": ["ann@x"]}),
1132            json!({"id": "weak", "origin_ms": 2, "question": q, "area": "concurrency", "engineers": ["bob@x"]}),
1133            json!({"id": "ann-old", "origin_ms": 0, "question": "unrelated", "area": "concurrency", "engineers": ["ann@x"]}),
1134            json!({"id": "bob-old", "origin_ms": 0, "question": "unrelated", "area": "concurrency", "engineers": ["bob@x"]}),
1135            json!({"id": "bob-sec", "origin_ms": 0, "question": "unrelated", "area": "security", "engineers": ["bob@x"]}),
1136        ];
1137        let plan = "check-then-act on the shared closed flag";
1138        let ids = |cs: &[Challenge]| select(cs, plan, 2).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1139        let neutral = store("trust-neutral", &lines, &[]);
1140        let cs = load(&neutral.join("lessons.jsonl"), None);
1141        assert_eq!(ids(&cs), ["weak", "strong"]);
1142        assert!(cs.iter().all(|c| c.trust == trust::NEUTRAL && c.weight == 1.0));
1143        // Neutral trust leaves BM25 scores unchanged (trust / 0.5 = 1).
1144        let raw = bm25(&cs.iter().map(|c| tokens(&c.question)).collect::<Vec<_>>(), plan)[0];
1145        assert!((rank(&cs, plan)[1].0 - raw).abs() < 1e-12);
1146        // bob's evidence in security does not touch his concurrency trust.
1147        let outs = [(CORRECTED, "s1", "bob-old"), (CORRECTED, "s2", "bob-old"), (NOT_CORRECTED, "s1", "ann-old"), (NOT_CORRECTED, "s3", "bob-sec")];
1148        let earned = store("trust-earned", &lines, &outs);
1149        let cs = load(&earned.join("lessons.jsonl"), None);
1150        let t = |id: &str| cs.iter().find(|c| c.id == id).unwrap().trust;
1151        assert_eq!((t("strong"), t("weak")), (2.0 / 3.0, 0.25));
1152        assert_eq!(ids(&cs), ["strong", "weak"]);
1153        for d in [neutral, earned] {
1154            let _ = std::fs::remove_dir_all(d);
1155        }
1156    }
1157
1158    #[test]
1159    fn a_superseded_lesson_is_not_asked_its_successor_is() {
1160        use serde_json::json;
1161        let lines = [
1162            json!({"id": "lock", "origin_ms": 1, "question": "Is the closed flag guarded by the delivery ReentrantLock?", "engineers": ["ann@x"]}),
1163            // The same engineer reverses himself; the new lesson shares few words with the plan.
1164            json!({"id": "atomic", "origin_ms": 2, "question": "Would a CAS suffice?", "engineers": ["ann@x"], "supersedes": ["lock"]}),
1165        ];
1166        let dir = store("superseded", &lines, &[]);
1167        let cs = load(&dir.join("lessons.jsonl"), None);
1168        let plan = "guard the closed flag with the delivery ReentrantLock";
1169        let sel = select(&cs, plan, 5);
1170        assert_eq!(sel.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), ["atomic"], "the successor inherits the relevance");
1171        assert!(!render(&sel).contains("ReentrantLock"));
1172        assert_eq!(cs.iter().find(|c| c.id == "lock").unwrap().trust, NEUTRAL_REVERSED);
1173        let _ = std::fs::remove_dir_all(dir);
1174    }
1175
1176    /// ann's trust after one reversal of a lesson in "other" (the area both lessons default to):
1177    /// her successor is hers too, so both carry the penalty.
1178    const NEUTRAL_REVERSED: f64 = 0.25;
1179
1180    #[test]
1181    fn disagreeing_lessons_render_as_one_conflict_with_trust() {
1182        let mk = |id: &str, eng: &str, area: &str, consequence: &str, t: f64| Challenge {
1183            id: id.into(),
1184            origin_ms: 1,
1185            question: format!("question of {id}"),
1186            situations: vec!["check-then-act on a shared mutable flag across threads".into()],
1187            consequence: consequence.into(),
1188            area: area.into(),
1189            engineers: vec![eng.into()],
1190            trust: t,
1191            ..Default::default()
1192        };
1193        let a = mk("A", "bob@x", "concurrency", "guard it with the existing ReentrantLock", 0.4);
1194        let b = mk("B", "ann@x", "concurrency", "use a lock-free compareAndSet instead", 0.8);
1195        let other = Challenge { id: "C".into(), question: "Is the spec cited?".into(), ..Default::default() };
1196        let text = render(&[&a, &other, &b]);
1197        assert!(
1198            text.contains("\n1. [A, B] Engineers disagree here (check-then-act on a shared mutable flag across threads): ann@x (trust 0.80 in concurrency) says \"use a lock-free compareAndSet instead\"; bob@x (0.40) says \"guard it with the existing ReentrantLock\" — weigh the evidence"),
1199            "{text}"
1200        );
1201        assert!(text.contains("\n2. [C] Is the spec cited?") && !text.contains("question of"), "{text}");
1202        // A supersession cycle between two asked lessons is a disagreement too, whatever the wording.
1203        let x = Challenge { id: "X".into(), question: "Lock?".into(), supersedes: vec!["Y".into()], engineers: vec!["ann@x".into()], ..Default::default() };
1204        let y = Challenge { id: "Y".into(), question: "Atomic?".into(), supersedes: vec!["X".into()], area: "scope".into(), ..Default::default() };
1205        let text = render(&[&x, &y]);
1206        assert!(
1207            text.contains("1. [X, Y] Engineers disagree here: ann@x (trust 0.50 in other) says \"Lock?\"; lesson Y (0.50 in scope) says \"Atomic?\""),
1208            "{text}"
1209        );
1210        assert!(!text.contains("\n2."));
1211        // Agreeing lessons stay separate questions.
1212        let c = mk("C2", "cy@x", "concurrency", "guard it with the existing ReentrantLock", 0.5);
1213        assert!(render(&[&a, &c]).contains("\n2. [C2] question of C2"));
1214        // A live check's asks: the same numbered questions and answer lines, as a mid-turn notice.
1215        let live = render_live(&[&a, &c]);
1216        assert!(live.starts_with("[borg] borg check of your work so far:") && live.contains("`<id>: applies`"), "{live}");
1217        assert!(live.contains("\n2. [C2] question of C2") && !live.contains("Before you finish"), "{live}");
1218    }
1219
1220    #[test]
1221    fn a_less_trusted_contradiction_is_shown_as_a_disagreement_not_hidden() {
1222        use crate::outcome::{CORRECTED, NOT_CORRECTED};
1223        use serde_json::json;
1224        let q = "Is the closed flag guarded by the delivery ReentrantLock?";
1225        let lines = [
1226            json!({"id": "lock", "origin_ms": 1, "question": q, "consequence": "guard it with the existing ReentrantLock",
1227                "situations": ["check-then-act on the closed flag"], "area": "concurrency", "engineers": ["ann@x"]}),
1228            json!({"id": "cas", "origin_ms": 2, "question": "Would a CAS on the closed flag ReentrantLock path suffice?", "consequence": "use compareAndSet",
1229                "situations": ["check-then-act on the closed flag"], "area": "concurrency", "engineers": ["bob@x"], "supersedes": ["lock"]}),
1230            json!({"id": "ann-old", "origin_ms": 0, "question": "unrelated", "area": "concurrency", "engineers": ["ann@x"]}),
1231            json!({"id": "bob-old", "origin_ms": 0, "question": "unrelated", "area": "concurrency", "engineers": ["bob@x"]}),
1232        ];
1233        let dir = store("weak-supersedes", &lines, &[(NOT_CORRECTED, "s1", "ann-old"), (CORRECTED, "s2", "bob-old")]);
1234        let cs = load(&dir.join("lessons.jsonl"), None);
1235        let plan = "guard the closed flag with the delivery ReentrantLock";
1236        let sel = select(&cs, plan, 5);
1237        let ids: Vec<&str> = sel.iter().map(|c| c.id.as_str()).collect();
1238        assert!(ids.contains(&"lock") && ids.contains(&"cas"), "{ids:?}");
1239        let text = render(&sel);
1240        assert!(text.contains("Engineers disagree here") && text.contains("ann@x (trust 0.67 in concurrency)"), "{text}");
1241        assert_eq!(disagreement_ids(&sel), [vec!["lock".to_string(), "cas".to_string()]]);
1242        let _ = std::fs::remove_dir_all(dir);
1243    }
1244
1245    #[test]
1246    fn a_scoped_lesson_is_asked_only_where_its_scope_is_named() {
1247        let drain = Challenge {
1248            id: "drain".into(),
1249            question: "Is each per-turn place drained by an explicit consumer instead of a new reset arc?".into(),
1250            scope: vec!["Orion".into()],
1251            overrides: "upstream petri-net-design seeds a budget with a reset arc on the starting transition".into(),
1252            ..ch("drain", "")
1253        };
1254        let other = Challenge { scope: vec!["search lab".into()], ..ch("lab", "Is the reset arc per-turn place budget pinned?") };
1255        let open = ch("open", "Does every per-turn token have a consumer?");
1256        let cs = vec![drain, other, open];
1257        let ids = |ctx: &str| select(&cs, ctx, 5).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1258        // k2-shaped: a print-shop net, same Petri words, no Orion: only the unscoped lesson.
1259        assert_eq!(ids("PressNet: reset arc on the per-turn reprint budget place"), ["open"]);
1260        // k1-shaped: the scope is named in a touched path.
1261        let k1 = ids("Read /w/orion-text/src/FlowConfig.java; add a per-turn hint place with a reset arc");
1262        assert!(k1.contains(&"drain".to_string()) && !k1.contains(&"lab".to_string()), "{k1:?}");
1263        // A multi-word scope is a phrase: its words adjacent, in order, short parts included.
1264        assert!(ids("the search-lab reset arc per-turn budget").contains(&"lab".to_string()));
1265        assert!(ids("SearchLab: reset arc per-turn budget").contains(&"lab".to_string()));
1266        assert!(!ids("search the lab: reset arc per-turn budget").contains(&"lab".to_string()));
1267        let text = render(&[&cs[0]]);
1268        assert!(text.contains("instead of a new reset arc? (This team rule replaces: upstream petri-net-design seeds"), "{text}");
1269        // A superseded scoped lesson out of scope passes no relevance to its successor.
1270        let succ = Challenge { supersedes: vec!["drain".into()], ..ch("succ", "Unrelated wording") };
1271        let cs2 = vec![cs[0].clone(), succ];
1272        assert!(select(&cs2, "per-turn place reset arc consumer", 5).is_empty());
1273    }
1274
1275    #[test]
1276    fn scope_names_match_as_phrases_or_identifiers_never_as_scattered_words() {
1277        assert_eq!(
1278            segments("HTTPClientFactory cart-link-v2 harbor_orion SR3Review"),
1279            ["http", "client", "factory", "cart", "link", "v2", "harbor", "orion", "sr3", "review"]
1280        );
1281        // The k2 shape: a print-shop net whose final message says "guard" and "output arc" apart.
1282        let k2 = Names::of(
1283            "Read /w/press/src/PressNet.java. The jam transition's guard now checks the counter; \
1284                            the reprint transition's output arc goes to Ready; reset arc removed. A button links here.",
1285        );
1286        for name in ["Answer Guard", "pay-button", "cart-link-v2", "Orion", "harbor_orion", "ticket-triage-agent"] {
1287            assert!(!k2.contains(name), "{name} must not match k2");
1288        }
1289        assert!(Names::of("wire the AnswerGuard bean").contains("Answer Guard"));
1290        assert!(Names::of("src/quality-acceptance-test/java").contains("quality-acceptance-test"));
1291        assert!(Names::of("the pay-button component").contains("pay-button"));
1292        assert!(!Names::of("the button").contains("pay-button"), "a short part is never dropped");
1293        assert!(Names::of("/w/orion-text/src/OrionConfig.java").contains("Orion"));
1294        assert!(!Names::of_all(["answer", "guard"]).contains("Answer Guard"), "never across two texts");
1295        assert!(!Names::of("").contains("Orion") && !Names::of("x").contains("--"));
1296    }
1297
1298    /// E3 review regression: handbook k2 (a print-shop net, no Orion) at the Stop checkpoint, with the
1299    /// k2 prompt, the touched PressNet paths and a realistic final message. A Orion lesson whose scope
1300    /// list also carried "Answer Guard" ranked first when scope names were bags of words.
1301    #[test]
1302    fn k2_stop_context_asks_no_orion_lesson() {
1303        let guard = Challenge {
1304            scope: vec!["Orion".into(), "harbor_orion".into(), "LiveCheckService".into(), "QuickReplySubnet".into(), "Answer Guard".into()],
1305            ..ch(
1306                "I0a1b2c3d4e5f",
1307                "Have you listed every LLM call whose output reaches the customer, traced through the Petri net from the \
1308guard's output place to each send action, and stated per surface whether the Answer Guard sees it?",
1309            )
1310        };
1311        let reset = Challenge {
1312            scope: vec!["Orion".into(), "pay-button".into(), "cart-link-v2".into()],
1313            ..ch("reset", "Is per-turn state drained instead of cleared by a reset arc on the transition?")
1314        };
1315        let generic = ch("generic", "Does the demo show the changed behaviour for every job, not only the first?");
1316        let cs = vec![guard, reset, generic];
1317        let w = "/tmp/e3live/0a1b2c3d/work/press-queue";
1318        let k2 = format!(
1319            "Operators say only the first jammed job of a shift gets reprinted; every jam after that goes straight to failed. \
1320Every job should get one reprint after a jam before we mark it failed.\n{w}/src/printshop/press/PressNet.java\n{w}/src/printshop/press/ShiftDemo.java\n\
1321The reprint budget was one shift-wide token. Now the jam transition's guard checks the job's reprint count, the reprint transition's \
1322output arc puts the job back into Queued, and the shift-start reset arc is removed. A button in the link view shows it."
1323        );
1324        let ids: Vec<String> = select(&cs, &k2, 5).iter().map(|c| c.id.clone()).collect();
1325        assert_eq!(ids, ["generic"]);
1326        // The same lesson still reaches Orion work.
1327        assert!(select(&cs, &format!("{k2}\n/w/harbor_orion/src/AnswerGuard.java"), 5).iter().any(|c| c.id == "I0a1b2c3d4e5f"));
1328    }
1329
1330    #[test]
1331    fn early_delivers_only_scoped_lessons_on_a_named_topic_that_score_near_the_best() {
1332        let sc = |id: &str, scope: &[&str], q: &str| Challenge { scope: scope.iter().map(|s| s.to_string()).collect(), ..ch(id, q) };
1333        let cs = vec![
1334            sc("live", &["Beacon"], "Does the Beacon replay run its services on live hosts?"),
1335            sc("judge", &["Beacon", "search-lab"], "Is the replay judge exactly the named model?"),
1336            sc("weak", &["Beacon"], "Is the facet mapping evaluated at the relaxed tier?"),
1337            sc("drain", &["Orion"], "Is the replay place drained instead of reset?"),
1338            ch("generic", "Does the replay plan name a control arm and a live judge?"),
1339        ];
1340        let ctx = "Set up the Beacon replay on live hosts with the named judge model";
1341        assert_eq!(named_scopes(&cs, ctx), ["Beacon"]);
1342        assert_eq!(named_scopes(&cs, "/w/search-lab/x and /w/orion-text/y"), ["search-lab", "Orion"]);
1343        let topics = vec!["Beacon".to_string()];
1344        let ids = |done: &HashSet<&str>| early(&cs, ctx, &topics, done).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1345        // "weak" shares no word with the work; "drain" is another topic; "generic" has none.
1346        assert_eq!(ids(&HashSet::new()), ["judge", "live"]);
1347        assert_eq!(ids(&HashSet::from(["live"])), ["judge"]);
1348        assert_eq!(ids(&HashSet::from(["judge"])), ["live"]);
1349        assert!(early(&cs, ctx, &[], &HashSet::new()).is_empty());
1350        let (text, shown) = render_early(&early(&cs, ctx, &topics, &HashSet::new()), &topics).unwrap();
1351        assert_eq!(shown, 2);
1352        assert!(text.starts_with("[borg] Peer lessons for Beacon") && text.ends_with("\n- Does the Beacon replay run its services on live hosts?"), "{text}");
1353        assert!(render_early(&[], &topics).is_none());
1354        // The character cap holds: long lessons are clipped, and lines that would pass it are left out.
1355        let long: Vec<Challenge> = (0..9).map(|i| Challenge { consequence: "c".repeat(900), ..sc(&format!("l{i}"), &["Beacon"], &"q ".repeat(400)) }).collect();
1356        let (text, shown) = render_early(&long.iter().collect::<Vec<_>>(), &topics).unwrap();
1357        assert!(text.chars().count() <= EARLY_CHARS && (1..9).contains(&shown), "{shown} {}", text.len());
1358    }
1359
1360    #[test]
1361    fn the_stop_blocks_only_for_a_strong_lesson_not_done_and_then_asks_generously() {
1362        let sc = |id: &str| Challenge { scope: vec!["Beacon".into()], ..ch(id, "") };
1363        let (s1, s2, s3, s4) = (sc("s1"), sc("s2"), sc("s3"), sc("s4"));
1364        let gs: Vec<Challenge> = (0..6).map(|i| ch(&format!("g{i}"), "")).collect();
1365        let ids = |v: Vec<&Challenge>| v.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1366        let none = HashSet::new();
1367        // Blocking: scoped first whatever their score order, at most GENERIC_CAP generic, nothing under LOW x top.
1368        let ranked: Vec<(f64, &Challenge)> =
1369            vec![(10.0, &gs[0]), (9.0, &s1), (8.0, &gs[1]), (7.0, &gs[2]), (6.0, &s2), (5.5, &gs[3]), (3.0, &s3), (2.9, &s4), (2.0, &gs[4])];
1370        assert_eq!(ids(budget(&ranked, &none)), ["s1", "s2", "s3", "g0", "g1", "g2"]);
1371        // No scope named: generic hygiene alone, three at most.
1372        let generic: Vec<(f64, &Challenge)> = gs.iter().map(|g| (5.0, g)).collect();
1373        assert_eq!(budget(&generic, &none).len(), GENERIC_CAP);
1374        // Many in-scope matches: up to CAP.
1375        let many: Vec<Challenge> = (0..14).map(|i| sc(&format!("a{i}"))).collect();
1376        let ranked_many: Vec<(f64, &Challenge)> = many.iter().map(|c| (5.0, c)).collect();
1377        assert_eq!(budget(&ranked_many, &none).len(), CAP);
1378        assert!(budget(&[], &none).is_empty(), "nothing scores, nothing is asked");
1379        // Whether to block: the strong lessons (>= BLOCK x top: g0, s1, g1) are done, so no extra round,
1380        // although weaker ones are left. One of them not done: block, and ask the weaker ones too.
1381        assert!(budget(&ranked, &HashSet::from(["g0", "s1", "g1"])).is_empty());
1382        assert_eq!(ids(budget(&ranked, &HashSet::from(["g0", "g1"]))), ["s1", "s2", "s3", "g2", "g3"]);
1383        // The consequence model decides to block; the block then carries the other lessons over LOW.
1384        assert!(widen(&ranked, &[], &none).is_empty(), "the model abstained: no block");
1385        let w = ids(widen(&ranked, &[&gs[4]], &HashSet::from(["g0"])));
1386        assert_eq!(w, ["s1", "s2", "s3", "g4", "g1", "g2"], "the model's pick leads, below the bar or not");
1387    }
1388
1389    #[test]
1390    fn a_pool_that_fits_has_propensity_one() {
1391        let sc = |id: &str| Challenge { scope: vec!["Beacon".into()], belief: (1.0, 40.0), ..ch(id, "") };
1392        let ls: Vec<Challenge> = (0..7).map(|i| sc(&format!("s{i}"))).chain((0..3).map(|i| ch(&format!("g{i}"), ""))).collect();
1393        let pool: Vec<(f64, &Challenge)> = ls.iter().enumerate().map(|(i, c)| (10.0 - i as f64, c)).collect();
1394        let p = propensity(&pool, "s");
1395        assert_eq!(p.len(), CAP);
1396        assert!(p.values().all(|&x| x == 1.0), "{p:?}");
1397    }
1398
1399    #[test]
1400    fn propensities_fill_the_slots() {
1401        let ls: Vec<Challenge> = (0..14).map(|i| Challenge { scope: vec!["Beacon".into()], ..ch(&format!("a{i}"), "") }).collect();
1402        let pool: Vec<(f64, &Challenge)> = ls.iter().map(|c| (5.0, c)).collect();
1403        let p = propensity(&pool, "s");
1404        let sum: f64 = p.values().sum();
1405        assert!((sum - CAP as f64).abs() < 0.05, "{sum}");
1406        assert!(p.values().all(|&x| x > 0.0 && x < 1.0), "{p:?}");
1407        // Unscoped lessons share GENERIC_CAP slots.
1408        let gs: Vec<Challenge> = (0..6).map(|i| ch(&format!("g{i}"), "")).collect();
1409        let pool: Vec<(f64, &Challenge)> = gs.iter().map(|c| (5.0, c)).collect();
1410        assert!((propensity(&pool, "s").values().sum::<f64>() - GENERIC_CAP as f64).abs() < 0.05);
1411    }
1412
1413    #[test]
1414    fn a_constraint_never_reaches_further_than_its_lesson() {
1415        use serde_json::json;
1416        let lessons = [
1417            json!({"id": "Lrepo", "origin_ms": 1, "question": "q", "repo": "app", "reach": "repo", "scope": ["Orion"]}),
1418            json!({"id": "Lgone", "origin_ms": 1, "question": "q", "repo": "app", "reach": "personal"}),
1419            json!({"id": "Lteam", "origin_ms": 1, "question": "q", "repo": "app"}),
1420        ];
1421        let dir = store("constraint-reach", &lessons, &[]);
1422        let line = |id: &str, lesson: &str, extra: serde_json::Value| {
1423            let mut v = json!({"id": id, "text": format!("rule {id}"), "lesson": lesson, "by": "lead@x", "ms": 5});
1424            v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
1425            format!("{v}\n")
1426        };
1427        let text = [
1428            line("c1", "Lrepo", json!({})),
1429            line("c2", "Lgone", json!({"reach": ""})),
1430            line("c3", "Lteam", json!({"reach": "repo", "repo": "app"})),
1431            line("c4", "Lmissing", json!({"repo": "app", "scope": ["Beacon"]})),
1432            line("c5", "Lmissing", json!({})),
1433        ]
1434        .concat();
1435        std::fs::write(crate::veto::constraints_path(&dir), text).unwrap();
1436        let all = load_with(&dir.join("lessons.jsonl"), None, &Aliases::default());
1437        let c = |id: &str| all.iter().find(|c| c.id == id && c.standing());
1438        let of = |id: &str| c(id).map(|c| (c.reach.as_str(), c.repo.as_str(), c.scope.clone()));
1439        assert_eq!(of("c1"), Some(("repo", "app", vec!["Orion".to_string()])), "a repo convention's constraint stays in its repo");
1440        assert_eq!(of("c2").map(|x| x.0), Some("personal"), "a withdrawn lesson takes its constraint along");
1441        assert_eq!(of("c3").map(|x| x.0), Some("repo"), "the line's narrower reach holds over a team lesson");
1442        assert_eq!(of("c4"), Some(("repo", "app", vec!["Beacon".to_string()])), "an unknown lesson: the line's scope, bound to its repo");
1443        assert!(c("c5").is_none(), "an unknown lesson and no repo: never delivered everywhere");
1444        let here = ["other".to_string()];
1445        assert!(["c1", "c2", "c3", "c4"].iter().all(|id| !crate::reach::deliverable(c(id).unwrap(), &here)));
1446        let _ = std::fs::remove_dir_all(dir);
1447    }
1448
1449    #[test]
1450    fn early_propensities_fill_its_slots_and_what_it_shows() {
1451        let topics = vec!["Beacon".to_string()];
1452        let ls: Vec<Challenge> = (0..8).map(|i| Challenge { scope: vec!["Beacon".into()], ..ch(&format!("a{i}"), "Is it short?") }).collect();
1453        let pool: Vec<(f64, &Challenge)> = ls.iter().map(|c| (5.0, c)).collect();
1454        assert!(early_propensity(&pool[..EARLY_CAP], "s", &topics).values().all(|&x| x == 1.0), "the whole pool shows");
1455        let p = early_propensity(&pool, "s", &topics);
1456        let sum: f64 = p.values().sum();
1457        assert!((sum - EARLY_CAP as f64).abs() < 0.05, "{sum}");
1458        assert!(p.values().all(|&x| x > 0.0 && x < 1.0), "{p:?}");
1459        // Lines too long for `EARLY_CHARS` to hold all four: the slots are what it shows, whatever the cap.
1460        let long: Vec<Challenge> =
1461            (0..4).map(|i| Challenge { scope: vec!["Beacon".into()], consequence: "y".repeat(199), ..ch(&format!("l{i}"), &"x".repeat(299)) }).collect();
1462        let pool: Vec<(f64, &Challenge)> = long.iter().map(|c| (5.0, c)).collect();
1463        let shown = render_early(&pool.iter().map(|(_, c)| *c).collect::<Vec<_>>(), &topics).unwrap().1;
1464        let sum: f64 = early_propensity(&pool, "s", &topics).values().sum();
1465        assert!(shown < pool.len() && (sum - shown as f64).abs() < 1e-9, "{shown} {sum}");
1466    }
1467
1468    #[test]
1469    fn a_proven_lesson_outdraws_an_uncertain_one() {
1470        let sc = |id: &str, belief: (f64, f64)| Challenge { scope: vec!["Beacon".into()], belief, ..ch(id, "") };
1471        let mut ls: Vec<Challenge> = (0..10).map(|i| sc(&format!("a{i}"), (1.0, 1.0))).collect();
1472        ls.push(sc("proven", (40.0, 2.0)));
1473        ls.push(sc("harmful", (1.0, 40.0)));
1474        let pool: Vec<(f64, &Challenge)> = ls.iter().map(|c| (5.0, c)).collect();
1475        let p = propensity(&pool, "s");
1476        assert!(p["proven"] > p["harmful"], "{p:?}");
1477    }
1478
1479    #[test]
1480    fn propensity_is_deterministic() {
1481        let ls: Vec<Challenge> =
1482            (0..12).map(|i| Challenge { scope: vec!["Beacon".into()], belief: (1.0 + i as f64, 2.5), ..ch(&format!("a{i}"), "") }).collect();
1483        let pool: Vec<(f64, &Challenge)> = ls.iter().enumerate().map(|(i, c)| (5.0 + i as f64 / 10.0, c)).collect();
1484        assert_eq!(propensity(&pool, "s"), propensity(&pool, "s"));
1485        assert_ne!(propensity(&pool, "s"), propensity(&pool, "t"), "another session draws again");
1486    }
1487
1488    #[test]
1489    fn bm25_ranks_the_matching_question_first() {
1490        let cs = vec![
1491            ch("log", "Am I diagnosing from the full application log rather than a truncated debug trace?"),
1492            ch("toctou", "Is any check-then-act on an AtomicBoolean flag TOCTOU-safe across threads?"),
1493            ch("css", "Does the stylesheet follow the design tokens?"),
1494        ];
1495        let plan = "The relay checks closed.get() on the AtomicBoolean before deliver(); reader and drainer threads race.";
1496        let sel = select(&cs, plan, 2);
1497        assert_eq!(sel[0].id, "toctou");
1498        assert!(select(&cs, "zzz qqq", 3).is_empty());
1499    }
1500
1501    #[test]
1502    fn a_store_without_facets_ranks_exactly_as_bm25_over_the_questions() {
1503        let qs = ["Is the closed flag guarded by the delivery lock?", "Does the plan cite the spec?", "", "Is the flag lock-free?", "Is the flag lock-free?"];
1504        let docs: Vec<Vec<String>> = qs.iter().map(|q| tokens(q)).collect();
1505        let groups: Vec<Vec<Vec<String>>> = docs.iter().map(|d| vec![d.clone()]).collect();
1506        for query in ["the closed flag and its lock", "spec spec plan", "nothing here", ""] {
1507            let (a, b) = (bm25(&docs, query), bm25_groups(&groups, query, 0.5));
1508            assert!(a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-12), "{query}: {a:?} {b:?}");
1509        }
1510        let b = bm25_groups(&groups, "lock-free flag", 0.0);
1511        assert_eq!(b[3].to_bits(), b[4].to_bits(), "equal documents score bit-for-bit equal");
1512    }
1513
1514    #[test]
1515    fn a_facet_finds_its_lesson_from_another_angle_and_counts_once_for_idf() {
1516        let mut fill = ch("fill", "Is P@8 split into fill@8 and relevance among filled slots?");
1517        fill.facets = vec![
1518            "empty result slots counted as irrelevant products make precision look worse".into(),
1519            "Leere Trefferplätze werden als irrelevante Dokumente gezählt".into(),
1520        ];
1521        let other = ch("judge", "Is the replay judge exactly the named model?");
1522        let cs = vec![fill.clone(), other];
1523        // The question shares no word with this context; a facet does.
1524        let ctx = "precision dropped because the search returned fewer products; empty slots look irrelevant";
1525        assert_eq!(select(&cs, ctx, 1)[0].id, "fill");
1526        assert!(select(&cs, "Plätze leer, Dokumente gezählt", 1).iter().any(|c| c.id == "fill"), "German facet");
1527        // Max, not sum: repeating a word across facets does not add up.
1528        let groups: Vec<Vec<Vec<String>>> = cs.iter().map(documents).collect();
1529        let one = bm25_groups(&groups, "irrelevant", 0.0)[0];
1530        let mut twice = fill.clone();
1531        twice.facets.push("irrelevant".into());
1532        let g2: Vec<Vec<Vec<String>>> = [twice, cs[1].clone()].iter().map(documents).collect();
1533        let s = bm25_groups(&g2, "irrelevant", 0.0)[0];
1534        assert!(s > one, "the one-word facet is the better document");
1535        let with_second = bm25_groups(&g2, "irrelevant", 0.5)[0];
1536        assert!(with_second > s && with_second < 2.0 * s, "max + 0.5 x second");
1537        // idf over lessons: a word in every facet of one lesson is still in one lesson of two.
1538        // Documents: "irrelevant" twice (one lesson), "other words entirely": avg length 5/3, idf ln 2.
1539        let x = Challenge { facets: vec!["irrelevant".into()], ..ch("x", "irrelevant") };
1540        let groups = [documents(&x), vec![tokens("other words entirely")]];
1541        let expect = 2f64.ln() * 2.2 / (1.0 + 1.2 * (0.25 + 0.75 * 0.6));
1542        assert!((bm25_groups(&groups, "irrelevant", 0.0)[0] - expect).abs() < 1e-12);
1543    }
1544}