1use 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 pub origin_ms: i64,
21 pub question: String,
22 #[serde(default)]
24 pub situations: Vec<String>,
25 #[serde(default)]
26 pub consequence: String,
27 #[serde(default)]
29 pub area: String,
30 #[serde(default)]
32 pub engineers: Vec<String>,
33 #[serde(default)]
35 pub joined: std::collections::BTreeMap<String, i64>,
36 #[serde(default)]
38 pub supersedes: Vec<String>,
39 #[serde(default)]
41 pub source: String,
42 #[serde(default)]
44 pub scope: Vec<String>,
45 #[serde(default)]
47 pub overrides: String,
48 #[serde(default)]
51 pub facets: Vec<String>,
52 #[serde(default)]
54 pub repo: String,
55 #[serde(default)]
57 pub reach: String,
58 #[serde(skip)]
60 pub off_system: bool,
61 #[serde(skip, default = "one")]
64 pub weight: f64,
65 #[serde(skip)]
67 pub dormant: bool,
68 #[serde(skip)]
70 pub consolidated: bool,
71 #[serde(skip, default = "one")]
75 pub explore: f64,
76 #[serde(skip, default = "uniform")]
79 pub belief: (f64, f64),
80 #[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
126pub fn load(path: &Path, before_ms: Option<i64>) -> Vec<Challenge> {
133 load_with(path, before_ms, collective::aliases())
134}
135
136pub fn load_with(path: &Path, before_ms: Option<i64>, aliases: &Aliases) -> Vec<Challenge> {
138 load_as(path, before_ms, aliases, None, false)
139}
140
141pub fn load_for(path: &Path, before_ms: Option<i64>, session: Option<&str>) -> Vec<Challenge> {
144 load_as(path, before_ms, collective::aliases(), session, false)
145}
146
147pub fn load_store_for(path: &Path, before_ms: Option<i64>, session: Option<&str>) -> Vec<Challenge> {
152 load_as(path, before_ms, collective::aliases(), session, true)
153}
154
155pub fn load_store_with(path: &Path, before_ms: Option<i64>, aliases: &Aliases) -> Vec<Challenge> {
157 load_as(path, before_ms, aliases, None, true)
158}
159
160fn load_as(path: &Path, before_ms: Option<i64>, aliases: &Aliases, session: Option<&str>, personal: bool) -> Vec<Challenge> {
161 let outcomes = crate::outcome::read_team(path);
162 let mut out = load_unweighted_with(path, before_ms, aliases);
163 if personal {
164 let mut mine = load_unweighted_with(&path.with_file_name(crate::reach::PERSONAL_FILE), before_ms, aliases);
165 mine.retain(|c| c.question != crate::reach::MOVED);
167 if !mine.is_empty() {
168 out.retain(|c| !mine.iter().any(|m| m.id == c.id));
169 out.extend(mine.into_iter().map(|c| Challenge { reach: String::new(), ..c }));
170 }
171 }
172 let memory = crate::memory::derive(&outcomes, &out, session);
173 let trust = trust::Trust::compute(&out, &outcomes);
174 for c in &mut out {
175 if let Some(m) = memory.get(&c.id) {
176 c.weight = m.weight(&c.id, None);
180 c.explore = if session.is_some() { m.weight(&c.id, session) / c.weight } else { 1.0 };
181 c.belief = (m.alpha(), m.beta());
182 c.dormant = m.dormant;
183 c.consolidated = m.consolidated;
184 }
185 c.trust = trust.lesson(c);
186 }
187 out.extend(constraints(path, before_ms, aliases, &out));
188 out
189}
190
191pub const CONSTRAINT: &str = "constraint";
193
194impl Challenge {
195 pub fn standing(&self) -> bool {
200 self.source == CONSTRAINT
201 }
202}
203
204fn constraints(path: &Path, before_ms: Option<i64>, aliases: &Aliases, lessons: &[Challenge]) -> Vec<Challenge> {
213 let Some(dir) = path.parent() else { return Vec::new() };
214 let Ok(text) = std::fs::read_to_string(crate::veto::constraints_path(dir)) else { return Vec::new() };
215 let mut by: std::collections::BTreeMap<String, (i64, String, Challenge)> = std::collections::BTreeMap::new();
216 for v in text.lines().filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok()) {
217 let s = |k: &str| v[k].as_str().unwrap_or_default().trim().to_string();
218 let (id, question, ms) = (s("id"), s("text"), v["ms"].as_i64().unwrap_or(0));
219 if id.is_empty() || question.is_empty() || before_ms.is_some_and(|b| ms >= b) {
220 continue;
221 }
222 let author = aliases.canon(&s("by"));
223 if by.get(&id).is_some_and(|(m, a, _)| (*m, a.as_str()) <= (ms, author.as_str())) {
224 continue;
225 }
226 let line_scope: Vec<String> = v["scope"].as_array().into_iter().flatten().filter_map(|x| x.as_str()).map(str::to_string).collect();
227 let (scope, repo, reach, area) = match lessons.iter().find(|l| l.id == s("lesson")) {
228 Some(l) => {
229 let repo = if l.repo.is_empty() { s("repo") } else { l.repo.clone() };
230 (l.scope.clone(), repo, crate::reach::narrower(&s("reach"), &l.reach).to_string(), l.area.clone())
231 }
232 None if s("repo").is_empty() => continue,
233 None => (line_scope, s("repo"), crate::reach::narrower(&s("reach"), crate::reach::REPO).to_string(), trust::OTHER.into()),
234 };
235 let c = Challenge {
236 id: id.clone(),
237 origin_ms: ms,
238 question,
239 source: CONSTRAINT.into(),
240 engineers: Some(author.clone()).filter(|a| !a.is_empty()).into_iter().collect(),
241 scope,
242 repo,
243 reach,
244 area,
245 consolidated: true,
246 ..Challenge::default()
247 };
248 by.insert(id, (ms, author, c));
249 }
250 by.into_values().map(|(_, _, c)| c).collect()
251}
252
253pub fn load_unweighted(path: &Path, before_ms: Option<i64>) -> Vec<Challenge> {
256 load_unweighted_with(path, before_ms, collective::aliases())
257}
258
259pub fn load_unweighted_with(path: &Path, before_ms: Option<i64>, aliases: &Aliases) -> Vec<Challenge> {
261 let Ok(text) = std::fs::read_to_string(path) else { return Vec::new() };
262 let mut out: Vec<Challenge> = Vec::new();
264 let mut at: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
265 for mut c in text.lines().filter_map(|l| serde_json::from_str::<Challenge>(l).ok()) {
266 c.area = trust::area(&c.area).into();
267 canonical(&mut c, aliases);
268 if before_ms.is_some_and(|b| c.origin_ms >= b) {
269 continue;
270 }
271 match at.get(&c.id) {
272 Some(&i) => out[i] = c,
273 None => {
274 at.insert(c.id.clone(), out.len());
275 out.push(c);
276 }
277 }
278 }
279 out
280}
281
282fn canonical(c: &mut Challenge, aliases: &Aliases) {
287 let mut engineers: Vec<String> = Vec::new();
288 for e in c.engineers.iter().map(|e| aliases.canon(e)).filter(|e| !e.is_empty()) {
289 if !engineers.contains(&e) {
290 engineers.push(e);
291 }
292 }
293 let joined = engineers
294 .iter()
295 .filter_map(|who| {
296 let raws = c.engineers.iter().filter(|r| aliases.canon(r) == *who);
297 let at: Option<Vec<i64>> = raws.map(|r| c.joined.get(r).copied()).collect();
298 Some((who.clone(), at?.into_iter().min()?))
299 })
300 .collect();
301 (c.engineers, c.joined) = (engineers, joined);
302}
303
304pub fn tokens(text: &str) -> Vec<String> {
306 let mut out = Vec::new();
307 for raw in text.split(|c: char| !c.is_alphanumeric() && c != '_') {
308 if raw.len() < 3 {
309 continue;
310 }
311 out.push(raw.to_lowercase());
312 let mut word = String::new();
313 for ch in raw.chars() {
314 if ch.is_uppercase() && !word.is_empty() {
315 if word.len() >= 3 && word.len() < raw.len() {
316 out.push(word.to_lowercase());
317 }
318 word.clear();
319 }
320 word.push(ch);
321 }
322 if word.len() >= 3 && word.len() < raw.len() {
323 out.push(word.to_lowercase());
324 }
325 }
326 out
327}
328
329pub fn rank<'a>(challenges: &'a [Challenge], context: &str) -> Vec<(f64, &'a Challenge)> {
348 rank_scoped(challenges, context, context)
349}
350
351pub fn work_text(context: &str) -> std::borrow::Cow<'_, str> {
355 if !context.contains("#borg-") {
356 return std::borrow::Cow::Borrowed(context);
357 }
358 std::borrow::Cow::Owned(context.split_inclusive('\n').filter(|l| !l.starts_with("#borg-")).collect())
359}
360
361pub fn rank_scoped<'a>(challenges: &'a [Challenge], context: &str, scope_text: &str) -> Vec<(f64, &'a Challenge)> {
364 let groups: Vec<Vec<Vec<String>>> = challenges.iter().map(documents).collect();
365 let mut raw = bm25_groups(&groups, context, 0.0);
366 if challenges.iter().any(|c| !c.scope.is_empty()) {
367 let have = Names::of(scope_text);
368 for (r, c) in raw.iter_mut().zip(challenges) {
369 if !in_scope(c, &have) || c.off_system {
370 *r = 0.0;
371 }
372 }
373 }
374 let best = raw.iter().copied().fold(0.0, f64::max);
376 for (r, c) in raw.iter_mut().zip(challenges) {
377 if c.dormant && *r < STRONG * best {
378 *r = 0.0;
379 }
380 }
381 let successors = trust::successors(challenges);
382 let mut relevance = raw.clone();
383 if !successors.is_empty() {
384 let at: std::collections::HashMap<&str, usize> = challenges.iter().enumerate().map(|(i, c)| (c.id.as_str(), i)).collect();
385 for (i, c) in challenges.iter().enumerate() {
386 if let Some(&j) = successors.get(&c.id).and_then(|s| at.get(s.as_str())) {
387 relevance[j] = relevance[j].max(raw[i]);
388 }
389 }
390 }
391 let mut scored: Vec<(f64, &Challenge)> = relevance
392 .into_iter()
393 .zip(challenges)
394 .filter(|(_, c)| !successors.contains_key(&c.id))
395 .map(|(s, c)| (s * c.weight * c.trust / trust::NEUTRAL, c))
396 .filter(|(s, _)| *s > 0.0)
397 .collect();
398 scored.sort_by(|a, b| b.0.total_cmp(&a.0).then(b.1.origin_ms.cmp(&a.1.origin_ms)));
399 scored
400}
401
402pub const STRONG: f64 = 0.8;
406
407pub fn in_scope(c: &Challenge, have: &Names) -> bool {
412 c.scope.is_empty() || c.scope.iter().any(|s| have.contains(s))
413}
414
415pub fn segments(text: &str) -> Vec<String> {
418 let mut out = Vec::new();
419 for raw in text.split(|c: char| !c.is_alphanumeric()).filter(|r| !r.is_empty()) {
420 let cs: Vec<char> = raw.chars().collect();
421 let mut word = String::new();
422 for (i, &ch) in cs.iter().enumerate() {
423 let hump = i > 0
424 && ch.is_uppercase()
425 && (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())));
426 if hump && !word.is_empty() {
427 out.push(std::mem::take(&mut word).to_lowercase());
428 }
429 word.push(ch);
430 }
431 out.push(word.to_lowercase());
432 }
433 out
434}
435
436pub struct Names {
438 seq: Vec<String>,
439 at: std::collections::HashMap<String, Vec<usize>>,
440}
441
442impl Names {
443 pub fn of(text: &str) -> Self {
444 Self::of_all([text])
445 }
446
447 pub fn of_all<'a>(texts: impl IntoIterator<Item = &'a str>) -> Self {
449 let mut seq = Vec::new();
450 for t in texts {
451 seq.extend(segments(t));
452 seq.push(String::new()); }
454 let mut at: std::collections::HashMap<String, Vec<usize>> = std::collections::HashMap::new();
455 for (i, s) in seq.iter().enumerate() {
456 at.entry(s.clone()).or_default().push(i);
457 }
458 Names { seq, at }
459 }
460
461 pub fn contains(&self, name: &str) -> bool {
463 let need = segments(name);
464 let Some(first) = need.first() else { return false };
465 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())))
466 }
467}
468
469pub const BM25_K1: f64 = 1.2;
473pub const BM25_B: f64 = 0.75;
474
475pub fn bm25(docs: &[Vec<String>], query: &str) -> Vec<f64> {
477 let (k1, b) = (BM25_K1, BM25_B);
478 let n = docs.len().max(1) as f64;
479 let avg = docs.iter().map(Vec::len).sum::<usize>() as f64 / n;
480 let mut df: std::collections::HashMap<&str, f64> = std::collections::HashMap::new();
481 for d in docs {
482 for t in d.iter().map(String::as_str).collect::<HashSet<_>>() {
483 *df.entry(t).or_default() += 1.0;
484 }
485 }
486 let query: HashSet<String> = tokens(query).into_iter().collect();
487 docs.iter()
488 .map(|d| {
489 let mut tf: std::collections::HashMap<&str, f64> = std::collections::HashMap::new();
490 for t in d {
491 *tf.entry(t.as_str()).or_default() += 1.0;
492 }
493 query
494 .iter()
495 .filter_map(|t| tf.get(t.as_str()).map(|f| (t, *f)))
496 .map(|(t, f)| {
497 let dft = df[t.as_str()];
498 let idf = (1.0 + (n - dft + 0.5) / (dft + 0.5)).ln();
499 idf * f * (k1 + 1.0) / (f + k1 * (1.0 - b + b * d.len() as f64 / avg))
500 })
501 .sum()
502 })
503 .collect()
504}
505
506pub fn documents(c: &Challenge) -> Vec<Vec<String>> {
508 std::iter::once(tokens(&c.question)).chain(c.facets.iter().map(|f| tokens(f)).filter(|d| !d.is_empty())).collect()
509}
510
511pub fn bm25_groups(groups: &[Vec<Vec<String>>], query: &str, second: f64) -> Vec<f64> {
517 let (k1, b) = (BM25_K1, BM25_B);
518 let n = groups.len().max(1) as f64;
519 let ndocs = groups.iter().map(Vec::len).sum::<usize>().max(1) as f64;
520 let avg = groups.iter().flatten().map(Vec::len).sum::<usize>() as f64 / ndocs;
521 let mut index: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
522 for t in tokens(query) {
523 let next = index.len();
524 index.entry(t).or_insert(next);
525 }
526 let counted: Vec<Vec<Vec<(usize, f64)>>> = groups
528 .iter()
529 .map(|g| {
530 g.iter()
531 .map(|d| {
532 let mut tf: Vec<(usize, f64)> = Vec::new();
533 for q in d.iter().filter_map(|t| index.get(t.as_str())) {
534 match tf.iter_mut().find(|(x, _)| x == q) {
535 Some((_, f)) => *f += 1.0,
536 None => tf.push((*q, 1.0)),
537 }
538 }
539 tf.sort_by_key(|(q, _)| *q);
540 tf
541 })
542 .collect()
543 })
544 .collect();
545 let mut df = vec![0.0f64; index.len()];
546 let mut seen: Vec<usize> = Vec::new();
547 for g in &counted {
548 seen.clear();
549 for &(q, _) in g.iter().flatten() {
550 if !seen.contains(&q) {
551 seen.push(q);
552 df[q] += 1.0;
553 }
554 }
555 }
556 let idf: Vec<f64> = df.iter().map(|&d| (1.0 + (n - d + 0.5) / (d + 0.5)).ln()).collect();
557 counted
558 .iter()
559 .zip(groups)
560 .map(|(g, docs)| {
561 let (mut best, mut next) = (0.0f64, 0.0f64);
562 for (tf, d) in g.iter().zip(docs) {
563 let norm = k1 * (1.0 - b + b * d.len() as f64 / avg);
564 let s: f64 = tf.iter().map(|&(q, f)| idf[q] * f * (k1 + 1.0) / (f + norm)).sum();
565 if s > best {
566 (best, next) = (s, best);
567 } else if s > next {
568 next = s;
569 }
570 }
571 best + second * next
572 })
573 .collect()
574}
575
576pub fn select<'a>(challenges: &'a [Challenge], context: &str, k: usize) -> Vec<&'a Challenge> {
578 select_scoped(challenges, context, context, k)
579}
580
581pub fn select_scoped<'a>(challenges: &'a [Challenge], context: &str, scope_text: &str, k: usize) -> Vec<&'a Challenge> {
583 rank_scoped(challenges, context, scope_text).into_iter().take(k).map(|(_, c)| c).collect()
584}
585
586pub const RELATIVE: f64 = 0.5;
593pub const BLOCK: f64 = 0.8;
597pub const LOW: f64 = 0.3;
600pub const CAP: usize = 10;
604pub const GENERIC_CAP: usize = 3;
607
608pub fn budget<'a>(ranked: &[(f64, &'a Challenge)], done: &HashSet<&str>) -> Vec<&'a Challenge> {
617 in_scope_first(explored(budget_pool(ranked, done)))
618}
619
620pub fn budget_pool<'a>(ranked: &[(f64, &'a Challenge)], done: &HashSet<&str>) -> Vec<(f64, &'a Challenge)> {
623 let Some(&(top, _)) = ranked.first() else { return Vec::new() };
624 if !ranked.iter().any(|(s, c)| *s >= BLOCK * top && !done.contains(c.id.as_str())) {
625 return Vec::new();
626 }
627 ranked.iter().copied().filter(|(s, c)| *s >= LOW * top && !done.contains(c.id.as_str())).collect()
628}
629
630pub fn widen<'a>(ranked: &[(f64, &'a Challenge)], predicted: &[&'a Challenge], done: &HashSet<&str>) -> Vec<&'a Challenge> {
633 in_scope_first(explored(widen_pool(ranked, predicted, done)))
634}
635
636pub fn widen_pool<'a>(ranked: &[(f64, &'a Challenge)], predicted: &[&'a Challenge], done: &HashSet<&str>) -> Vec<(f64, &'a Challenge)> {
639 if predicted.is_empty() {
640 return Vec::new();
641 }
642 let top = ranked.first().map_or(0.0, |r| r.0);
643 let score = |c: &Challenge| ranked.iter().find(|(_, x)| x.id == c.id).map_or(0.0, |r| r.0);
644 let mut pool: Vec<(f64, &Challenge)> = predicted.iter().map(|c| (score(c).max(top), *c)).collect();
646 for &(s, c) in ranked {
647 if s >= LOW * top && !done.contains(c.id.as_str()) && !pool.iter().any(|(_, x)| x.id == c.id) {
648 pool.push((s, c));
649 }
650 }
651 pool
652}
653
654pub fn graded<'a>(applied: &[(&'a Challenge, u8)]) -> (Vec<&'a Challenge>, Vec<&'a Challenge>) {
662 graded_capped(applied, ask_cap())
663}
664
665pub fn ask_cap() -> Option<usize> {
668 std::env::var("BORG_STOP_ASK_CAP").ok().and_then(|v| v.trim().parse().ok()).filter(|n| *n > 0)
669}
670
671pub fn graded_capped<'a>(applied: &[(&'a Challenge, u8)], cap: Option<usize>) -> (Vec<&'a Challenge>, Vec<&'a Challenge>) {
673 graded_without(applied, cap, &[])
674}
675
676pub fn graded_without<'a>(applied: &[(&'a Challenge, u8)], cap: Option<usize>, had: &[String]) -> (Vec<&'a Challenge>, Vec<&'a Challenge>) {
681 let of = |g: u8| applied.iter().filter(move |(_, x)| *x == g).map(|(c, _)| *c);
682 if of(3).next().is_none() {
683 return (Vec::new(), of(2).chain(of(1)).filter(|c| !had.contains(&c.id)).take(CAP).collect());
684 }
685 if let Some(n) = cap {
686 return (of(3).take(n).collect(), Vec::new());
687 }
688 let mut ask: Vec<&Challenge> = of(3).chain(of(2)).collect();
689 let room = CAP.saturating_sub(ask.len());
690 ask.extend(of(1).take(room));
691 (ask, Vec::new())
692}
693
694pub fn explored<'a>(passed: impl IntoIterator<Item = (f64, &'a Challenge)>) -> Vec<&'a Challenge> {
697 let mut v: Vec<(f64, &Challenge)> = passed.into_iter().map(|(s, c)| (s * c.explore, c)).collect();
698 v.sort_by(|a, b| b.0.total_cmp(&a.0));
699 v.into_iter().map(|(_, c)| c).collect()
700}
701
702pub fn in_scope_first<'a>(candidates: impl IntoIterator<Item = &'a Challenge>) -> Vec<&'a Challenge> {
704 let (scoped, generic): (Vec<&Challenge>, Vec<&Challenge>) = candidates.into_iter().partition(|c| !c.scope.is_empty());
705 scoped.into_iter().chain(generic.into_iter().take(GENERIC_CAP)).take(CAP).collect()
706}
707
708pub const P_DRAWS: usize = 512;
711
712pub fn propensity(pool: &[(f64, &Challenge)], session: &str) -> std::collections::HashMap<String, f64> {
718 if pool.iter().filter(|(_, c)| c.scope.is_empty()).count() <= GENERIC_CAP && pool.len() <= CAP {
719 return pool.iter().map(|(_, c)| (c.id.clone(), 1.0)).collect();
720 }
721 kept_share(pool, session, |order| in_scope_first(order).into_iter().map(|c| c.id.clone()).collect())
722}
723
724fn kept_share(pool: &[(f64, &Challenge)], session: &str, keep: impl Fn(Vec<&Challenge>) -> Vec<String>) -> std::collections::HashMap<String, f64> {
727 let draw = |c: &Challenge, i: usize| {
728 let (a, b) = c.belief;
729 let x = crate::memory::draw(a, b, crate::memory::seed(&format!("{session}#p{i}"), &c.id));
730 (0.5 + x) / (0.5 + a / (a + b))
731 };
732 let mut kept: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
733 for i in 0..P_DRAWS {
734 let mut v: Vec<(f64, &Challenge)> = pool.iter().map(|&(s, c)| (s * draw(c, i), c)).collect();
735 v.sort_by(|a, b| b.0.total_cmp(&a.0));
736 for id in keep(v.into_iter().map(|(_, c)| c).collect()) {
737 *kept.entry(id).or_default() += 1;
738 }
739 }
740 pool.iter().map(|(_, c)| (c.id.clone(), kept.get(&c.id).copied().unwrap_or(0) as f64 / P_DRAWS as f64)).collect()
741}
742
743pub fn pool_base(s: f64, c: &Challenge) -> f64 {
748 let (a, b) = c.belief;
749 s / (0.5 + a / (a + b))
750}
751
752pub const EARLY_CAP: usize = 5;
754pub const EARLY_CHARS: usize = 2000;
758pub const EARLY_QUESTION_CHARS: usize = 300;
762pub const EARLY_CONSEQUENCE_CHARS: usize = 200;
765pub const EARLY_OVERRIDES_CHARS: usize = 150;
768
769pub fn named_scopes(challenges: &[Challenge], text: &str) -> Vec<String> {
771 let have = Names::of(text);
772 let mut out: Vec<String> = Vec::new();
773 for s in challenges.iter().flat_map(|c| &c.scope) {
774 if !out.contains(s) && have.contains(s) {
775 out.push(s.clone());
776 }
777 }
778 out
779}
780
781pub fn early<'a>(challenges: &'a [Challenge], context: &str, topics: &[String], done: &HashSet<&str>) -> Vec<&'a Challenge> {
787 let pool: Vec<(f64, &Challenge)> = standing_pool(challenges, topics, done).into_iter().chain(early_pool(challenges, context, topics, done)).collect();
788 explored(pool).into_iter().take(EARLY_CAP).collect()
789}
790
791pub fn early_pool<'a>(challenges: &'a [Challenge], context: &str, topics: &[String], done: &HashSet<&str>) -> Vec<(f64, &'a Challenge)> {
794 let on_topic = Names::of_all(topics.iter().map(String::as_str));
795 let any = topics.iter().any(|t| t == ANY);
796 let ranked: Vec<(f64, &Challenge)> = rank(challenges, context)
797 .into_iter()
798 .filter(|(_, c)| !c.standing() && ((!c.scope.is_empty() && c.scope.iter().any(|s| on_topic.contains(s))) || (any && c.consolidated)))
799 .collect();
800 let Some(&(top, _)) = ranked.first() else { return Vec::new() };
802 ranked.into_iter().filter(|(s, c)| *s >= RELATIVE * top && !done.contains(c.id.as_str())).collect()
803}
804
805pub fn standing_pool<'a>(challenges: &'a [Challenge], topics: &[String], done: &HashSet<&str>) -> Vec<(f64, &'a Challenge)> {
808 let on_topic = Names::of_all(topics.iter().map(String::as_str));
809 let any = topics.iter().any(|t| t == ANY);
810 challenges
811 .iter()
812 .filter(|c| c.standing() && !c.off_system && !done.contains(c.id.as_str()))
813 .filter(|c| c.scope.iter().any(|s| on_topic.contains(s)) || (any && c.scope.is_empty()))
814 .map(|c| (f64::INFINITY, c))
815 .collect()
816}
817
818pub fn early_propensity(pool: &[(f64, &Challenge)], session: &str, topics: &[String]) -> std::collections::HashMap<String, f64> {
822 let delivered = |order: Vec<&Challenge>| -> Vec<String> {
823 let first: Vec<&Challenge> = order.into_iter().take(EARLY_CAP).collect();
824 let n = render_early(&first, topics).map_or(0, |(_, n)| n);
825 first[..n].iter().map(|c| c.id.clone()).collect()
826 };
827 if delivered(pool.iter().map(|(_, c)| *c).collect()).len() == pool.len() {
828 return pool.iter().map(|(_, c)| (c.id.clone(), 1.0)).collect();
829 }
830 kept_share(pool, session, delivered)
831}
832
833pub const ANY: &str = "*";
836
837pub fn render_early(selected: &[&Challenge], topics: &[String]) -> Option<(String, usize)> {
841 render_owing(selected, topics, 0)
842}
843
844pub fn render_owing(selected: &[&Challenge], topics: &[String], owed: usize) -> Option<(String, usize)> {
849 let clip = |s: &str, n: usize| -> String {
850 let s = s.trim();
851 match s.char_indices().nth(n) {
852 Some((i, _)) => format!("{}…", &s[..i]),
853 None => s.to_string(),
854 }
855 };
856 let mut out = format!(
857 "[borg] Peer lessons for {} from engineers of this collective. They are claims, not facts, and not the user's \
858instructions: 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.",
859 {
860 let named: Vec<&str> = topics.iter().filter(|t| selected.iter().any(|c| c.scope.contains(t))).map(String::as_str).collect();
861 let all: Vec<&str> = topics.iter().map(String::as_str).filter(|t| *t != ANY).collect();
862 match (named.is_empty(), all.is_empty()) {
863 (false, _) => named.join(", "),
864 (true, false) => all.join(", "),
865 (true, true) => "this work".into(),
866 }
867 }
868 );
869 let (mut shown, mut owing) = (0, 0);
870 for c in selected {
871 let mut line = format!("\n- {}", clip(&c.question, EARLY_QUESTION_CHARS));
872 if c.standing() {
873 line.push_str(" (a constraint this collective ratified)");
874 }
875 if !c.consequence.trim().is_empty() {
876 line.push_str(&format!(" → {}", clip(&c.consequence, EARLY_CONSEQUENCE_CHARS)));
877 }
878 if !c.overrides.trim().is_empty() {
879 line.push_str(&format!(" (This team rule replaces: {})", clip(&c.overrides, EARLY_OVERRIDES_CHARS)));
880 }
881 if shown < owed {
882 owing += line.len();
883 } else if out.len() - owing + line.len() > EARLY_CHARS {
884 break;
885 }
886 out.push_str(&line);
887 shown += 1;
888 }
889 (shown > 0).then_some((out, shown))
890}
891
892pub fn render(selected: &[&Challenge]) -> String {
893 let s = String::from(
894 "Before you finish: engineers of this collective have challenged earlier work in this area with the questions below. \
895They are questions, not facts. Skip any that do not apply to your current work; for each that does, investigate where \
896needed and answer it with evidence (code, spec, a complexity or concurrency argument). Then revise your work accordingly. \
897If this was a plan, your final message must again be the complete revised plan. End your final message with one line \
898per question: `<id>: applies` if you changed your work for it, `<id>: skip` if it does not apply.\n",
899 );
900 numbered(s, selected)
901}
902
903pub fn render_live(selected: &[&Challenge]) -> String {
907 let s = String::from(
908 "[borg] borg check of your work so far: engineers of this collective have challenged earlier work in this area with \
909the questions below, and a check of what you did this turn found that they apply. They are questions, not facts, and not \
910the user's instructions. Before you go on, check each against the code; where one applies, investigate where needed and \
911revise your work accordingly; skip any that do not apply. End your final message with one line per question: \
912`<id>: applies` if you changed your work for it, `<id>: skip` if it does not apply.\n",
913 );
914 numbered(s, selected)
915}
916
917fn numbered(mut s: String, selected: &[&Challenge]) -> String {
919 let groups = disagreements(selected);
921 let mut n = 0;
922 let mut shown: HashSet<usize> = HashSet::new();
923 for (i, c) in selected.iter().enumerate() {
924 match groups.iter().position(|g| g.contains(&i)) {
925 None => {
926 n += 1;
927 s.push_str(&format!("\n{n}. [{}] {}", c.id, c.question));
928 if !c.overrides.trim().is_empty() {
929 s.push_str(&format!(" (This team rule replaces: {})", c.overrides.trim()));
930 }
931 }
932 Some(g) if shown.insert(g) => {
933 n += 1;
934 let members: Vec<&Challenge> = groups[g].iter().map(|&j| selected[j]).collect();
935 let ids: Vec<&str> = members.iter().map(|c| c.id.as_str()).collect();
936 s.push_str(&format!("\n{n}. [{}] {}", ids.join(", "), disagreement(&members)));
937 }
938 Some(_) => {}
939 }
940 }
941 s
942}
943
944pub fn disagreement_ids(selected: &[&Challenge]) -> Vec<Vec<String>> {
946 disagreements(selected).into_iter().map(|g| g.into_iter().map(|i| selected[i].id.clone()).collect()).collect()
947}
948
949pub fn disagreements(selected: &[&Challenge]) -> Vec<Vec<usize>> {
953 let mut pairs = crate::queen::conflict_pairs(selected);
954 for (i, a) in selected.iter().enumerate() {
955 for (j, b) in selected.iter().enumerate().skip(i + 1) {
956 if a.supersedes.contains(&b.id) || b.supersedes.contains(&a.id) {
957 pairs.push((i, j));
958 }
959 }
960 }
961 fn root(g: &mut [usize], mut i: usize) -> usize {
963 while g[i] != i {
964 g[i] = g[g[i]];
965 i = g[i];
966 }
967 i
968 }
969 let mut parent: Vec<usize> = (0..selected.len()).collect();
970 for (a, b) in pairs {
971 let (ra, rb) = (root(&mut parent, a), root(&mut parent, b));
972 parent[ra.max(rb)] = ra.min(rb);
973 }
974 let mut groups: Vec<(usize, Vec<usize>)> = Vec::new();
975 for i in 0..selected.len() {
976 let r = root(&mut parent, i);
977 match groups.iter_mut().find(|(x, _)| *x == r) {
978 Some((_, g)) => g.push(i),
979 None => groups.push((r, vec![i])),
980 }
981 }
982 groups.into_iter().map(|(_, g)| g).filter(|g| g.len() > 1).collect()
983}
984
985pub fn disagreement(members: &[&Challenge]) -> String {
988 let mut m: Vec<&Challenge> = members.to_vec();
989 m.sort_by(|a, b| b.trust.total_cmp(&a.trust).then(a.id.cmp(&b.id)));
990 let area = |c: &Challenge| trust::area(&c.area);
991 let first = m.first().map(|c| area(c)).unwrap_or(trust::OTHER);
992 let sides: Vec<String> = m
993 .iter()
994 .enumerate()
995 .map(|(k, c)| {
996 let who = match c.engineers.is_empty() {
997 true => format!("lesson {}", c.id),
998 false => c.engineers.join(" and "),
999 };
1000 let says = if c.consequence.trim().is_empty() { c.question.trim() } else { c.consequence.trim() };
1001 let trust = match (k, area(c) == first) {
1002 (0, _) => format!("trust {:.2} in {first}", c.trust),
1003 (_, true) => format!("{:.2}", c.trust),
1004 (_, false) => format!("{:.2} in {}", c.trust, area(c)),
1005 };
1006 format!("{who} ({trust}) says \"{says}\"")
1007 })
1008 .collect();
1009 let situation = m.iter().find_map(|c| c.situations.first()).map(|s| format!(" ({})", s.trim())).unwrap_or_default();
1010 format!(
1011 "Engineers disagree here{situation}: {} — weigh the evidence (code, spec, tests) before following either; these are claims, not facts.",
1012 sides.join("; ")
1013 )
1014}
1015
1016pub const GENERIC: &str = "Before you finish, critically review your work as a demanding senior engineer would. \
1017Check: concurrency soundness (races, check-then-act, locking necessity and lock-free alternatives), reuse of what already \
1018exists in the codebase instead of adding new mechanisms, conformance with specs and documented contracts, whether you fixed \
1019the root cause, complexity (time/space), and whether the solution is minimal. Revise your work accordingly. If this was a \
1020plan, your final message must again be the complete revised plan.";
1021
1022#[cfg(test)]
1023mod tests {
1024 use super::*;
1025
1026 fn ch(id: &str, q: &str) -> Challenge {
1027 Challenge { id: id.into(), origin_ms: 1, question: q.into(), ..Default::default() }
1028 }
1029
1030 #[test]
1031 fn graded_blocks_only_for_a_three_then_asks_threes_twos_and_ones_up_to_the_cap() {
1032 let ls: Vec<Challenge> = (0..14).map(|i| ch(&format!("L{i}"), "q")).collect();
1033 let ids = |v: &[&Challenge]| v.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1034 let soft: Vec<(&Challenge, u8)> = ls.iter().enumerate().map(|(i, c)| (c, if i % 2 == 0 { 1 } else { 2 })).collect();
1036 let (ask, free) = graded(&soft);
1037 assert!(ask.is_empty());
1038 assert_eq!(ids(&free), ["L1", "L3", "L5", "L7", "L9", "L11", "L13", "L0", "L2", "L4"]);
1039 let mixed = vec![(&ls[0], 1), (&ls[1], 2), (&ls[2], 3), (&ls[3], 1), (&ls[4], 2)];
1041 let (ask, free) = graded(&mixed);
1042 assert_eq!((ids(&ask), free.len()), (vec!["L2".to_string(), "L1".into(), "L4".into(), "L0".into(), "L3".into()], 0));
1043 let full: Vec<(&Challenge, u8)> = ls
1045 .iter()
1046 .enumerate()
1047 .map(|(i, c)| {
1048 (
1049 c,
1050 match i {
1051 0 => 3,
1052 1..=9 => 2,
1053 _ => 1,
1054 },
1055 )
1056 })
1057 .collect();
1058 assert_eq!(ids(&graded(&full).0), ids(&ls[..10].iter().collect::<Vec<_>>()));
1059 let two_threes = vec![(&ls[0], 2), (&ls[1], 3), (&ls[2], 1), (&ls[3], 3)];
1061 let (ask, free) = graded_capped(&two_threes, Some(1));
1062 assert_eq!((ids(&ask), free.len()), (vec!["L1".to_string()], 0));
1063 assert_eq!(ids(&graded_capped(&two_threes, Some(5)).0), ["L1", "L3"]);
1064 let (ask, free) = graded_capped(&soft, Some(1));
1065 assert!(ask.is_empty() && free.len() == CAP);
1066 let (ask, free) = graded(&[]);
1067 assert!(ask.is_empty() && free.is_empty());
1068 }
1069
1070 #[test]
1071 fn outcome_weight_reorders_the_shortlist() {
1072 use crate::outcome::{ASKED, CORRECTED, IGNORED, NOT_CORRECTED, Outcome, append, path_beside};
1073 let dir = std::env::temp_dir().join(format!("borg-conscience-{}", std::process::id()));
1074 let _ = std::fs::remove_dir_all(&dir);
1075 let lessons = dir.join("lessons.jsonl");
1076 std::fs::create_dir_all(&dir).unwrap();
1077 let line =
1079 |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?"}));
1080 std::fs::write(&lessons, line("specific", 1) + &line("generic", 2)).unwrap();
1081 let plan = "check-then-act on the shared closed flag";
1082 let ids = |cs: &[Challenge]| select(cs, plan, 2).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1083 assert_eq!(ids(&load(&lessons, None)), ["generic", "specific"]);
1084 let o = |kind: &str, s: &str, ms, l: &str| Outcome {
1088 kind: kind.into(),
1089 session: s.into(),
1090 lessons: vec![l.into()],
1091 ms,
1092 repo: "r".into(),
1093 ..Default::default()
1094 };
1095 for x in [
1096 o(ASKED, "s1", 1, "generic"),
1097 o(CORRECTED, "s1", 2, "generic"),
1098 o(ASKED, "s2", 3, "generic"),
1099 o(IGNORED, "s2", 4, "generic"),
1100 o(NOT_CORRECTED, "s2", 4, "generic"),
1101 ] {
1102 append(&path_beside(&lessons), &x).unwrap();
1103 }
1104 let cs = load(&lessons, None);
1105 let w = |cs: &[Challenge], id: &str| cs.iter().find(|c| c.id == id).unwrap().weight;
1106 let sq = |age: f64| crate::memory::squash(age.powf(-0.5).ln());
1107 assert!((w(&cs, "generic") - sq(2.0) * 0.7).abs() < 1e-12 && (w(&cs, "specific") - sq(3.0)).abs() < 1e-12);
1108 assert_eq!(ids(&cs), ["specific", "generic"]);
1109 for x in [
1111 o(ASKED, "s3", 5, "generic"),
1112 o(crate::outcome::CHANGED, "s3", 6, "generic"),
1113 o(ASKED, "s4", 7, "generic"),
1114 o(crate::outcome::CHANGED, "s4", 8, "generic"),
1115 ] {
1116 append(&path_beside(&lessons), &x).unwrap();
1117 }
1118 let cs = load(&lessons, None);
1119 assert!(w(&cs, "generic") > w(&cs, "specific"), "{} {}", w(&cs, "generic"), w(&cs, "specific"));
1120 assert_eq!(ids(&cs), ["generic", "specific"]);
1121 let _ = std::fs::remove_dir_all(dir);
1122 }
1123
1124 fn store(name: &str, lines: &[serde_json::Value], outcomes: &[(&str, &str, &str)]) -> std::path::PathBuf {
1125 let dir = std::env::temp_dir().join(format!("borg-conscience-{name}-{}", std::process::id()));
1126 let _ = std::fs::remove_dir_all(&dir);
1127 std::fs::create_dir_all(&dir).unwrap();
1128 let text: String = lines.iter().map(|l| format!("{l}\n")).collect();
1129 std::fs::write(dir.join("lessons.jsonl"), text).unwrap();
1130 for (kind, session, id) in outcomes {
1131 let o = crate::outcome::Outcome {
1132 kind: kind.to_string(),
1133 session: session.to_string(),
1134 lessons: vec![id.to_string()],
1135 ms: 1,
1136 repo: "r".into(),
1137 ..Default::default()
1138 };
1139 crate::outcome::append(&dir.join("outcomes.jsonl"), &o).unwrap();
1140 }
1141 dir
1142 }
1143
1144 #[test]
1145 fn author_trust_in_the_area_reorders_the_shortlist() {
1146 use crate::outcome::{CORRECTED, NOT_CORRECTED};
1147 use serde_json::json;
1148 let q = "Is the check-then-act on the shared flag atomic?";
1149 let lines = [
1153 json!({"id": "strong", "origin_ms": 1, "question": q, "area": "concurrency", "engineers": ["ann@x"]}),
1154 json!({"id": "weak", "origin_ms": 2, "question": q, "area": "concurrency", "engineers": ["bob@x"]}),
1155 json!({"id": "ann-old", "origin_ms": 0, "question": "unrelated", "area": "concurrency", "engineers": ["ann@x"]}),
1156 json!({"id": "bob-old", "origin_ms": 0, "question": "unrelated", "area": "concurrency", "engineers": ["bob@x"]}),
1157 json!({"id": "bob-sec", "origin_ms": 0, "question": "unrelated", "area": "security", "engineers": ["bob@x"]}),
1158 ];
1159 let plan = "check-then-act on the shared closed flag";
1160 let ids = |cs: &[Challenge]| select(cs, plan, 2).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1161 let neutral = store("trust-neutral", &lines, &[]);
1162 let cs = load(&neutral.join("lessons.jsonl"), None);
1163 assert_eq!(ids(&cs), ["weak", "strong"]);
1164 assert!(cs.iter().all(|c| c.trust == trust::NEUTRAL && c.weight == 1.0));
1165 let raw = bm25(&cs.iter().map(|c| tokens(&c.question)).collect::<Vec<_>>(), plan)[0];
1167 assert!((rank(&cs, plan)[1].0 - raw).abs() < 1e-12);
1168 let outs = [(CORRECTED, "s1", "bob-old"), (CORRECTED, "s2", "bob-old"), (NOT_CORRECTED, "s1", "ann-old"), (NOT_CORRECTED, "s3", "bob-sec")];
1170 let earned = store("trust-earned", &lines, &outs);
1171 let cs = load(&earned.join("lessons.jsonl"), None);
1172 let t = |id: &str| cs.iter().find(|c| c.id == id).unwrap().trust;
1173 assert_eq!((t("strong"), t("weak")), (2.0 / 3.0, 0.25));
1174 assert_eq!(ids(&cs), ["strong", "weak"]);
1175 for d in [neutral, earned] {
1176 let _ = std::fs::remove_dir_all(d);
1177 }
1178 }
1179
1180 #[test]
1181 fn a_superseded_lesson_is_not_asked_its_successor_is() {
1182 use serde_json::json;
1183 let lines = [
1184 json!({"id": "lock", "origin_ms": 1, "question": "Is the closed flag guarded by the delivery ReentrantLock?", "engineers": ["ann@x"]}),
1185 json!({"id": "atomic", "origin_ms": 2, "question": "Would a CAS suffice?", "engineers": ["ann@x"], "supersedes": ["lock"]}),
1187 ];
1188 let dir = store("superseded", &lines, &[]);
1189 let cs = load(&dir.join("lessons.jsonl"), None);
1190 let plan = "guard the closed flag with the delivery ReentrantLock";
1191 let sel = select(&cs, plan, 5);
1192 assert_eq!(sel.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), ["atomic"], "the successor inherits the relevance");
1193 assert!(!render(&sel).contains("ReentrantLock"));
1194 assert_eq!(cs.iter().find(|c| c.id == "lock").unwrap().trust, NEUTRAL_REVERSED);
1195 let _ = std::fs::remove_dir_all(dir);
1196 }
1197
1198 const NEUTRAL_REVERSED: f64 = 0.25;
1201
1202 #[test]
1203 fn disagreeing_lessons_render_as_one_conflict_with_trust() {
1204 let mk = |id: &str, eng: &str, area: &str, consequence: &str, t: f64| Challenge {
1205 id: id.into(),
1206 origin_ms: 1,
1207 question: format!("question of {id}"),
1208 situations: vec!["check-then-act on a shared mutable flag across threads".into()],
1209 consequence: consequence.into(),
1210 area: area.into(),
1211 engineers: vec![eng.into()],
1212 trust: t,
1213 ..Default::default()
1214 };
1215 let a = mk("A", "bob@x", "concurrency", "guard it with the existing ReentrantLock", 0.4);
1216 let b = mk("B", "ann@x", "concurrency", "use a lock-free compareAndSet instead", 0.8);
1217 let other = Challenge { id: "C".into(), question: "Is the spec cited?".into(), ..Default::default() };
1218 let text = render(&[&a, &other, &b]);
1219 assert!(
1220 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"),
1221 "{text}"
1222 );
1223 assert!(text.contains("\n2. [C] Is the spec cited?") && !text.contains("question of"), "{text}");
1224 let x = Challenge { id: "X".into(), question: "Lock?".into(), supersedes: vec!["Y".into()], engineers: vec!["ann@x".into()], ..Default::default() };
1226 let y = Challenge { id: "Y".into(), question: "Atomic?".into(), supersedes: vec!["X".into()], area: "scope".into(), ..Default::default() };
1227 let text = render(&[&x, &y]);
1228 assert!(
1229 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?\""),
1230 "{text}"
1231 );
1232 assert!(!text.contains("\n2."));
1233 let c = mk("C2", "cy@x", "concurrency", "guard it with the existing ReentrantLock", 0.5);
1235 assert!(render(&[&a, &c]).contains("\n2. [C2] question of C2"));
1236 let live = render_live(&[&a, &c]);
1238 assert!(live.starts_with("[borg] borg check of your work so far:") && live.contains("`<id>: applies`"), "{live}");
1239 assert!(live.contains("\n2. [C2] question of C2") && !live.contains("Before you finish"), "{live}");
1240 }
1241
1242 #[test]
1243 fn a_less_trusted_contradiction_is_shown_as_a_disagreement_not_hidden() {
1244 use crate::outcome::{CORRECTED, NOT_CORRECTED};
1245 use serde_json::json;
1246 let q = "Is the closed flag guarded by the delivery ReentrantLock?";
1247 let lines = [
1248 json!({"id": "lock", "origin_ms": 1, "question": q, "consequence": "guard it with the existing ReentrantLock",
1249 "situations": ["check-then-act on the closed flag"], "area": "concurrency", "engineers": ["ann@x"]}),
1250 json!({"id": "cas", "origin_ms": 2, "question": "Would a CAS on the closed flag ReentrantLock path suffice?", "consequence": "use compareAndSet",
1251 "situations": ["check-then-act on the closed flag"], "area": "concurrency", "engineers": ["bob@x"], "supersedes": ["lock"]}),
1252 json!({"id": "ann-old", "origin_ms": 0, "question": "unrelated", "area": "concurrency", "engineers": ["ann@x"]}),
1253 json!({"id": "bob-old", "origin_ms": 0, "question": "unrelated", "area": "concurrency", "engineers": ["bob@x"]}),
1254 ];
1255 let dir = store("weak-supersedes", &lines, &[(NOT_CORRECTED, "s1", "ann-old"), (CORRECTED, "s2", "bob-old")]);
1256 let cs = load(&dir.join("lessons.jsonl"), None);
1257 let plan = "guard the closed flag with the delivery ReentrantLock";
1258 let sel = select(&cs, plan, 5);
1259 let ids: Vec<&str> = sel.iter().map(|c| c.id.as_str()).collect();
1260 assert!(ids.contains(&"lock") && ids.contains(&"cas"), "{ids:?}");
1261 let text = render(&sel);
1262 assert!(text.contains("Engineers disagree here") && text.contains("ann@x (trust 0.67 in concurrency)"), "{text}");
1263 assert_eq!(disagreement_ids(&sel), [vec!["lock".to_string(), "cas".to_string()]]);
1264 let _ = std::fs::remove_dir_all(dir);
1265 }
1266
1267 #[test]
1268 fn a_scoped_lesson_is_asked_only_where_its_scope_is_named() {
1269 let drain = Challenge {
1270 id: "drain".into(),
1271 question: "Is each per-turn place drained by an explicit consumer instead of a new reset arc?".into(),
1272 scope: vec!["Orion".into()],
1273 overrides: "upstream petri-net-design seeds a budget with a reset arc on the starting transition".into(),
1274 ..ch("drain", "")
1275 };
1276 let other = Challenge { scope: vec!["search lab".into()], ..ch("lab", "Is the reset arc per-turn place budget pinned?") };
1277 let open = ch("open", "Does every per-turn token have a consumer?");
1278 let cs = vec![drain, other, open];
1279 let ids = |ctx: &str| select(&cs, ctx, 5).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1280 assert_eq!(ids("PressNet: reset arc on the per-turn reprint budget place"), ["open"]);
1282 let k1 = ids("Read /w/orion-text/src/FlowConfig.java; add a per-turn hint place with a reset arc");
1284 assert!(k1.contains(&"drain".to_string()) && !k1.contains(&"lab".to_string()), "{k1:?}");
1285 assert!(ids("the search-lab reset arc per-turn budget").contains(&"lab".to_string()));
1287 assert!(ids("SearchLab: reset arc per-turn budget").contains(&"lab".to_string()));
1288 assert!(!ids("search the lab: reset arc per-turn budget").contains(&"lab".to_string()));
1289 let text = render(&[&cs[0]]);
1290 assert!(text.contains("instead of a new reset arc? (This team rule replaces: upstream petri-net-design seeds"), "{text}");
1291 let succ = Challenge { supersedes: vec!["drain".into()], ..ch("succ", "Unrelated wording") };
1293 let cs2 = vec![cs[0].clone(), succ];
1294 assert!(select(&cs2, "per-turn place reset arc consumer", 5).is_empty());
1295 }
1296
1297 #[test]
1298 fn scope_names_match_as_phrases_or_identifiers_never_as_scattered_words() {
1299 assert_eq!(
1300 segments("HTTPClientFactory cart-link-v2 harbor_orion SR3Review"),
1301 ["http", "client", "factory", "cart", "link", "v2", "harbor", "orion", "sr3", "review"]
1302 );
1303 let k2 = Names::of(
1305 "Read /w/press/src/PressNet.java. The jam transition's guard now checks the counter; \
1306 the reprint transition's output arc goes to Ready; reset arc removed. A button links here.",
1307 );
1308 for name in ["Answer Guard", "pay-button", "cart-link-v2", "Orion", "harbor_orion", "ticket-triage-agent"] {
1309 assert!(!k2.contains(name), "{name} must not match k2");
1310 }
1311 assert!(Names::of("wire the AnswerGuard bean").contains("Answer Guard"));
1312 assert!(Names::of("src/quality-acceptance-test/java").contains("quality-acceptance-test"));
1313 assert!(Names::of("the pay-button component").contains("pay-button"));
1314 assert!(!Names::of("the button").contains("pay-button"), "a short part is never dropped");
1315 assert!(Names::of("/w/orion-text/src/OrionConfig.java").contains("Orion"));
1316 assert!(!Names::of_all(["answer", "guard"]).contains("Answer Guard"), "never across two texts");
1317 assert!(!Names::of("").contains("Orion") && !Names::of("x").contains("--"));
1318 }
1319
1320 #[test]
1324 fn k2_stop_context_asks_no_orion_lesson() {
1325 let guard = Challenge {
1326 scope: vec!["Orion".into(), "harbor_orion".into(), "LiveCheckService".into(), "QuickReplySubnet".into(), "Answer Guard".into()],
1327 ..ch(
1328 "I0a1b2c3d4e5f",
1329 "Have you listed every LLM call whose output reaches the customer, traced through the Petri net from the \
1330guard's output place to each send action, and stated per surface whether the Answer Guard sees it?",
1331 )
1332 };
1333 let reset = Challenge {
1334 scope: vec!["Orion".into(), "pay-button".into(), "cart-link-v2".into()],
1335 ..ch("reset", "Is per-turn state drained instead of cleared by a reset arc on the transition?")
1336 };
1337 let generic = ch("generic", "Does the demo show the changed behaviour for every job, not only the first?");
1338 let cs = vec![guard, reset, generic];
1339 let w = "/tmp/e3live/0a1b2c3d/work/press-queue";
1340 let k2 = format!(
1341 "Operators say only the first jammed job of a shift gets reprinted; every jam after that goes straight to failed. \
1342Every 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\
1343The reprint budget was one shift-wide token. Now the jam transition's guard checks the job's reprint count, the reprint transition's \
1344output arc puts the job back into Queued, and the shift-start reset arc is removed. A button in the link view shows it."
1345 );
1346 let ids: Vec<String> = select(&cs, &k2, 5).iter().map(|c| c.id.clone()).collect();
1347 assert_eq!(ids, ["generic"]);
1348 assert!(select(&cs, &format!("{k2}\n/w/harbor_orion/src/AnswerGuard.java"), 5).iter().any(|c| c.id == "I0a1b2c3d4e5f"));
1350 }
1351
1352 #[test]
1353 fn early_delivers_only_scoped_lessons_on_a_named_topic_that_score_near_the_best() {
1354 let sc = |id: &str, scope: &[&str], q: &str| Challenge { scope: scope.iter().map(|s| s.to_string()).collect(), ..ch(id, q) };
1355 let cs = vec![
1356 sc("live", &["Beacon"], "Does the Beacon replay run its services on live hosts?"),
1357 sc("judge", &["Beacon", "search-lab"], "Is the replay judge exactly the named model?"),
1358 sc("weak", &["Beacon"], "Is the facet mapping evaluated at the relaxed tier?"),
1359 sc("drain", &["Orion"], "Is the replay place drained instead of reset?"),
1360 ch("generic", "Does the replay plan name a control arm and a live judge?"),
1361 ];
1362 let ctx = "Set up the Beacon replay on live hosts with the named judge model";
1363 assert_eq!(named_scopes(&cs, ctx), ["Beacon"]);
1364 assert_eq!(named_scopes(&cs, "/w/search-lab/x and /w/orion-text/y"), ["search-lab", "Orion"]);
1365 let topics = vec!["Beacon".to_string()];
1366 let ids = |done: &HashSet<&str>| early(&cs, ctx, &topics, done).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1367 assert_eq!(ids(&HashSet::new()), ["judge", "live"]);
1369 assert_eq!(ids(&HashSet::from(["live"])), ["judge"]);
1370 assert_eq!(ids(&HashSet::from(["judge"])), ["live"]);
1371 assert!(early(&cs, ctx, &[], &HashSet::new()).is_empty());
1372 let (text, shown) = render_early(&early(&cs, ctx, &topics, &HashSet::new()), &topics).unwrap();
1373 assert_eq!(shown, 2);
1374 assert!(text.starts_with("[borg] Peer lessons for Beacon") && text.ends_with("\n- Does the Beacon replay run its services on live hosts?"), "{text}");
1375 assert!(render_early(&[], &topics).is_none());
1376 let long: Vec<Challenge> = (0..9).map(|i| Challenge { consequence: "c".repeat(900), ..sc(&format!("l{i}"), &["Beacon"], &"q ".repeat(400)) }).collect();
1378 let (text, shown) = render_early(&long.iter().collect::<Vec<_>>(), &topics).unwrap();
1379 assert!(text.chars().count() <= EARLY_CHARS && (1..9).contains(&shown), "{shown} {}", text.len());
1380 }
1381
1382 #[test]
1383 fn the_stop_blocks_only_for_a_strong_lesson_not_done_and_then_asks_generously() {
1384 let sc = |id: &str| Challenge { scope: vec!["Beacon".into()], ..ch(id, "") };
1385 let (s1, s2, s3, s4) = (sc("s1"), sc("s2"), sc("s3"), sc("s4"));
1386 let gs: Vec<Challenge> = (0..6).map(|i| ch(&format!("g{i}"), "")).collect();
1387 let ids = |v: Vec<&Challenge>| v.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1388 let none = HashSet::new();
1389 let ranked: Vec<(f64, &Challenge)> =
1391 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])];
1392 assert_eq!(ids(budget(&ranked, &none)), ["s1", "s2", "s3", "g0", "g1", "g2"]);
1393 let generic: Vec<(f64, &Challenge)> = gs.iter().map(|g| (5.0, g)).collect();
1395 assert_eq!(budget(&generic, &none).len(), GENERIC_CAP);
1396 let many: Vec<Challenge> = (0..14).map(|i| sc(&format!("a{i}"))).collect();
1398 let ranked_many: Vec<(f64, &Challenge)> = many.iter().map(|c| (5.0, c)).collect();
1399 assert_eq!(budget(&ranked_many, &none).len(), CAP);
1400 assert!(budget(&[], &none).is_empty(), "nothing scores, nothing is asked");
1401 assert!(budget(&ranked, &HashSet::from(["g0", "s1", "g1"])).is_empty());
1404 assert_eq!(ids(budget(&ranked, &HashSet::from(["g0", "g1"]))), ["s1", "s2", "s3", "g2", "g3"]);
1405 assert!(widen(&ranked, &[], &none).is_empty(), "the model abstained: no block");
1407 let w = ids(widen(&ranked, &[&gs[4]], &HashSet::from(["g0"])));
1408 assert_eq!(w, ["s1", "s2", "s3", "g4", "g1", "g2"], "the model's pick leads, below the bar or not");
1409 }
1410
1411 #[test]
1412 fn a_pool_that_fits_has_propensity_one() {
1413 let sc = |id: &str| Challenge { scope: vec!["Beacon".into()], belief: (1.0, 40.0), ..ch(id, "") };
1414 let ls: Vec<Challenge> = (0..7).map(|i| sc(&format!("s{i}"))).chain((0..3).map(|i| ch(&format!("g{i}"), ""))).collect();
1415 let pool: Vec<(f64, &Challenge)> = ls.iter().enumerate().map(|(i, c)| (10.0 - i as f64, c)).collect();
1416 let p = propensity(&pool, "s");
1417 assert_eq!(p.len(), CAP);
1418 assert!(p.values().all(|&x| x == 1.0), "{p:?}");
1419 }
1420
1421 #[test]
1422 fn propensities_fill_the_slots() {
1423 let ls: Vec<Challenge> = (0..14).map(|i| Challenge { scope: vec!["Beacon".into()], ..ch(&format!("a{i}"), "") }).collect();
1424 let pool: Vec<(f64, &Challenge)> = ls.iter().map(|c| (5.0, c)).collect();
1425 let p = propensity(&pool, "s");
1426 let sum: f64 = p.values().sum();
1427 assert!((sum - CAP as f64).abs() < 0.05, "{sum}");
1428 assert!(p.values().all(|&x| x > 0.0 && x < 1.0), "{p:?}");
1429 let gs: Vec<Challenge> = (0..6).map(|i| ch(&format!("g{i}"), "")).collect();
1431 let pool: Vec<(f64, &Challenge)> = gs.iter().map(|c| (5.0, c)).collect();
1432 assert!((propensity(&pool, "s").values().sum::<f64>() - GENERIC_CAP as f64).abs() < 0.05);
1433 }
1434
1435 #[test]
1436 fn a_constraint_never_reaches_further_than_its_lesson() {
1437 use serde_json::json;
1438 let lessons = [
1439 json!({"id": "Lrepo", "origin_ms": 1, "question": "q", "repo": "app", "reach": "repo", "scope": ["Orion"]}),
1440 json!({"id": "Lgone", "origin_ms": 1, "question": "q", "repo": "app", "reach": "personal"}),
1441 json!({"id": "Lteam", "origin_ms": 1, "question": "q", "repo": "app"}),
1442 ];
1443 let dir = store("constraint-reach", &lessons, &[]);
1444 let line = |id: &str, lesson: &str, extra: serde_json::Value| {
1445 let mut v = json!({"id": id, "text": format!("rule {id}"), "lesson": lesson, "by": "lead@x", "ms": 5});
1446 v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
1447 format!("{v}\n")
1448 };
1449 let text = [
1450 line("c1", "Lrepo", json!({})),
1451 line("c2", "Lgone", json!({"reach": ""})),
1452 line("c3", "Lteam", json!({"reach": "repo", "repo": "app"})),
1453 line("c4", "Lmissing", json!({"repo": "app", "scope": ["Beacon"]})),
1454 line("c5", "Lmissing", json!({})),
1455 ]
1456 .concat();
1457 std::fs::write(crate::veto::constraints_path(&dir), text).unwrap();
1458 let all = load_with(&dir.join("lessons.jsonl"), None, &Aliases::default());
1459 let c = |id: &str| all.iter().find(|c| c.id == id && c.standing());
1460 let of = |id: &str| c(id).map(|c| (c.reach.as_str(), c.repo.as_str(), c.scope.clone()));
1461 assert_eq!(of("c1"), Some(("repo", "app", vec!["Orion".to_string()])), "a repo convention's constraint stays in its repo");
1462 assert_eq!(of("c2").map(|x| x.0), Some("personal"), "a withdrawn lesson takes its constraint along");
1463 assert_eq!(of("c3").map(|x| x.0), Some("repo"), "the line's narrower reach holds over a team lesson");
1464 assert_eq!(of("c4"), Some(("repo", "app", vec!["Beacon".to_string()])), "an unknown lesson: the line's scope, bound to its repo");
1465 assert!(c("c5").is_none(), "an unknown lesson and no repo: never delivered everywhere");
1466 let here = ["other".to_string()];
1467 assert!(["c1", "c2", "c3", "c4"].iter().all(|id| !crate::reach::deliverable(c(id).unwrap(), &here)));
1468 let _ = std::fs::remove_dir_all(dir);
1469 }
1470
1471 #[test]
1472 fn early_propensities_fill_its_slots_and_what_it_shows() {
1473 let topics = vec!["Beacon".to_string()];
1474 let ls: Vec<Challenge> = (0..8).map(|i| Challenge { scope: vec!["Beacon".into()], ..ch(&format!("a{i}"), "Is it short?") }).collect();
1475 let pool: Vec<(f64, &Challenge)> = ls.iter().map(|c| (5.0, c)).collect();
1476 assert!(early_propensity(&pool[..EARLY_CAP], "s", &topics).values().all(|&x| x == 1.0), "the whole pool shows");
1477 let p = early_propensity(&pool, "s", &topics);
1478 let sum: f64 = p.values().sum();
1479 assert!((sum - EARLY_CAP as f64).abs() < 0.05, "{sum}");
1480 assert!(p.values().all(|&x| x > 0.0 && x < 1.0), "{p:?}");
1481 let long: Vec<Challenge> =
1483 (0..4).map(|i| Challenge { scope: vec!["Beacon".into()], consequence: "y".repeat(199), ..ch(&format!("l{i}"), &"x".repeat(299)) }).collect();
1484 let pool: Vec<(f64, &Challenge)> = long.iter().map(|c| (5.0, c)).collect();
1485 let shown = render_early(&pool.iter().map(|(_, c)| *c).collect::<Vec<_>>(), &topics).unwrap().1;
1486 let sum: f64 = early_propensity(&pool, "s", &topics).values().sum();
1487 assert!(shown < pool.len() && (sum - shown as f64).abs() < 1e-9, "{shown} {sum}");
1488 }
1489
1490 #[test]
1491 fn a_proven_lesson_outdraws_an_uncertain_one() {
1492 let sc = |id: &str, belief: (f64, f64)| Challenge { scope: vec!["Beacon".into()], belief, ..ch(id, "") };
1493 let mut ls: Vec<Challenge> = (0..10).map(|i| sc(&format!("a{i}"), (1.0, 1.0))).collect();
1494 ls.push(sc("proven", (40.0, 2.0)));
1495 ls.push(sc("harmful", (1.0, 40.0)));
1496 let pool: Vec<(f64, &Challenge)> = ls.iter().map(|c| (5.0, c)).collect();
1497 let p = propensity(&pool, "s");
1498 assert!(p["proven"] > p["harmful"], "{p:?}");
1499 }
1500
1501 #[test]
1502 fn propensity_is_deterministic() {
1503 let ls: Vec<Challenge> =
1504 (0..12).map(|i| Challenge { scope: vec!["Beacon".into()], belief: (1.0 + i as f64, 2.5), ..ch(&format!("a{i}"), "") }).collect();
1505 let pool: Vec<(f64, &Challenge)> = ls.iter().enumerate().map(|(i, c)| (5.0 + i as f64 / 10.0, c)).collect();
1506 assert_eq!(propensity(&pool, "s"), propensity(&pool, "s"));
1507 assert_ne!(propensity(&pool, "s"), propensity(&pool, "t"), "another session draws again");
1508 }
1509
1510 #[test]
1511 fn bm25_ranks_the_matching_question_first() {
1512 let cs = vec![
1513 ch("log", "Am I diagnosing from the full application log rather than a truncated debug trace?"),
1514 ch("toctou", "Is any check-then-act on an AtomicBoolean flag TOCTOU-safe across threads?"),
1515 ch("css", "Does the stylesheet follow the design tokens?"),
1516 ];
1517 let plan = "The relay checks closed.get() on the AtomicBoolean before deliver(); reader and drainer threads race.";
1518 let sel = select(&cs, plan, 2);
1519 assert_eq!(sel[0].id, "toctou");
1520 assert!(select(&cs, "zzz qqq", 3).is_empty());
1521 }
1522
1523 #[test]
1524 fn a_store_without_facets_ranks_exactly_as_bm25_over_the_questions() {
1525 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?"];
1526 let docs: Vec<Vec<String>> = qs.iter().map(|q| tokens(q)).collect();
1527 let groups: Vec<Vec<Vec<String>>> = docs.iter().map(|d| vec![d.clone()]).collect();
1528 for query in ["the closed flag and its lock", "spec spec plan", "nothing here", ""] {
1529 let (a, b) = (bm25(&docs, query), bm25_groups(&groups, query, 0.5));
1530 assert!(a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-12), "{query}: {a:?} {b:?}");
1531 }
1532 let b = bm25_groups(&groups, "lock-free flag", 0.0);
1533 assert_eq!(b[3].to_bits(), b[4].to_bits(), "equal documents score bit-for-bit equal");
1534 }
1535
1536 #[test]
1537 fn a_facet_finds_its_lesson_from_another_angle_and_counts_once_for_idf() {
1538 let mut fill = ch("fill", "Is P@8 split into fill@8 and relevance among filled slots?");
1539 fill.facets = vec![
1540 "empty result slots counted as irrelevant products make precision look worse".into(),
1541 "Leere Trefferplätze werden als irrelevante Dokumente gezählt".into(),
1542 ];
1543 let other = ch("judge", "Is the replay judge exactly the named model?");
1544 let cs = vec![fill.clone(), other];
1545 let ctx = "precision dropped because the search returned fewer products; empty slots look irrelevant";
1547 assert_eq!(select(&cs, ctx, 1)[0].id, "fill");
1548 assert!(select(&cs, "Plätze leer, Dokumente gezählt", 1).iter().any(|c| c.id == "fill"), "German facet");
1549 let groups: Vec<Vec<Vec<String>>> = cs.iter().map(documents).collect();
1551 let one = bm25_groups(&groups, "irrelevant", 0.0)[0];
1552 let mut twice = fill.clone();
1553 twice.facets.push("irrelevant".into());
1554 let g2: Vec<Vec<Vec<String>>> = [twice, cs[1].clone()].iter().map(documents).collect();
1555 let s = bm25_groups(&g2, "irrelevant", 0.0)[0];
1556 assert!(s > one, "the one-word facet is the better document");
1557 let with_second = bm25_groups(&g2, "irrelevant", 0.5)[0];
1558 assert!(with_second > s && with_second < 2.0 * s, "max + 0.5 x second");
1559 let x = Challenge { facets: vec!["irrelevant".into()], ..ch("x", "irrelevant") };
1562 let groups = [documents(&x), vec![tokens("other words entirely")]];
1563 let expect = 2f64.ln() * 2.2 / (1.0 + 1.2 * (0.25 + 0.75 * 0.6));
1564 assert!((bm25_groups(&groups, "irrelevant", 0.0)[0] - expect).abs() < 1e-12);
1565 }
1566}