Skip to main content

mj_transcript/
github_history.rs

1//! Byte-exact aliases600 retrieval and evidence envelope from the frozen Python format.
2use anyhow::Result;
3use mj_core::github_item::history_unicode as u;
4use regex::Regex;
5use serde::{Deserialize, Serialize};
6use serde_json::json;
7/// Local ordered JSON, so the Python format never changes global serde_json features.
8#[derive(Clone, Debug, Serialize, Deserialize)]
9#[serde(untagged)]
10pub enum OrderedValue {
11    Null,
12    Bool(bool),
13    Number(serde_json::Number),
14    String(String),
15    Array(Vec<OrderedValue>),
16    Object(indexmap::IndexMap<String, OrderedValue>),
17}
18use OrderedValue as Value;
19impl Value {
20    pub fn as_str(&self) -> Option<&str> {
21        if let Self::String(s) = self {
22            Some(s)
23        } else {
24            None
25        }
26    }
27    pub fn as_u64(&self) -> Option<u64> {
28        if let Self::Number(n) = self {
29            n.as_u64()
30        } else {
31            None
32        }
33    }
34    pub fn as_object(&self) -> Option<&indexmap::IndexMap<String, Value>> {
35        if let Self::Object(o) = self {
36            Some(o)
37        } else {
38            None
39        }
40    }
41    pub fn as_array(&self) -> Option<&Vec<Value>> {
42        if let Self::Array(a) = self {
43            Some(a)
44        } else {
45            None
46        }
47    }
48}
49impl std::ops::Index<&str> for Value {
50    type Output = Self;
51    fn index(&self, k: &str) -> &Self {
52        self.as_object()
53            .and_then(|o| o.get(k))
54            .unwrap_or(&Self::Null)
55    }
56}
57impl std::fmt::Display for Value {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        match self {
60            Self::Object(o) => {
61                f.write_str("{")?;
62                for (i, (key, value)) in o.iter().enumerate() {
63                    if i > 0 {
64                        f.write_str(",")?;
65                    }
66                    write!(f, "{}:{value}", json!(key))?;
67                }
68                f.write_str("}")
69            }
70            Self::Array(a) => {
71                f.write_str("[")?;
72                for (i, value) in a.iter().enumerate() {
73                    if i > 0 {
74                        f.write_str(",")?;
75                    }
76                    write!(f, "{value}")?;
77                }
78                f.write_str("]")
79            }
80            Self::Number(n) => f.write_str(&python_number(n)),
81            _ => f.write_str(&serde_json::to_string(self).map_err(|_| std::fmt::Error)?),
82        }
83    }
84}
85// Python repr uses the same shortest round-trip digits, but a different
86// scientific-notation threshold, explicit exponent signs and two-digit exponents.
87fn python_number(number: &serde_json::Number) -> String {
88    let raw = number.to_string();
89    if !number.is_f64() {
90        return raw;
91    }
92    let (sign, unsigned) = raw
93        .strip_prefix('-')
94        .map_or(("", raw.as_str()), |s| ("-", s));
95    let (mantissa, exponent) = unsigned.split_once('e').map_or((unsigned, 0), |(m, e)| {
96        (m, e.parse::<i32>().expect("JSON exponent"))
97    });
98    let decimal = mantissa.find('.').unwrap_or(mantissa.len()) as i32;
99    let digits = mantissa.replace('.', "");
100    let leading = digits.bytes().take_while(|&c| c == b'0').count();
101    if leading == digits.len() {
102        return format!("{sign}0.0");
103    }
104    let exponent = exponent + decimal - leading as i32 - 1;
105    let digits = digits[leading..].trim_end_matches('0');
106    if !(-4..16).contains(&exponent) {
107        let mantissa = if digits.len() == 1 {
108            digits.to_string()
109        } else {
110            format!("{}.{}", &digits[..1], &digits[1..])
111        };
112        format!(
113            "{sign}{mantissa}e{}{:02}",
114            if exponent < 0 { "-" } else { "+" },
115            exponent.abs()
116        )
117    } else {
118        let position = exponent + 1;
119        if position <= 0 {
120            format!("{sign}0.{}{digits}", "0".repeat((-position) as usize))
121        } else if position as usize >= digits.len() {
122            format!(
123                "{sign}{digits}{}.0",
124                "0".repeat(position as usize - digits.len())
125            )
126        } else {
127            format!(
128                "{sign}{}.{}",
129                &digits[..position as usize],
130                &digits[position as usize..]
131            )
132        }
133    }
134}
135
136impl PartialEq<&str> for Value {
137    fn eq(&self, s: &&str) -> bool {
138        self.as_str() == Some(*s)
139    }
140}
141
142fn re(s: &str) -> Regex {
143    Regex::new(s).expect("frozen expression")
144}
145fn chars(s: &str) -> Vec<char> {
146    s.chars().collect()
147}
148pub fn redact(s: &str) -> String {
149    static LONG_TOKEN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
150    LONG_TOKEN
151        .get_or_init(|| re(r"[A-Za-z0-9_.+\-]{24,}"))
152        .replace_all(s, "[redacted]")
153        .into_owned()
154}
155/// Python json.dumps with its default separators, retaining source object order.
156fn spaced(v: &Value) -> String {
157    match v {
158        Value::Object(o) => format!(
159            "{{{}}}",
160            o.iter()
161                .map(|(k, v)| format!("{}: {}", json!(k), spaced(v)))
162                .collect::<Vec<_>>()
163                .join(", ")
164        ),
165        Value::Array(a) => format!("[{}]", a.iter().map(spaced).collect::<Vec<_>>().join(", ")),
166        _ => v.to_string(),
167    }
168}
169pub use mj_core::github_item::HistorySnippet as Snippet;
170#[derive(Clone, Debug)]
171pub struct Span {
172    pub start: usize,
173    pub end: usize,
174    pub score: f64,
175    pub snippet: Snippet,
176}
177fn identifiers(item: &Value) -> Vec<(String, f64)> {
178    let title = item["title"].as_str().unwrap_or("");
179    let text = format!("{}\n{}", title, item["body"].as_str().unwrap_or(""));
180    let word = u::class(u::WORD);
181    let decimal = u::class(u::DECIMAL);
182    let boundary = format!("(?:$|[^{w}])", w = &word[1..word.len() - 1]);
183    let mut ids = Vec::<(String, f64)>::new();
184    let mut put = |s: &str, w| {
185        if let Some(x) = ids.iter_mut().find(|x| x.0 == s) {
186            x.1 = w;
187        } else if !s.is_empty() {
188            ids.push((s.into(), w));
189        }
190    };
191    // Boundaries are checked separately so a rejected match still advances as Python does.
192    for m in re(&format!("#({decimal}+)")).captures_iter(&text) {
193        let end = m.get(0).unwrap().end();
194        if text[end..]
195            .chars()
196            .next()
197            .is_none_or(|c| !u::contains(u::WORD, c))
198        {
199            put(&m[1], 1.3);
200        }
201    }
202    for m in re(&format!(
203        r"[{w}.-]+(?:/[{w}.:-]+)+",
204        w = &word[1..word.len() - 1]
205    ))
206    .find_iter(&text)
207    {
208        let before = text[..m.start()].chars().rev().take(8).collect::<Vec<_>>();
209        let nearby = before
210            .iter()
211            .rev()
212            .copied()
213            .chain(text[m.start()..].chars().take(3))
214            .collect::<String>();
215        if nearby.contains("://") || re("[a-f0-9]{16,}").is_match(m.as_str()) {
216            continue;
217        }
218        put(m.as_str(), 1.2);
219        put(m.as_str().rsplit('/').next().unwrap(), 1.0);
220    }
221    for m in re(r"[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*").find_iter(&text) {
222        let a = m.as_str();
223        if re("^[a-fA-F0-9]{7,}$").is_match(a) {
224            continue;
225        }
226        for s in std::iter::once(a).chain(a.split('.')) {
227            if s.len() >= 6 && (s.contains('_') || re("[a-z][A-Z]").is_match(s)) {
228                put(s, 1.0);
229            }
230            let bits = s.split('_').collect::<Vec<_>>();
231            if bits.len() > 2 {
232                let p = bits[..2].join("_");
233                if p.len() >= 6 {
234                    put(&p, 0.7);
235                }
236            }
237        }
238    }
239    for (source, pattern, weight) in [
240        (
241            &text,
242            format!(
243                r"[A-Za-z_][{w}-]*\.(?:rs|py|sql|json|tsv)",
244                w = &word[1..word.len() - 1]
245            ),
246            1.0,
247        ),
248        (&title.to_string(), "[A-Z]{3,}".into(), 0.5),
249    ] {
250        let pattern = re(&pattern);
251        let right = re(&format!("^{boundary}"));
252        let mut offset = 0;
253        while let Some(m) = pattern.find_at(source, offset) {
254            if source[..m.start()]
255                .chars()
256                .next_back()
257                .is_none_or(|c| !u::contains(u::WORD, c))
258                && right.is_match(&source[m.end()..])
259            {
260                put(m.as_str(), weight);
261                offset = m.end();
262            } else {
263                // Python's boundary is inside the regex: a rejected start must
264                // not consume a later valid filename within this candidate.
265                offset = m.start() + source[m.start()..].chars().next().unwrap().len_utf8();
266            }
267        }
268    }
269    ids
270}
271/// Receives rendered transcript text piece by piece.
272pub trait TextSink {
273    fn push_str(&mut self, text: &str);
274    /// The text that follows belongs to a new part of the transcript: the
275    /// header (`None`) or the row with this ordinal. A sink that keeps
276    /// positions uses it to say where in the stored rows a position lies.
277    fn mark(&mut self, _ordinal: Option<usize>) {}
278    /// The sink takes no more text; the rest may be skipped.
279    fn is_full(&self) -> bool {
280        false
281    }
282}
283impl TextSink for String {
284    fn push_str(&mut self, text: &str) {
285        String::push_str(self, text);
286    }
287}
288
289/// A sink that ends in a selection of windows once the whole transcript has
290/// been pushed.
291pub trait HistorySink: TextSink {
292    /// What the sink returns besides the selection.
293    type Done;
294    /// `check` is called often; an error from it ends the selection.
295    fn select(self, check: &dyn Fn() -> Result<()>) -> Result<(Self::Done, Vec<Selected>)>;
296}
297impl HistorySink for String {
298    type Done = String;
299    fn select(self, _: &dyn Fn() -> Result<()>) -> Result<(String, Vec<Selected>)> {
300        Ok((self, Vec::new()))
301    }
302}
303
304impl TextSink for HistoryScanner {
305    fn push_str(&mut self, text: &str) {
306        HistoryScanner::push_str(self, text);
307    }
308    fn mark(&mut self, ordinal: Option<usize>) {
309        HistoryScanner::mark(self, ordinal);
310    }
311}
312impl HistorySink for HistoryScanner {
313    type Done = ();
314    fn select(self, check: &dyn Fn() -> Result<()>) -> Result<((), Vec<Selected>)> {
315        Ok(((), self.finish(check)?))
316    }
317}
318
319/// One identifier's streaming match state.
320struct IdState {
321    /// Length in code points.
322    cps: usize,
323    numeric: bool,
324    /// End (code point index) of the last raw occurrence: later occurrences must start at or after it.
325    last_end: usize,
326    /// Occurrences that passed the boundary checks.
327    hits: usize,
328}
329
330const NO_STAMP: u32 = u32::MAX;
331const OPEN: u16 = u16::MAX;
332/// `Candidate::ids` while the window can still receive hits.
333const BUILDING: u32 = u32::MAX;
334/// The ordinal of the header, which is not a row.
335const HEADER: u32 = u32::MAX;
336
337/// A window of up to 500 code points around at least one hit that is not a
338/// duplicate of the session digest, in 24 bytes. Its text is held only while
339/// it is open; the text of the selected ones is recovered from the stored
340/// rows. Windows judged duplicates are not kept at all.
341#[derive(Clone, Copy)]
342struct Candidate {
343    start: u32,
344    /// Position of the last stamp at or before the start.
345    stamp: u32,
346    /// The part of the transcript the start lies in, and its offset in that part.
347    ordinal: u32,
348    offset: u32,
349    /// Index in the interned identifier sets, once the window takes no more hits.
350    ids: u32,
351    /// Length of the trimmed text in code points, or `OPEN`.
352    len: u16,
353}
354
355/// Identifier sets, interned when a window stops receiving hits: a window
356/// holds the index of its set.
357#[derive(Default)]
358struct IdSets {
359    sets: Vec<Vec<u32>>,
360    index: std::collections::HashMap<Vec<u32>, u32>,
361}
362impl IdSets {
363    fn intern(&mut self, set: Vec<u32>) -> u32 {
364        if let Some(&i) = self.index.get(&set) {
365            return i;
366        }
367        let i = self.sets.len() as u32;
368        self.index.insert(set.clone(), i);
369        self.sets.push(set);
370        i
371    }
372}
373
374/// The 100-code-point windows of the session digest, found by hash and compared exactly.
375struct Known {
376    digest: Vec<char>,
377    windows: Vec<(u64, usize)>,
378}
379fn window_hash(window: &[char]) -> u64 {
380    use std::hash::{Hash, Hasher};
381    let mut hasher = std::collections::hash_map::DefaultHasher::new();
382    window.hash(&mut hasher);
383    hasher.finish()
384}
385impl Known {
386    fn new(digest: Vec<char>) -> Self {
387        let mut windows = (0..digest.len().saturating_sub(99))
388            .map(|i| (window_hash(&digest[i..i + 100]), i))
389            .collect::<Vec<_>>();
390        windows.sort_unstable();
391        Self { digest, windows }
392    }
393    fn contains(&self, window: &[char]) -> bool {
394        let hash = window_hash(window);
395        let from = self.windows.partition_point(|&(h, _)| h < hash);
396        self.windows[from..]
397            .iter()
398            .take_while(|&&(h, _)| h == hash)
399            .any(|&(_, i)| self.digest[i..i + 100] == *window)
400    }
401}
402
403/// The trimmed length of a finished window, or None when it duplicates the session digest.
404fn judge(existing: &str, known: &Known, text: &str) -> Option<u16> {
405    let raw = text.trim_matches(|c| u::contains(u::SPACE, c));
406    let rt = redact(raw);
407    let r = chars(&rt);
408    if existing.contains(&rt)
409        || (0..r.len().saturating_sub(99))
410            .step_by(50)
411            .any(|i| known.contains(&r[i..i + 100]))
412    {
413        None
414    } else {
415        Some(raw.chars().count() as u16)
416    }
417}
418
419/// A window chosen for the evidence, before its text is recovered.
420#[derive(Clone, Debug)]
421pub struct Selected {
422    pub start: usize,
423    pub end: usize,
424    pub score: f64,
425    /// Position of the governing stamp.
426    pub stamp: Option<usize>,
427    /// Where the start lies: the row ordinal, or `u32::MAX` for the header
428    /// (or when the sink was never marked), and the offset in that part.
429    pub ordinal: u32,
430    pub offset: u32,
431}
432
433/// Single-pass form of the frozen retrieval: the transcript is pushed in pieces
434/// and only the last few hundred code points and a small record per window
435/// that has a hit are kept. Positions are code point indexes, as in the
436/// Python original.
437pub struct HistoryScanner {
438    existing: String,
439    known: Known,
440    ids: Vec<(String, f64)>,
441    info: Vec<IdState>,
442    automaton: Option<aho_corasick::nfa::contiguous::NFA>,
443    state: aho_corasick::automaton::StateID,
444    seen: usize,
445    /// Holds the code points `[seen - ring.len(), seen)`. Large enough for a
446    /// window that starts 374 code points before a hit that ends one
447    /// identifier length later, plus the boundary character before the hit.
448    ring: std::collections::VecDeque<char>,
449    ring_cap: usize,
450    /// Raw occurrences ending at `seen`; the next code point decides their boundary.
451    pending: Vec<(usize, usize)>,
452    /// Windows kept, ordered by start.
453    live: Vec<Candidate>,
454    sets: IdSets,
455    /// Identifiers of windows that can still receive hits.
456    /// Windows still taking hits, sorted by start. Every window closes at its
457    /// start plus the same reach, so the oldest always closes first.
458    building: std::collections::VecDeque<(u32, Vec<u32>)>,
459    /// Windows still collecting text: start and text.
460    open: Vec<(u32, String)>,
461    /// Positions of the stamps seen, pruned to those a future window can still need.
462    stamps: std::collections::VecDeque<usize>,
463    /// A stamp in progress: its position and whether it has content yet.
464    stamp_open: Option<(usize, bool)>,
465    /// Windows that began inside a stamp that was still open.
466    awaiting_stamp: Vec<u32>,
467    /// Where each part of the transcript starts, pruned like the stamps.
468    segments: std::collections::VecDeque<(usize, u32)>,
469    line_start: bool,
470    /// Set when the transcript outgrew the 32-bit positions of the records.
471    too_long: bool,
472    #[cfg(test)]
473    peak_texts: usize,
474}
475
476impl HistoryScanner {
477    /// `item` is the original title/body; `session` the bounded session digest.
478    pub fn new(item: &Value, session: &Value) -> Self {
479        Self::with_identifiers(identifiers(item), session)
480    }
481
482    /// Like [`Self::new`] with the item's identifiers already extracted.
483    fn with_identifiers(ids: Vec<(String, f64)>, session: &Value) -> Self {
484        use aho_corasick::automaton::Automaton;
485        use aho_corasick::nfa::contiguous::NFA;
486        let info = ids
487            .iter()
488            .map(|(id, _)| IdState {
489                cps: id.chars().count(),
490                numeric: id.chars().all(|c| u::contains(u::ISDIGIT, c)),
491                last_end: 0,
492                hits: 0,
493            })
494            .collect::<Vec<_>>();
495        let ring_cap = info.iter().map(|i| i.cps).max().unwrap_or(0) + 400;
496        let automaton = (!ids.is_empty()).then(|| {
497            NFA::new(ids.iter().map(|(id, _)| id.as_bytes())).expect("identifier automaton")
498        });
499        let state = automaton
500            .as_ref()
501            .map_or(aho_corasick::automaton::StateID::ZERO, |a| {
502                a.start_state(aho_corasick::Anchored::No)
503                    .expect("start state")
504            });
505        Self {
506            existing: session["conversation"].as_str().unwrap_or("").to_string(),
507            known: Known::new(chars(&spaced(session))),
508            ids,
509            info,
510            automaton,
511            state,
512            seen: 0,
513            ring: Default::default(),
514            ring_cap,
515            pending: Vec::new(),
516            live: Vec::new(),
517            sets: IdSets::default(),
518            building: std::collections::VecDeque::new(),
519            open: Vec::new(),
520            stamps: Default::default(),
521            stamp_open: None,
522            awaiting_stamp: Vec::new(),
523            segments: Default::default(),
524            line_start: true,
525            too_long: false,
526            #[cfg(test)]
527            peak_texts: 0,
528        }
529    }
530
531    /// See `TextSink::mark`.
532    pub fn mark(&mut self, ordinal: Option<usize>) {
533        if self.automaton.is_none() {
534            return;
535        }
536        self.segments
537            .push_back((self.seen, ordinal.map_or(HEADER, |o| o as u32)));
538        while self.segments.len() >= 2 && self.segments[1].0 + self.ring_cap <= self.seen {
539            self.segments.pop_front();
540        }
541    }
542
543    fn ring_at(&self, index: usize) -> char {
544        self.ring[index - (self.seen - self.ring.len())]
545    }
546
547    fn find(&self, start: u32) -> std::result::Result<usize, usize> {
548        self.live.binary_search_by_key(&start, |c| c.start)
549    }
550
551    fn resolve(&mut self, id: usize, pos: usize, next: Option<char>) {
552        let prev = (pos > 0).then(|| self.ring_at(pos - 1));
553        let ok = if self.info[id].numeric {
554            prev.is_none_or(|c| !u::contains(u::ISDIGIT, c))
555                && next.is_none_or(|c| !u::contains(u::ISDIGIT, c))
556        } else {
557            prev.is_none_or(|c| !(u::contains(u::ISALNUM, c) || c == '_'))
558                && next.is_none_or(|c| !u::contains(u::ISALNUM, c))
559        };
560        if !ok {
561            return;
562        }
563        self.info[id].hits += 1;
564        let start = (pos / 250 * 250).saturating_sub(125);
565        let key = start as u32;
566        match self.find(key) {
567            Ok(at) => {
568                let at_building = match self.building.binary_search_by_key(&key, |b| b.0) {
569                    Ok(n) => n,
570                    Err(n) => {
571                        // Cannot happen before a window closes; keep it correct anyway.
572                        let set = self.sets.sets[self.live[at].ids as usize].clone();
573                        self.live[at].ids = BUILDING;
574                        self.building.insert(n, (key, set));
575                        n
576                    }
577                };
578                let set = &mut self.building[at_building].1;
579                if let Err(pos) = set.binary_search(&(id as u32)) {
580                    set.insert(pos, id as u32);
581                }
582            }
583            Err(at) => {
584                let stop = self.seen.min(start + 500);
585                let base = self.seen - self.ring.len();
586                let text: String = self
587                    .ring
588                    .range(start - base..stop - base)
589                    .copied()
590                    .collect();
591                let len = if stop - start < 500 {
592                    OPEN
593                } else {
594                    match judge(&self.existing, &self.known, &text) {
595                        Some(len) => len,
596                        None => return,
597                    }
598                };
599                let (ordinal, offset) = self
600                    .segments
601                    .iter()
602                    .rev()
603                    .find(|(s, _)| *s <= start)
604                    .map_or((HEADER, start as u32), |&(s, o)| (o, (start - s) as u32));
605                let stamp = self
606                    .stamps
607                    .iter()
608                    .rev()
609                    .find(|p| **p <= start)
610                    .map_or(NO_STAMP, |&p| p as u32);
611                if self.stamp_open.is_some_and(|(p, _)| p <= start) {
612                    self.awaiting_stamp.push(key);
613                }
614                // A longer identifier's hit can start before a shorter one's.
615                let n = self.building.partition_point(|b| b.0 < key);
616                self.building.insert(n, (key, vec![id as u32]));
617                self.live.insert(
618                    at,
619                    Candidate {
620                        start: key,
621                        stamp,
622                        ordinal,
623                        offset,
624                        ids: BUILDING,
625                        len,
626                    },
627                );
628                if len == OPEN {
629                    self.open.push((key, text));
630                    #[cfg(test)]
631                    {
632                        self.peak_texts = self.peak_texts.max(self.open.len());
633                    }
634                }
635            }
636        }
637    }
638
639    /// Interns the identifiers of windows no later hit can reach: a hit
640    /// ends at most `ring_cap - 400` code points (the longest identifier)
641    /// past a start it can reach by 374.
642    fn close_windows(&mut self, all: bool) {
643        let reach = self.ring_cap - 400 + 376;
644        let seen = self.seen;
645        while let Some(&(start, _)) = self.building.front() {
646            if !all && start as usize + reach > seen {
647                break;
648            }
649            let (start, set) = self.building.pop_front().expect("front exists");
650            if let Ok(at) = self.find(start) {
651                self.live[at].ids = self.sets.intern(set);
652            }
653        }
654    }
655
656    /// Records the verdict on a window whose text is complete.
657    fn settle(&mut self, start: u32, text: &str) {
658        let verdict = judge(&self.existing, &self.known, text);
659        let at = self.find(start).expect("an open window is live");
660        match verdict {
661            Some(len) => self.live[at].len = len,
662            None => {
663                self.live.remove(at);
664            }
665        }
666    }
667
668    fn step(&mut self, c: char) {
669        use aho_corasick::automaton::Automaton;
670        if self.seen >= u32::MAX as usize - 1 {
671            self.too_long = true;
672            return;
673        }
674        // `resolve` never touches `pending`; hand the buffer back so it keeps
675        // its allocation across code points.
676        let mut pending = std::mem::take(&mut self.pending);
677        for (id, pos) in pending.drain(..) {
678            self.resolve(id, pos, Some(c));
679        }
680        self.pending = pending;
681        // Stamps: `(?m)^\[([^\]\n]+)\]`.
682        if let Some((pos, content)) = &mut self.stamp_open {
683            if c == ']' || c == '\n' {
684                let (pos, content) = (*pos, *content);
685                self.stamp_open = None;
686                let awaiting = std::mem::take(&mut self.awaiting_stamp);
687                if c == ']' && content {
688                    for start in awaiting {
689                        if let Ok(at) = self.find(start) {
690                            self.live[at].stamp = pos as u32;
691                        }
692                    }
693                    self.stamps.push_back(pos);
694                    while self.stamps.len() >= 2 && self.stamps[1] + self.ring_cap <= self.seen {
695                        self.stamps.pop_front();
696                    }
697                }
698            } else {
699                *content = true;
700            }
701        } else if self.line_start && c == '[' {
702            self.stamp_open = Some((self.seen, false));
703        }
704        self.line_start = c == '\n';
705        if self.ring.len() == self.ring_cap {
706            self.ring.pop_front();
707        }
708        self.ring.push_back(c);
709        let mut i = 0;
710        while i < self.open.len() {
711            let (start, text) = &mut self.open[i];
712            text.push(c);
713            if self.seen + 1 - *start as usize >= 500 {
714                let (start, text) = self.open.remove(i);
715                self.settle(start, &text);
716            } else {
717                i += 1;
718            }
719        }
720        self.seen += 1;
721        self.close_windows(false);
722        if let Some(automaton) = &self.automaton {
723            let mut buffer = [0; 4];
724            for &byte in c.encode_utf8(&mut buffer).as_bytes() {
725                self.state = automaton.next_state(aho_corasick::Anchored::No, self.state, byte);
726                if automaton.is_match(self.state) {
727                    for k in 0..automaton.match_len(self.state) {
728                        let id = automaton.match_pattern(self.state, k).as_usize();
729                        let info = &mut self.info[id];
730                        let pos = self.seen - info.cps;
731                        // Per identifier, matches are leftmost and do not overlap,
732                        // whether or not the boundary checks accept them.
733                        if pos >= info.last_end {
734                            info.last_end = self.seen;
735                            self.pending.push((id, pos));
736                        }
737                    }
738                }
739            }
740        }
741    }
742
743    pub fn push_str(&mut self, text: &str) {
744        if self.automaton.is_none() {
745            return;
746        }
747        for c in text.chars() {
748            self.step(c);
749        }
750    }
751
752    /// Scores and selects the windows once the whole transcript was pushed.
753    pub fn finish(mut self, check: &dyn Fn() -> Result<()>) -> Result<Vec<Selected>> {
754        anyhow::ensure!(
755            !self.too_long,
756            "the transcript is longer than 4 billion code points"
757        );
758        for (id, pos) in std::mem::take(&mut self.pending) {
759            self.resolve(id, pos, None);
760        }
761        for (start, text) in std::mem::take(&mut self.open) {
762            self.settle(start, &text);
763        }
764        self.close_windows(true);
765        let total = self.seen;
766        // `f64::ln_1p` calls the platform's C library, whose log1p is not
767        // correctly rounded: glibc, Apple's libm and MSVC each differ by an
768        // ulp on some inputs, which broke byte parity on Windows. The pure
769        // Rust fdlibm port gives the same bits on every platform and
770        // reproduces every reference fixture.
771        let weights = self
772            .ids
773            .iter()
774            .zip(&self.info)
775            .map(|((_, base), info)| {
776                base * (1.0 + libm::log1p((total as f64 / 500.0).max(1.0) / (1 + info.hits) as f64))
777            })
778            .collect::<Vec<_>>();
779        // Weights are summed in identifier order, once per distinct set.
780        let set_weights = self
781            .sets
782            .sets
783            .iter()
784            .map(|set| set.iter().fold(0.0, |sum, &id| sum + weights[id as usize]))
785            .collect::<Vec<_>>();
786        let mut ranked = Vec::with_capacity(self.live.len());
787        for (n, candidate) in self.live.iter().enumerate() {
788            if n % 1024 == 0 {
789                check()?;
790            }
791            let start = candidate.start as usize;
792            let score = set_weights[candidate.ids as usize]
793                * (1.0 + 0.1 * start as f64 / total.max(1) as f64);
794            ranked.push((n, score));
795        }
796        check()?;
797        ranked.sort_by(|a, b| {
798            b.1.total_cmp(&a.1)
799                .then(self.live[b.0].start.cmp(&self.live[a.0].start))
800        });
801        let mut selected: Vec<Selected> = Vec::new();
802        let mut used = 0;
803        for (n, (index, score)) in ranked.into_iter().enumerate() {
804            if n % 1024 == 0 {
805                check()?;
806            }
807            let candidate = self.live[index];
808            let start = candidate.start as usize;
809            let end = start + 500.min(total - start);
810            if used + candidate.len as usize > 2100
811                || selected.iter().any(|s| start < s.end && end > s.start)
812            {
813                continue;
814            }
815            used += candidate.len as usize;
816            selected.push(Selected {
817                start,
818                end,
819                score,
820                stamp: (candidate.stamp != NO_STAMP).then_some(candidate.stamp as usize),
821                ordinal: candidate.ordinal,
822                offset: candidate.offset,
823            });
824        }
825        selected.sort_by_key(|s| s.start);
826        Ok(selected)
827    }
828}
829
830/// The spans of selected windows whose text is cut out of a whole transcript.
831fn spans_from_whole_text(selected: Vec<Selected>, text: &str) -> Vec<Span> {
832    selected
833        .into_iter()
834        .map(|s| {
835            let window: String = text.chars().skip(s.start).take(s.end - s.start).collect();
836            let time = s.stamp.map(|at| {
837                text.chars()
838                    .skip(at + 1)
839                    .take_while(|&c| c != ']')
840                    .collect()
841            });
842            Span {
843                start: s.start,
844                end: s.end,
845                score: s.score,
846                snippet: Snippet {
847                    time,
848                    text: redact(window.trim_matches(|c| u::contains(u::SPACE, c))),
849                },
850            }
851        })
852        .collect()
853}
854
855/// Retrieves from a complete transcript text. Original title/body must be
856/// supplied, independently of the bounded classifier item.
857pub fn retrieve(item: &Value, text: &str, session: &Value) -> Vec<Span> {
858    let mut scanner = HistoryScanner::new(item, session);
859    scanner.push_str(text);
860    let selected = scanner
861        .finish(&|| Ok(()))
862        .expect("retrieval from a whole text cannot fail");
863    spans_from_whole_text(selected, text)
864}
865/// Counts that the transcript header reports; they fix the header's length and
866/// so every code point position after it.
867#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
868pub struct HistoryCounts {
869    pub included: usize,
870    pub changed: usize,
871    pub later: usize,
872    pub notices: usize,
873}
874
875/// What the first pass needs from each row. SQLite's `json_extract` yields
876/// these cheaply, without decoding the whole body.
877pub struct RowMeta<'a> {
878    pub created_at_ms: i64,
879    pub last_changed_at_ms: i64,
880    /// `body.kind`, empty unless a string.
881    pub kind: &'a str,
882    /// `body.event.body.type`, empty unless a string.
883    pub event_type: &'a str,
884    /// `body.event.body.number` when an unsigned integer.
885    pub event_number: Option<u64>,
886    /// `body.event.body.repo` when a string.
887    pub event_repo: Option<&'a str>,
888}
889
890fn kind_renders(kind: &str) -> bool {
891    matches!(kind, "user" | "agent" | "tool" | "message")
892}
893
894fn is_notice_type(event_type: &str) -> bool {
895    event_type == "new_github_item" || event_type.starts_with("github_")
896}
897
898/// Whether a notice of a notice type names this pair's item.
899fn notice_names_item(
900    number: Option<u64>,
901    repo: Option<&str>,
902    item_number: u64,
903    item_repo_lower: &str,
904) -> bool {
905    number == Some(item_number) && repo.is_none_or(|r| r.to_lowercase() == item_repo_lower)
906}
907
908fn timestamp(ms: i64) -> Result<String> {
909    Ok(chrono::DateTime::from_timestamp_millis(ms)
910        .ok_or_else(|| anyhow::anyhow!("timestamp out of range"))?
911        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
912}
913
914/// One decoded row, rendered once for every pair that includes it.
915struct RowRender {
916    /// None for kinds the transcript never shows.
917    text: Option<String>,
918    /// Set for message rows of a notice type: (number, repo) decide per pair.
919    notice: Option<(Option<u64>, Option<String>)>,
920    created: Result<String, ()>,
921}
922
923fn render_row(created_at_ms: i64, b: &Value) -> RowRender {
924    let s = |v: &Value| v.as_str().unwrap_or("").to_string();
925    let mut notice = None;
926    let text = match b["kind"].as_str().unwrap_or("") {
927        "user" => Some(format!(
928            "USER\n{}",
929            b["content"]
930                .as_array()
931                .into_iter()
932                .flatten()
933                .filter(|x| x["type"] == "text")
934                .map(|x| s(&x["text"]))
935                .collect::<Vec<_>>()
936                .join("\n")
937        )),
938        "agent" => Some(format!(
939            "AGENT\n{}",
940            b["chunks"]
941                .as_array()
942                .into_iter()
943                .flatten()
944                .filter(|x| x["content"]["type"] == "text")
945                .map(|x| s(&x["content"]["text"]))
946                .collect::<String>()
947        )),
948        "tool" => {
949            let call = &b["call"];
950            Some(format!(
951                "TOOL {}\nTITLE: {}\nCALL: {}",
952                call["kind"]
953                    .as_str()
954                    .filter(|x| !x.is_empty())
955                    .unwrap_or("call")
956                    .to_uppercase(),
957                s(&call["title"]),
958                call
959            ))
960        }
961        "message" => {
962            let body = &b["event"]["body"];
963            let typ = body["type"].as_str().unwrap_or("");
964            if typ == "new_github_item" || typ.starts_with("github_") {
965                notice = Some((
966                    body["number"].as_u64(),
967                    body["repo"].as_str().map(str::to_string),
968                ));
969            }
970            Some(format!(
971                "PEER MESSAGE {}\n{}",
972                s(&body["from"]["title"]),
973                s(&body["text"])
974            ))
975        }
976        _ => None,
977    };
978    RowRender {
979        text,
980        notice,
981        created: timestamp(created_at_ms).map_err(|_| ()),
982    }
983}
984
985/// `\r\n` and lone `\r` become `\n` across piece boundaries.
986#[derive(Default)]
987struct LineEndings {
988    after_cr: bool,
989}
990impl LineEndings {
991    fn push(&mut self, mut s: &str, sink: &mut impl TextSink) {
992        if self.after_cr && !s.is_empty() {
993            self.after_cr = false;
994            s = s.strip_prefix('\n').unwrap_or(s);
995        }
996        while !sink.is_full()
997            && let Some(i) = s.find('\r')
998        {
999            sink.push_str(&s[..i]);
1000            sink.push_str("\n");
1001            s = &s[i + 1..];
1002            match s.strip_prefix('\n') {
1003                Some(rest) => s = rest,
1004                None if s.is_empty() => self.after_cr = true,
1005                None => {}
1006            }
1007        }
1008        if !sink.is_full() {
1009            sink.push_str(s);
1010        }
1011    }
1012}
1013
1014/// Copies a pair's header while it is emitted.
1015struct Tee<'a, S> {
1016    sink: &'a mut S,
1017    copy: &'a mut String,
1018}
1019impl<S: TextSink> TextSink for Tee<'_, S> {
1020    fn push_str(&mut self, text: &str) {
1021        self.copy.push_str(text);
1022        self.sink.push_str(text);
1023    }
1024}
1025
1026struct PairRender<S> {
1027    cutoff_ms: i64,
1028    repo_lower: String,
1029    number: u64,
1030    expected: HistoryCounts,
1031    seen: HistoryCounts,
1032    endings: LineEndings,
1033    sink: S,
1034    /// The header as emitted.
1035    header: String,
1036}
1037
1038impl<S: TextSink> PairRender<S> {
1039    fn put(&mut self, s: &str) {
1040        self.endings.push(s, &mut self.sink);
1041    }
1042    fn put_header(&mut self, s: &str) {
1043        self.sink.mark(None);
1044        let mut tee = Tee {
1045            sink: &mut self.sink,
1046            copy: &mut self.header,
1047        };
1048        self.endings.push(s, &mut tee);
1049    }
1050    fn include(
1051        &mut self,
1052        row: &RowRender,
1053        ordinal: usize,
1054        created_at_ms: i64,
1055        changed_ms: i64,
1056    ) -> Result<()> {
1057        if created_at_ms > self.cutoff_ms || changed_ms > self.cutoff_ms {
1058            return Ok(());
1059        }
1060        let Some(text) = &row.text else {
1061            return Ok(());
1062        };
1063        if let Some((n, repo)) = &row.notice
1064            && notice_names_item(*n, repo.as_deref(), self.number, &self.repo_lower)
1065        {
1066            self.seen.notices += 1;
1067            return Ok(());
1068        }
1069        if self.seen.included > 0 {
1070            self.put("\n\n");
1071        }
1072        self.seen.included += 1;
1073        let ts = row
1074            .created
1075            .as_ref()
1076            .map_err(|()| anyhow::anyhow!("timestamp out of range"))?;
1077        self.sink.mark(Some(ordinal));
1078        self.put("[");
1079        self.put(ts);
1080        self.put("] ");
1081        self.put(text);
1082        Ok(())
1083    }
1084}
1085
1086/// Collects a range of code points and the stamp that starts at one position.
1087struct Slice {
1088    from: u64,
1089    to: u64,
1090    pos: u64,
1091    out: String,
1092    stamp_at: Option<u64>,
1093    /// 0 before the stamp, 1 inside it, 2 after its closing bracket.
1094    stamp_state: u8,
1095    stamp: String,
1096}
1097impl Slice {
1098    fn done(&self) -> bool {
1099        self.pos >= self.to && (self.stamp_at.is_none() || self.stamp_state == 2)
1100    }
1101}
1102impl TextSink for Slice {
1103    fn is_full(&self) -> bool {
1104        self.done()
1105    }
1106    fn push_str(&mut self, text: &str) {
1107        for c in text.chars() {
1108            if self.done() {
1109                return;
1110            }
1111            if (self.from..self.to).contains(&self.pos) {
1112                self.out.push(c);
1113            }
1114            if self.stamp_state == 1 {
1115                if c == ']' {
1116                    self.stamp_state = 2;
1117                } else {
1118                    self.stamp.push(c);
1119                }
1120            } else if self.stamp_state == 0 && self.stamp_at == Some(self.pos) {
1121                self.stamp_state = 1;
1122            }
1123            self.pos += 1;
1124        }
1125    }
1126}
1127
1128/// Gives back the stored rows the passes saw.
1129pub trait RowFetch {
1130    /// The body of the row the second pass was given under `key`.
1131    fn body(&mut self, key: i64) -> Result<String>;
1132}
1133
1134/// What the second pass knows about each row it was given, 24 bytes a row and
1135/// shared by every item: enough to tell which rows an item includes and to
1136/// fetch the ones a window needs.
1137#[derive(Clone, Copy)]
1138struct RowInfo {
1139    key: i64,
1140    created_at_ms: i64,
1141    last_changed_at_ms: i64,
1142}
1143
1144/// One item's cutoff and notice rule, kept to render rows again.
1145struct PairFilter {
1146    cutoff_ms: i64,
1147    repo_lower: String,
1148    number: u64,
1149    header: String,
1150}
1151
1152/// A window being rendered again.
1153struct Replay {
1154    pair: usize,
1155    window: usize,
1156    slice: Slice,
1157    endings: LineEndings,
1158    /// The ordinal to look from for the next row this item includes.
1159    next: usize,
1160    chunks: usize,
1161    /// Whether the header was already replayed, so the first row may be any included one.
1162    endings_started: bool,
1163    done: bool,
1164    /// Key of the stamp this replay collects, if it is the one to.
1165    stamp_key: (Option<usize>, u32, u32),
1166}
1167
1168/// One item's windows with their recovered text.
1169#[derive(Debug)]
1170pub struct HistoryResult<D> {
1171    pub done: D,
1172    pub spans: Vec<Span>,
1173}
1174
1175/// One item's transcript view of a session: its cutoff, the item it is about,
1176/// and where its rendered text goes.
1177pub struct HistoryPairSpec<S> {
1178    pub cutoff_ms: i64,
1179    pub repo: String,
1180    pub number: u64,
1181    pub sink: S,
1182}
1183
1184/// Renders one session's rows for several items at once. Rows are read twice,
1185/// in the same snapshot: `count_row` over all of them fixes each header, then
1186/// `row` over them in `(position, stable_id)` order renders each exactly once
1187/// and hands it to every pair that includes it. The rendered text is
1188/// byte-identical to the whole-string rendering of the frozen format; it is
1189/// never held whole. `complete` then renders again, once, only the rows around
1190/// the windows the sinks selected.
1191pub struct SessionHistory<S> {
1192    session_id: String,
1193    pairs: Vec<PairRender<S>>,
1194    started: bool,
1195    rows: Vec<RowInfo>,
1196    /// Rows that may be item-specific notices: ordinal to number and repository.
1197    notices: std::collections::HashMap<usize, (Option<u64>, Option<String>)>,
1198}
1199
1200impl<S: HistorySink> SessionHistory<S> {
1201    pub fn new(session_id: &str, pairs: Vec<HistoryPairSpec<S>>) -> Self {
1202        Self {
1203            session_id: session_id.to_string(),
1204            pairs: pairs
1205                .into_iter()
1206                .map(|p| PairRender {
1207                    cutoff_ms: p.cutoff_ms,
1208                    repo_lower: p.repo.to_lowercase(),
1209                    number: p.number,
1210                    expected: HistoryCounts::default(),
1211                    seen: HistoryCounts::default(),
1212                    endings: LineEndings::default(),
1213                    sink: p.sink,
1214                    header: String::new(),
1215                })
1216                .collect(),
1217            started: false,
1218            rows: Vec::new(),
1219            notices: Default::default(),
1220        }
1221    }
1222
1223    /// The latest cutoff of any pair. A row created or changed after it is
1224    /// withheld from every pair, so it only needs counting.
1225    pub fn max_cutoff_ms(&self) -> Option<i64> {
1226        self.pairs.iter().map(|p| p.cutoff_ms).max()
1227    }
1228
1229    /// First pass.
1230    pub fn count_row(&mut self, row: &RowMeta<'_>) {
1231        for pair in &mut self.pairs {
1232            let counts = &mut pair.expected;
1233            if row.created_at_ms > pair.cutoff_ms {
1234                counts.later += 1;
1235            } else if row.last_changed_at_ms > pair.cutoff_ms {
1236                counts.changed += 1;
1237            } else if row.kind == "message" {
1238                if is_notice_type(row.event_type)
1239                    && notice_names_item(
1240                        row.event_number,
1241                        row.event_repo,
1242                        pair.number,
1243                        &pair.repo_lower,
1244                    )
1245                {
1246                    counts.notices += 1;
1247                } else {
1248                    counts.included += 1;
1249                }
1250            } else if kind_renders(row.kind) {
1251                counts.included += 1;
1252            }
1253        }
1254    }
1255
1256    /// Writes every header; call once between the passes.
1257    pub fn begin(&mut self) -> Result<()> {
1258        for pair in &mut self.pairs {
1259            let c = pair.expected;
1260            let header = format!(
1261                "Session transcript as of {} (UTC)\nSession id: {}\nTranscript rows included: {}; withheld because changed after cutoff: {}; excluded because created later: {}; item-specific GitHub mailbox notices removed: {}.\nRows come only from Mjolnir materialized transcript records; timestamps are row creation times.\n\n",
1262                timestamp(pair.cutoff_ms)?,
1263                self.session_id,
1264                c.included,
1265                c.changed,
1266                c.later,
1267                c.notices
1268            );
1269            pair.put_header(&header);
1270        }
1271        self.started = true;
1272        Ok(())
1273    }
1274
1275    /// Second pass, over the rows in order. `key` is how `RowFetch` finds the
1276    /// row again. Rows nobody includes are not decoded; rows of a kind that
1277    /// never renders may be left out.
1278    pub fn row(
1279        &mut self,
1280        key: i64,
1281        created_at_ms: i64,
1282        last_changed_at_ms: i64,
1283        body_json: &str,
1284    ) -> Result<()> {
1285        anyhow::ensure!(self.started, "history rows rendered before the headers");
1286        let info = RowInfo {
1287            key,
1288            created_at_ms,
1289            last_changed_at_ms,
1290        };
1291        if !self
1292            .pairs
1293            .iter()
1294            .any(|p| created_at_ms <= p.cutoff_ms && last_changed_at_ms <= p.cutoff_ms)
1295        {
1296            self.rows.push(info);
1297            return Ok(());
1298        }
1299        let body: Value = serde_json::from_str(body_json)?;
1300        let rendered = render_row(created_at_ms, &body);
1301        drop(body);
1302        if rendered.text.is_none() {
1303            return Ok(());
1304        }
1305        let ordinal = self.rows.len();
1306        self.rows.push(info);
1307        if let Some(notice) = &rendered.notice {
1308            self.notices.insert(ordinal, notice.clone());
1309        }
1310        for pair in &mut self.pairs {
1311            pair.include(&rendered, ordinal, created_at_ms, last_changed_at_ms)?;
1312        }
1313        Ok(())
1314    }
1315
1316    /// Ends every transcript, lets each sink select its windows, and renders
1317    /// the rows around the selected windows again, once for all of them, with
1318    /// `fetch` reading the same rows as the passes did. Fails when the second
1319    /// pass disagrees with the counts in the headers, which means the rows
1320    /// changed between the passes or the counting query drifted from the
1321    /// renderer. `check` is called often; an error from it ends the work.
1322    pub fn complete(
1323        self,
1324        fetch: &mut dyn RowFetch,
1325        check: &dyn Fn() -> Result<()>,
1326    ) -> Result<Vec<HistoryResult<S::Done>>> {
1327        let Self {
1328            pairs,
1329            rows,
1330            notices,
1331            ..
1332        } = self;
1333        let mut filters = Vec::new();
1334        let mut dones = Vec::new();
1335        let mut selections = Vec::new();
1336        for mut pair in pairs {
1337            check()?;
1338            anyhow::ensure!(
1339                pair.seen.included == pair.expected.included
1340                    && pair.seen.notices == pair.expected.notices,
1341                "history header counts {:?} disagree with the rendered rows {:?}",
1342                pair.expected,
1343                pair.seen
1344            );
1345            pair.put("\n");
1346            filters.push(PairFilter {
1347                cutoff_ms: pair.cutoff_ms,
1348                repo_lower: pair.repo_lower,
1349                number: pair.number,
1350                header: pair.header,
1351            });
1352            let (done, selected) = pair.sink.select(check)?;
1353            dones.push(done);
1354            selections.push(selected);
1355        }
1356        let included = |pair: &PairFilter, ordinal: usize| {
1357            let row = &rows[ordinal];
1358            row.created_at_ms <= pair.cutoff_ms
1359                && row.last_changed_at_ms <= pair.cutoff_ms
1360                && !notices.get(&ordinal).is_some_and(|(n, repo)| {
1361                    notice_names_item(*n, repo.as_deref(), pair.number, &pair.repo_lower)
1362                })
1363        };
1364        // One replay per window; windows with the same stamp share one collector.
1365        let mut replays = Vec::new();
1366        let mut collectors = std::collections::HashSet::new();
1367        for (p, selected) in selections.iter().enumerate() {
1368            for (w, s) in selected.iter().enumerate() {
1369                let header = s.ordinal == HEADER;
1370                let segment = s.start - s.offset as usize;
1371                let stamp_at = match s.stamp {
1372                    Some(at) => Some(at.checked_sub(segment).ok_or_else(|| {
1373                        anyhow::anyhow!("a window's stamp lies before its part of the transcript")
1374                    })? as u64),
1375                    None => None,
1376                };
1377                let key = (
1378                    header.then_some(p),
1379                    s.ordinal,
1380                    stamp_at.map_or(u32::MAX, |at| at as u32),
1381                );
1382                let collect = stamp_at.is_some() && collectors.insert(key);
1383                let mut replay = Replay {
1384                    pair: p,
1385                    window: w,
1386                    slice: Slice {
1387                        from: s.offset as u64,
1388                        to: (s.offset as usize + s.end - s.start) as u64,
1389                        pos: 0,
1390                        out: String::new(),
1391                        stamp_at: if collect { stamp_at } else { None },
1392                        stamp_state: 0,
1393                        stamp: String::new(),
1394                    },
1395                    endings: LineEndings::default(),
1396                    next: if header { 0 } else { s.ordinal as usize },
1397                    chunks: 0,
1398                    endings_started: header,
1399                    done: false,
1400                    stamp_key: key,
1401                };
1402                if header {
1403                    replay.endings.push(&filters[p].header, &mut replay.slice);
1404                }
1405                replays.push(replay);
1406            }
1407        }
1408        loop {
1409            check()?;
1410            let mut target: Option<usize> = None;
1411            for replay in replays.iter_mut().filter(|r| !r.done) {
1412                if replay.slice.done() {
1413                    replay.done = true;
1414                    continue;
1415                }
1416                let filter = &filters[replay.pair];
1417                let anchor = replay.next;
1418                while replay.next < rows.len() && !included(filter, replay.next) {
1419                    replay.next += 1;
1420                }
1421                anyhow::ensure!(
1422                    replay.chunks > 0
1423                        || replay.endings_started
1424                        || replay.next == anchor
1425                        || replay.next >= rows.len(),
1426                    "a window's row is not one its item includes"
1427                );
1428                if replay.next < rows.len() {
1429                    target = Some(target.map_or(replay.next, |t| t.min(replay.next)));
1430                } else {
1431                    // No more rows: the transcript ends with a newline.
1432                    replay.endings.push("\n", &mut replay.slice);
1433                    replay.done = true;
1434                }
1435            }
1436            let Some(target) = target else { break };
1437            let body = fetch.body(rows[target].key)?;
1438            let rendered = render_row(
1439                rows[target].created_at_ms,
1440                &serde_json::from_str::<Value>(&body)?,
1441            );
1442            drop(body);
1443            let text = rendered
1444                .text
1445                .as_ref()
1446                .ok_or_else(|| anyhow::anyhow!("history row {target} no longer renders"))?;
1447            let ts = rendered
1448                .created
1449                .as_ref()
1450                .map_err(|()| anyhow::anyhow!("timestamp out of range"))?;
1451            for replay in replays.iter_mut().filter(|r| !r.done && r.next == target) {
1452                if replay.chunks > 0 {
1453                    replay.endings.push("\n\n", &mut replay.slice);
1454                }
1455                for piece in ["[", ts, "] ", text] {
1456                    if replay.slice.done() {
1457                        break;
1458                    }
1459                    replay.endings.push(piece, &mut replay.slice);
1460                }
1461                replay.chunks += 1;
1462                replay.next += 1;
1463            }
1464        }
1465        let mut stamps = std::collections::HashMap::new();
1466        for replay in &mut replays {
1467            anyhow::ensure!(
1468                replay.slice.pos >= replay.slice.to
1469                    && (replay.slice.stamp_at.is_none() || replay.slice.stamp_state == 2),
1470                "history rows changed between reading them and recovering a window"
1471            );
1472            if replay.slice.stamp_at.is_some() {
1473                stamps.insert(replay.stamp_key, std::mem::take(&mut replay.slice.stamp));
1474            }
1475        }
1476        let mut results = dones
1477            .into_iter()
1478            .map(|done| HistoryResult {
1479                done,
1480                spans: Vec::new(),
1481            })
1482            .collect::<Vec<_>>();
1483        for replay in replays {
1484            let s = &selections[replay.pair][replay.window];
1485            let time = s.stamp.map(|_| stamps[&replay.stamp_key].clone());
1486            results[replay.pair].spans.push(Span {
1487                start: s.start,
1488                end: s.end,
1489                score: s.score,
1490                snippet: Snippet {
1491                    time,
1492                    text: redact(replay.slice.out.trim_matches(|c| u::contains(u::SPACE, c))),
1493                },
1494            });
1495        }
1496        Ok(results)
1497    }
1498}
1499
1500/// A scanner for one item against one session. `base` must already be bounded
1501/// and redacted once; the original item's full body is used only for retrieval.
1502/// None when the item has no searchable identifiers, which gives empty history.
1503pub fn history_scanner(
1504    original: &mj_core::github_item::GithubItem,
1505    base: &mj_core::github_item::GithubItemEvidence,
1506) -> Result<Option<HistoryScanner>> {
1507    let original: Value = serde_json::from_str(&serde_json::to_string(original)?)?;
1508    let base: Value = serde_json::from_str(&serde_json::to_string(base)?)?;
1509    // An item without searchable identifiers can never select a snippet.
1510    let ids = identifiers(&original);
1511    if ids.is_empty() {
1512        return Ok(None);
1513    }
1514    Ok(Some(HistoryScanner::with_identifiers(
1515        ids,
1516        &base["session"],
1517    )))
1518}
1519
1520/// Training-format segments, item first, with history last in the session.
1521/// Evidence is already bounded/redacted; serialization never bounds it again.
1522pub fn student_segments(
1523    evidence: &mj_core::github_item::GithubItemEvidence,
1524) -> Result<(String, String)> {
1525    Ok((
1526        serde_json::to_string(&evidence.item)?,
1527        serde_json::to_string(&evidence.session)?,
1528    ))
1529}
1530
1531#[cfg(test)]
1532mod tests {
1533    use super::*;
1534    use std::collections::{BTreeMap, HashSet};
1535    fn slice(s: &[char], a: usize, b: usize) -> String {
1536        s[a..b].iter().collect()
1537    }
1538    // The implementation that streaming replaced, kept only as the oracle for
1539    // the differential test: whole-text retrieval over `Vec<char>` and the
1540    // whole-string renderer.
1541    /// Original title/body must be supplied, independently of the bounded classifier item.
1542    fn retrieve_reference(item: &Value, text: &str, session: &Value) -> Vec<Span> {
1543        let t = chars(text);
1544        let byte_positions = text
1545            .char_indices()
1546            .map(|(byte, _)| byte)
1547            .collect::<Vec<_>>();
1548        let digest = chars(&spaced(session));
1549        let known: HashSet<String> = (0..digest.len().saturating_sub(99))
1550            .map(|i| slice(&digest, i, i + 100))
1551            .collect();
1552        let existing = session["conversation"].as_str().unwrap_or("");
1553        let mut candidates: BTreeMap<usize, (f64, usize, HashSet<String>)> = BTreeMap::new();
1554        for (id, base) in identifiers(item) {
1555            let numeric = id.chars().all(|c| u::contains(u::ISDIGIT, c));
1556            let mut hits = Vec::new();
1557            let mut offset = 0;
1558            while let Some(p) = text[offset..].find(&id) {
1559                let b = offset + p;
1560                let pos = byte_positions.partition_point(|&byte| byte < b);
1561                let end = pos + id.chars().count();
1562                offset = b + id.len();
1563                let ok = if numeric {
1564                    (pos == 0 || !u::contains(u::ISDIGIT, t[pos - 1]))
1565                        && (end == t.len() || !u::contains(u::ISDIGIT, t[end]))
1566                } else {
1567                    (pos == 0 || !(u::contains(u::ISALNUM, t[pos - 1]) || t[pos - 1] == '_'))
1568                        && (end == t.len() || !u::contains(u::ISALNUM, t[end]))
1569                };
1570                if ok {
1571                    hits.push(pos);
1572                }
1573            }
1574            // `f64::ln_1p` calls the platform's C library, whose log1p is not
1575            // correctly rounded: glibc, Apple's libm and MSVC each differ by an
1576            // ulp on some inputs, which broke byte parity on Windows. The pure
1577            // Rust fdlibm port gives the same bits on every platform and
1578            // reproduces every reference fixture.
1579            let weight = base
1580                * (1.0 + libm::log1p((t.len() as f64 / 500.0).max(1.0) / (1 + hits.len()) as f64));
1581            for pos in hits {
1582                let start = (pos / 250 * 250).saturating_sub(125);
1583                let c = candidates.entry(start).or_insert((
1584                    0.0,
1585                    (start + 500).min(t.len()),
1586                    HashSet::new(),
1587                ));
1588                if c.2.insert(id.clone()) {
1589                    c.0 += weight;
1590                }
1591            }
1592        }
1593        let stamps = re(r"(?m)^\[([^\]\n]+)\]")
1594            .captures_iter(text)
1595            .map(|m| {
1596                (
1597                    byte_positions.partition_point(|&byte| byte < m.get(0).unwrap().start()),
1598                    m[1].to_string(),
1599                )
1600            })
1601            .collect::<Vec<_>>();
1602        let mut ranked = Vec::new();
1603        for (start, (score, end, _)) in candidates {
1604            let raw = slice(&t, start, end);
1605            let raw = raw.trim_matches(|c| u::contains(u::SPACE, c));
1606            let rt = redact(raw);
1607            let r = chars(&rt);
1608            if existing.contains(&rt)
1609                || (0..r.len().saturating_sub(99))
1610                    .step_by(50)
1611                    .any(|i| known.contains(&slice(&r, i, i + 100)))
1612            {
1613                continue;
1614            }
1615            let score = score * (1.0 + 0.1 * start as f64 / t.len().max(1) as f64);
1616            let time = stamps
1617                .iter()
1618                .rev()
1619                .find(|(p, _)| *p <= start)
1620                .map(|(_, s)| s.clone());
1621            ranked.push((
1622                Span {
1623                    start,
1624                    end,
1625                    score,
1626                    snippet: Snippet { time, text: rt },
1627                },
1628                raw.chars().count(),
1629            ));
1630        }
1631        ranked.sort_by(|a, b| {
1632            b.0.score
1633                .total_cmp(&a.0.score)
1634                .then(b.0.start.cmp(&a.0.start))
1635        });
1636        let mut selected: Vec<Span> = Vec::new();
1637        let mut used = 0;
1638        for (span, len) in ranked {
1639            if used + len > 2100
1640                || selected
1641                    .iter()
1642                    .any(|s| span.start < s.end && span.end > s.start)
1643            {
1644                continue;
1645            }
1646            used += len;
1647            selected.push(span);
1648        }
1649        selected.sort_by_key(|s| s.start);
1650        selected
1651    }
1652    /// Raw persisted rows retain tool-call JSON order and unknown row kinds for cutoff counts.
1653    #[derive(Clone, Debug, Deserialize)]
1654    struct HistoryRow {
1655        pub stable_id: String,
1656        pub position: i64,
1657        pub created_at_ms: i64,
1658        pub last_changed_at_ms: i64,
1659        pub body: Value,
1660    }
1661    /// Render one shared snapshot at the item's creation time; never use edited later bodies.
1662    fn render_reference(
1663        session_id: &str,
1664        rows: &[HistoryRow],
1665        cutoff_ms: i64,
1666        repo: &str,
1667        number: u64,
1668    ) -> Result<String> {
1669        let mut ordered = rows.iter().collect::<Vec<_>>();
1670        ordered.sort_by(|a, b| {
1671            a.position
1672                .cmp(&b.position)
1673                .then(a.stable_id.cmp(&b.stable_id))
1674        });
1675        let (mut changed, mut later, mut notices) = (0, 0, 0);
1676        let mut chunks = Vec::new();
1677        for row in ordered {
1678            if row.created_at_ms > cutoff_ms {
1679                later += 1;
1680                continue;
1681            }
1682            if row.last_changed_at_ms > cutoff_ms {
1683                changed += 1;
1684                continue;
1685            }
1686            let b = &row.body;
1687            let s = |v: &Value| v.as_str().unwrap_or("").to_string();
1688            let rendered = match b["kind"].as_str().unwrap_or("") {
1689                "user" => Some(format!(
1690                    "USER\n{}",
1691                    b["content"]
1692                        .as_array()
1693                        .into_iter()
1694                        .flatten()
1695                        .filter(|x| x["type"] == "text")
1696                        .map(|x| s(&x["text"]))
1697                        .collect::<Vec<_>>()
1698                        .join("\n")
1699                )),
1700                "agent" => Some(format!(
1701                    "AGENT\n{}",
1702                    b["chunks"]
1703                        .as_array()
1704                        .into_iter()
1705                        .flatten()
1706                        .filter(|x| x["content"]["type"] == "text")
1707                        .map(|x| s(&x["content"]["text"]))
1708                        .collect::<String>()
1709                )),
1710                "tool" => {
1711                    let call = &b["call"];
1712                    Some(format!(
1713                        "TOOL {}\nTITLE: {}\nCALL: {}",
1714                        call["kind"]
1715                            .as_str()
1716                            .filter(|x| !x.is_empty())
1717                            .unwrap_or("call")
1718                            .to_uppercase(),
1719                        s(&call["title"]),
1720                        call
1721                    ))
1722                }
1723                "message" => {
1724                    let body = &b["event"]["body"];
1725                    let typ = body["type"].as_str().unwrap_or("");
1726                    if (typ == "new_github_item" || typ.starts_with("github_"))
1727                        && body["number"].as_u64() == Some(number)
1728                        && body["repo"]
1729                            .as_str()
1730                            .is_none_or(|r| r.to_lowercase() == repo.to_lowercase())
1731                    {
1732                        notices += 1;
1733                        continue;
1734                    }
1735                    Some(format!(
1736                        "PEER MESSAGE {}\n{}",
1737                        s(&body["from"]["title"]),
1738                        s(&body["text"])
1739                    ))
1740                }
1741                _ => None,
1742            };
1743            if let Some(text) = rendered {
1744                chunks.push(format!("[{}] {}", timestamp(row.created_at_ms)?, text));
1745            }
1746        }
1747        Ok(format!("Session transcript as of {} (UTC)\nSession id: {session_id}\nTranscript rows included: {}; withheld because changed after cutoff: {changed}; excluded because created later: {later}; item-specific GitHub mailbox notices removed: {notices}.\nRows come only from Mjolnir materialized transcript records; timestamps are row creation times.\n\n{}\n",timestamp(cutoff_ms)?,chunks.len(),chunks.join("\n\n")).replace("\r\n","\n").replace('\r',"\n"))
1748    }
1749
1750    /// Runs both passes of the streaming renderer over rows held in memory,
1751    /// the way the store feeds them, into the given sinks.
1752    struct MemoryRows(Vec<String>);
1753    impl RowFetch for MemoryRows {
1754        fn body(&mut self, key: i64) -> Result<String> {
1755            Ok(self.0[key as usize].clone())
1756        }
1757    }
1758    fn stream_pairs<S: HistorySink>(
1759        session_id: &str,
1760        rows: &[HistoryRow],
1761        pairs: Vec<HistoryPairSpec<S>>,
1762    ) -> Vec<HistoryResult<S::Done>> {
1763        let mut ordered = rows.iter().collect::<Vec<_>>();
1764        ordered.sort_by(|a, b| {
1765            a.position
1766                .cmp(&b.position)
1767                .then(a.stable_id.cmp(&b.stable_id))
1768        });
1769        let mut memory = MemoryRows(
1770            ordered
1771                .iter()
1772                .map(|r| serde_json::to_string(&r.body).unwrap())
1773                .collect(),
1774        );
1775        let mut history = SessionHistory::new(session_id, pairs);
1776        for row in &ordered {
1777            let b = &row.body;
1778            let event = &b["event"]["body"];
1779            history.count_row(&RowMeta {
1780                created_at_ms: row.created_at_ms,
1781                last_changed_at_ms: row.last_changed_at_ms,
1782                kind: b["kind"].as_str().unwrap_or(""),
1783                event_type: event["type"].as_str().unwrap_or(""),
1784                event_number: event["number"].as_u64(),
1785                event_repo: event["repo"].as_str(),
1786            });
1787        }
1788        history.begin().unwrap();
1789        for (n, row) in ordered.iter().enumerate() {
1790            history
1791                .row(
1792                    n as i64,
1793                    row.created_at_ms,
1794                    row.last_changed_at_ms,
1795                    &memory.0[n],
1796                )
1797                .unwrap();
1798        }
1799        history.complete(&mut memory, &|| Ok(())).unwrap()
1800    }
1801    fn stream_render(
1802        session_id: &str,
1803        rows: &[HistoryRow],
1804        cutoff_ms: i64,
1805        repo: &str,
1806        number: u64,
1807    ) -> String {
1808        stream_pairs(
1809            session_id,
1810            rows,
1811            vec![HistoryPairSpec {
1812                cutoff_ms,
1813                repo: repo.into(),
1814                number,
1815                sink: String::new(),
1816            }],
1817        )
1818        .pop()
1819        .unwrap()
1820        .done
1821    }
1822    struct Rng(u64);
1823    impl Rng {
1824        fn next(&mut self) -> u64 {
1825            self.0 ^= self.0 << 13;
1826            self.0 ^= self.0 >> 7;
1827            self.0 ^= self.0 << 17;
1828            self.0
1829        }
1830        fn below(&mut self, n: usize) -> usize {
1831            (self.next() % n as u64) as usize
1832        }
1833    }
1834    const PIECES: &[&str] = &[
1835        "#42",
1836        "#420",
1837        "x#42",
1838        "#42y",
1839        "#4",
1840        "42",
1841        "src/foo_bar.rs",
1842        "foo_bar.rs",
1843        "foo_bar",
1844        "foo_bar_baz_qux",
1845        "FooBar",
1846        "fooBar_x",
1847        "CAFÉ",
1848        "CAFE",
1849        "AB",
1850        "ABC",
1851        "ABCD",
1852        "é",
1853        "😀",
1854        "日本語",
1855        "²",
1856        "٣",
1857        "_",
1858        ".",
1859        "-",
1860        "/",
1861        " ",
1862        " ",
1863        " ",
1864        "word",
1865        "words",
1866        "\n",
1867        "\n",
1868        "\r\n",
1869        "\r",
1870        "\r\n\r\n",
1871        "\n[2024-01-01 10:00]\n",
1872        "\n[x",
1873        "]",
1874        "[]",
1875        "\n[a\nb]",
1876        "\u{a0}",
1877        "\t",
1878        "tokenaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1879        "https://example.com/src/foo_bar.rs",
1880        "the quick brown fox jumps over the lazy dog ",
1881    ];
1882    fn random_text(rng: &mut Rng, pieces: usize) -> String {
1883        let mut text = String::new();
1884        for _ in 0..pieces {
1885            text.push_str(PIECES[rng.below(PIECES.len())]);
1886            if rng.below(6) == 0 {
1887                text.push_str(&"lorem ipsum ".repeat(rng.below(60)));
1888            }
1889        }
1890        text
1891    }
1892    fn random_rows(rng: &mut Rng, count: usize) -> Vec<HistoryRow> {
1893        (0..count)
1894            .map(|n| {
1895                let text = if rng.below(40) == 0 {
1896                    // More than a pipe buffer in one row.
1897                    format!("{}{}", random_text(rng, 30), "padding ".repeat(9000))
1898                } else {
1899                    {
1900                        let pieces = 1 + rng.below(40);
1901                        random_text(rng, pieces)
1902                    }
1903                };
1904                let created = 500 + rng.below(1200) as i64;
1905                let changed = if rng.below(6) == 0 { created + rng.below(900) as i64 } else { created };
1906                let body = match rng.below(7) {
1907                    0 => json!({"kind": "user", "content": [{"type": "text", "text": text}, {"type": "image"}, {"type": "text", "text": "#42"}]}),
1908                    1 => json!({"kind": "agent", "chunks": [{"content": {"type": "text", "text": text}}, {"content": {"type": "text", "text": "src/foo_bar.rs"}}]}),
1909                    2 => json!({"kind": "tool", "call": {"title": text, "kind": if rng.below(2) == 0 { "execute" } else { "" }, "rawInput": {"n": 1.5e300, "z": 0.1, "t": "#42\r\n"}, "toolCallId": "c"}}),
1910                    3 | 4 => {
1911                        let typ = ["github_issue", "new_github_item", "peer", "github_comment"][rng.below(4)];
1912                        let repo = [json!("Owner/Repo"), json!("other/repo"), json!(null), json!(7)][rng.below(4)].clone();
1913                        let number = [json!(42), json!(43), json!(42.0), json!("42")][rng.below(4)].clone();
1914                        json!({"kind": "message", "event": {"body": {"type": typ, "number": number, "repo": repo, "text": text, "from": {"title": "peer"}}}})
1915                    }
1916                    5 => json!({"kind": "thought", "text": text}),
1917                    _ => json!({"kind": 5, "x": text}),
1918                };
1919                HistoryRow {
1920                    stable_id: format!("row-{}", rng.below(count + 3)),
1921                    position: n as i64 / 2,
1922                    created_at_ms: created,
1923                    last_changed_at_ms: changed,
1924                    body: serde_json::from_value(body).unwrap(),
1925                }
1926            })
1927            .collect()
1928    }
1929    fn random_item(rng: &mut Rng) -> Value {
1930        let title = random_text(rng, 4);
1931        let body = format!(
1932            "{} #42 src/foo_bar.rs foo_bar_baz_qux FooBar CAFÉ ABC {}",
1933            random_text(rng, 8),
1934            random_text(rng, 8)
1935        );
1936        serde_json::from_value(json!({"title": title, "body": body})).unwrap()
1937    }
1938    fn spans_json(spans: &[Span]) -> String {
1939        spans
1940            .iter()
1941            .map(|s| {
1942                format!(
1943                    "{}:{}:{:016x}:{:?}:{:?}",
1944                    s.start,
1945                    s.end,
1946                    s.score.to_bits(),
1947                    s.snippet.time,
1948                    s.snippet.text
1949                )
1950            })
1951            .collect::<Vec<_>>()
1952            .join("\n")
1953    }
1954
1955    fn finish_whole(scanner: HistoryScanner, text: &str) -> Vec<Span> {
1956        spans_from_whole_text(scanner.finish(&|| Ok(())).unwrap(), text)
1957    }
1958
1959    // An identifier in every window of a long transcript, with a megabyte-long
1960    // bracketed line that opens a stamp under hundreds of windows, must not make
1961    // the scanner keep a string per window.
1962    #[test]
1963    fn scanner_holds_a_constant_number_of_window_strings() {
1964        let item: Value =
1965            serde_json::from_value(json!({"title": "t", "body": "src/zz_marker.rs"})).unwrap();
1966        let session: Value = serde_json::from_value(json!({"conversation": ""})).unwrap();
1967        let mut text = String::from("[2024-01-01T00:00:00.000Z] USER\n");
1968        for _ in 0..4000 {
1969            text.push_str("src/zz_marker.rs lorem ipsum dolor sit amet ééé 😀 consectetur\n");
1970        }
1971        text.push_str("\n[");
1972        for _ in 0..40_000 {
1973            text.push_str("src/zz_marker.rs padding padding padding ");
1974        }
1975        text.push_str("]\n");
1976        for _ in 0..4000 {
1977            text.push_str("lorem src/zz_marker.rs ipsum dolor sit amet\n");
1978        }
1979        assert!(text.len() > 1_000_000);
1980        let mut scanner = HistoryScanner::new(&item, &session);
1981        let mut rest = text.as_str();
1982        while !rest.is_empty() {
1983            let mut cut = 4096.min(rest.len());
1984            while !rest.is_char_boundary(cut) {
1985                cut += 1;
1986            }
1987            scanner.push_str(&rest[..cut]);
1988            rest = &rest[cut..];
1989        }
1990        assert!(scanner.live.len() > 8000, "{}", scanner.live.len());
1991        assert_eq!(std::mem::size_of::<Candidate>(), 24);
1992        assert_eq!(std::mem::size_of::<RowInfo>(), 24);
1993        assert!(scanner.peak_texts <= 3, "peak {}", scanner.peak_texts);
1994        assert!(scanner.open.len() <= 3);
1995        let expected = retrieve_reference(&item, &text, &session);
1996        assert!(!expected.is_empty());
1997        assert_eq!(
1998            spans_json(&finish_whole(scanner, &text)),
1999            spans_json(&expected)
2000        );
2001    }
2002
2003    // Streaming must reproduce the whole-text implementation exactly: header
2004    // counts, line-ending replacement, notices, rows that changed after the
2005    // cutoff, multi-byte text, identifiers across the window grid and the row
2006    // boundaries, bracket lines, and rows larger than a pipe buffer.
2007    #[test]
2008    fn streaming_history_matches_the_whole_text_reference() {
2009        let mut rng = Rng(0x9e3779b97f4a7c15);
2010        let mut retrieved = 0;
2011        for round in 0..30 {
2012            let count = 1 + rng.below(40);
2013            let rows = random_rows(&mut rng, count);
2014            let item = random_item(&mut rng);
2015            let session: Value = serde_json::from_value(json!({
2016                "conversation": if round % 3 == 0 { "lorem ipsum lorem ipsum" } else { "" },
2017                "files": [], "references": if round % 2 == 0 { json!(["lorem ipsum ".repeat(30)]) } else { json!([]) }
2018            }))
2019            .unwrap();
2020            let pairs = [
2021                (1200, "owner/repo", 42),
2022                (900, "OWNER/REPO", 42),
2023                (700, "owner/repo", 43),
2024            ];
2025            let specs = pairs
2026                .iter()
2027                .map(|&(cutoff_ms, repo, number)| HistoryPairSpec {
2028                    cutoff_ms,
2029                    repo: repo.into(),
2030                    number,
2031                    sink: HistoryScanner::new(&item, &session),
2032                })
2033                .collect();
2034            let outputs = stream_pairs("session-é", &rows, specs);
2035            for (result, &(cutoff, repo, number)) in outputs.into_iter().zip(&pairs) {
2036                let spans = result.spans;
2037                let text = render_reference("session-é", &rows, cutoff, repo, number).unwrap();
2038                let expected = retrieve_reference(&item, &text, &session);
2039                retrieved += expected.len();
2040                assert_eq!(
2041                    spans_json(&spans),
2042                    spans_json(&expected),
2043                    "round {round} pair {cutoff} {number}"
2044                );
2045                assert_eq!(
2046                    stream_render("session-é", &rows, cutoff, repo, number),
2047                    text,
2048                    "round {round} text"
2049                );
2050                // Pushing the text in arbitrary pieces changes nothing.
2051                let mut scanner = HistoryScanner::new(&item, &session);
2052                let mut rest = text.as_str();
2053                while !rest.is_empty() {
2054                    let mut cut = (1 + rng.below(700)).min(rest.len());
2055                    while !rest.is_char_boundary(cut) {
2056                        cut += 1;
2057                    }
2058                    scanner.push_str(&rest[..cut]);
2059                    rest = &rest[cut..];
2060                }
2061                assert_eq!(
2062                    spans_json(&finish_whole(scanner, &text)),
2063                    spans_json(&expected),
2064                    "round {round} pieces"
2065                );
2066            }
2067        }
2068        assert!(
2069            retrieved > 100,
2070            "the generator must produce retrievals; got {retrieved}"
2071        );
2072    }
2073
2074    // Hard-won: #1505: JSON float exponents and notation differed from Python tool rendering.
2075    #[test]
2076    fn github_history_python_tool_numbers() {
2077        let fixture: Value = serde_json::from_str(include_str!(
2078            "../tests/fixtures/github-history/tool-numbers.json"
2079        ))
2080        .unwrap();
2081        let row = HistoryRow {
2082            stable_id: "tool".into(),
2083            position: 1,
2084            created_at_ms: 1000,
2085            last_changed_at_ms: 1000,
2086            body: fixture["body"].clone(),
2087        };
2088        assert_eq!(
2089            stream_render("floats", &[row], 2000, "owner/repo", 42),
2090            fixture["expected"].as_str().unwrap()
2091        );
2092    }
2093    // Hard-won: #1505: Rust word/digit categories differ from the training Python interpreter.
2094    #[test]
2095    fn github_history_python_unicode_boundaries() {
2096        let f: Value = serde_json::from_str(include_str!(
2097            "../tests/fixtures/github-history/unicode-adversarial.json"
2098        ))
2099        .unwrap();
2100        assert_eq!(
2101            serde_json::to_string(&identifiers(&f["item"])).unwrap(),
2102            f["identifiers"].to_string()
2103        );
2104        let raw = retrieve(&f["item"], f["transcript"].as_str().unwrap(), &f["session"]);
2105        assert_eq!(
2106            serde_json::to_string(&raw.iter().map(|s| &s.snippet).collect::<Vec<_>>()).unwrap(),
2107            f["snippets"].to_string()
2108        );
2109    }
2110}