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#[derive(Debug)]
866pub struct HistoryEvidence {
867    pub evidence: Value,
868    pub history_tokens: usize,
869    pub total_tokens: usize,
870    pub base_tokens: usize,
871    pub original_snippets: usize,
872    pub retained: Vec<Span>,
873    pub removed: Vec<(usize, &'static str)>,
874    pub over_limit: bool,
875}
876/// Base evidence is already bounded/redacted exactly once; this only budgets history.
877#[cfg(any(test, feature = "github-history"))]
878pub fn evidence(original_item: &Value, text: &str, base: &Value) -> Result<HistoryEvidence> {
879    evidence_from_spans(base, retrieve(original_item, text, &base["session"]))
880}
881/// Budgets already retrieved spans into `base`; the transcript is used only through them.
882#[cfg(any(test, feature = "github-history"))]
883pub fn evidence_from_spans(base: &Value, mut work: Vec<Span>) -> Result<HistoryEvidence> {
884    let tokenizer = mj_core::github_item::history_tokenizer()?;
885    let count = |a: &str, b: Option<&str>, special| -> Result<usize> {
886        let input = match b {
887            Some(b) => tokenizers_input(a, b),
888            None => a.into(),
889        };
890        Ok(tokenizer
891            .encode(input, special)
892            .map_err(|e| anyhow::anyhow!("{e}"))?
893            .len())
894    };
895    let original_snippets = work.len();
896    for s in &mut work {
897        s.snippet.time = s.snippet.time.as_deref().map(redact);
898    }
899    let mut session = indexmap::IndexMap::new();
900    let source = base["session"]
901        .as_object()
902        .ok_or_else(|| anyhow::anyhow!("session must be object"))?;
903    for k in ["conversation", "files", "references", "mentions"] {
904        if let Some(v) = source.get(k) {
905            session.insert(k.into(), v.clone());
906        }
907    }
908    let mut extra = source
909        .keys()
910        .filter(|k| !session.contains_key(*k) && *k != "history")
911        .collect::<Vec<_>>();
912    extra.sort();
913    for k in extra {
914        session.insert(k.clone(), source[k].clone());
915    }
916    let item = base["item"].to_string();
917    let base_tokens = count(
918        &item,
919        Some(&Value::Object(session.clone()).to_string()),
920        true,
921    )?;
922    let mut removed = Vec::new();
923    loop {
924        let history = serde_json::from_str::<Value>(&serde_json::to_string(
925            &work.iter().map(|s| &s.snippet).collect::<Vec<_>>(),
926        )?)?;
927        let ht = count(&history.to_string(), None, false)?;
928        session.insert("history".into(), history);
929        let total = count(
930            &item,
931            Some(&Value::Object(session.clone()).to_string()),
932            true,
933        )?;
934        if work.is_empty() || (ht <= 800 && total <= 7999) {
935            return Ok(HistoryEvidence {
936                evidence: Value::Object(indexmap::IndexMap::from([
937                    ("item".into(), base["item"].clone()),
938                    ("session".into(), Value::Object(session)),
939                ])),
940                history_tokens: ht,
941                total_tokens: total,
942                base_tokens,
943                original_snippets,
944                retained: work,
945                removed,
946                over_limit: total > 7999,
947            });
948        }
949        let worst = (0..work.len())
950            .min_by(|&a, &b| {
951                work[a]
952                    .score
953                    .total_cmp(&work[b].score)
954                    .then(work[a].start.cmp(&work[b].start))
955            })
956            .unwrap();
957        removed.push((
958            work[worst].start,
959            if ht > 800 {
960                "history_budget"
961            } else {
962                "input_capacity"
963            },
964        ));
965        work.remove(worst);
966    }
967}
968#[cfg(any(test, feature = "github-history"))]
969fn tokenizers_input<'a>(a: &'a str, b: &'a str) -> tokenizers::EncodeInput<'a> {
970    (a, b).into()
971}
972
973/// Counts that the transcript header reports; they fix the header's length and
974/// so every code point position after it.
975#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
976pub struct HistoryCounts {
977    pub included: usize,
978    pub changed: usize,
979    pub later: usize,
980    pub notices: usize,
981}
982
983/// What the first pass needs from each row. SQLite's `json_extract` yields
984/// these cheaply, without decoding the whole body.
985pub struct RowMeta<'a> {
986    pub created_at_ms: i64,
987    pub last_changed_at_ms: i64,
988    /// `body.kind`, empty unless a string.
989    pub kind: &'a str,
990    /// `body.event.body.type`, empty unless a string.
991    pub event_type: &'a str,
992    /// `body.event.body.number` when an unsigned integer.
993    pub event_number: Option<u64>,
994    /// `body.event.body.repo` when a string.
995    pub event_repo: Option<&'a str>,
996}
997
998fn kind_renders(kind: &str) -> bool {
999    matches!(kind, "user" | "agent" | "tool" | "message")
1000}
1001
1002fn is_notice_type(event_type: &str) -> bool {
1003    event_type == "new_github_item" || event_type.starts_with("github_")
1004}
1005
1006/// Whether a notice of a notice type names this pair's item.
1007fn notice_names_item(
1008    number: Option<u64>,
1009    repo: Option<&str>,
1010    item_number: u64,
1011    item_repo_lower: &str,
1012) -> bool {
1013    number == Some(item_number) && repo.is_none_or(|r| r.to_lowercase() == item_repo_lower)
1014}
1015
1016fn timestamp(ms: i64) -> Result<String> {
1017    Ok(chrono::DateTime::from_timestamp_millis(ms)
1018        .ok_or_else(|| anyhow::anyhow!("timestamp out of range"))?
1019        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
1020}
1021
1022/// One decoded row, rendered once for every pair that includes it.
1023struct RowRender {
1024    /// None for kinds the transcript never shows.
1025    text: Option<String>,
1026    /// Set for message rows of a notice type: (number, repo) decide per pair.
1027    notice: Option<(Option<u64>, Option<String>)>,
1028    created: Result<String, ()>,
1029}
1030
1031fn render_row(created_at_ms: i64, b: &Value) -> RowRender {
1032    let s = |v: &Value| v.as_str().unwrap_or("").to_string();
1033    let mut notice = None;
1034    let text = match b["kind"].as_str().unwrap_or("") {
1035        "user" => Some(format!(
1036            "USER\n{}",
1037            b["content"]
1038                .as_array()
1039                .into_iter()
1040                .flatten()
1041                .filter(|x| x["type"] == "text")
1042                .map(|x| s(&x["text"]))
1043                .collect::<Vec<_>>()
1044                .join("\n")
1045        )),
1046        "agent" => Some(format!(
1047            "AGENT\n{}",
1048            b["chunks"]
1049                .as_array()
1050                .into_iter()
1051                .flatten()
1052                .filter(|x| x["content"]["type"] == "text")
1053                .map(|x| s(&x["content"]["text"]))
1054                .collect::<String>()
1055        )),
1056        "tool" => {
1057            let call = &b["call"];
1058            Some(format!(
1059                "TOOL {}\nTITLE: {}\nCALL: {}",
1060                call["kind"]
1061                    .as_str()
1062                    .filter(|x| !x.is_empty())
1063                    .unwrap_or("call")
1064                    .to_uppercase(),
1065                s(&call["title"]),
1066                call
1067            ))
1068        }
1069        "message" => {
1070            let body = &b["event"]["body"];
1071            let typ = body["type"].as_str().unwrap_or("");
1072            if typ == "new_github_item" || typ.starts_with("github_") {
1073                notice = Some((
1074                    body["number"].as_u64(),
1075                    body["repo"].as_str().map(str::to_string),
1076                ));
1077            }
1078            Some(format!(
1079                "PEER MESSAGE {}\n{}",
1080                s(&body["from"]["title"]),
1081                s(&body["text"])
1082            ))
1083        }
1084        _ => None,
1085    };
1086    RowRender {
1087        text,
1088        notice,
1089        created: timestamp(created_at_ms).map_err(|_| ()),
1090    }
1091}
1092
1093/// `\r\n` and lone `\r` become `\n` across piece boundaries.
1094#[derive(Default)]
1095struct LineEndings {
1096    after_cr: bool,
1097}
1098impl LineEndings {
1099    fn push(&mut self, mut s: &str, sink: &mut impl TextSink) {
1100        if self.after_cr && !s.is_empty() {
1101            self.after_cr = false;
1102            s = s.strip_prefix('\n').unwrap_or(s);
1103        }
1104        while !sink.is_full()
1105            && let Some(i) = s.find('\r')
1106        {
1107            sink.push_str(&s[..i]);
1108            sink.push_str("\n");
1109            s = &s[i + 1..];
1110            match s.strip_prefix('\n') {
1111                Some(rest) => s = rest,
1112                None if s.is_empty() => self.after_cr = true,
1113                None => {}
1114            }
1115        }
1116        if !sink.is_full() {
1117            sink.push_str(s);
1118        }
1119    }
1120}
1121
1122/// Copies a pair's header while it is emitted.
1123struct Tee<'a, S> {
1124    sink: &'a mut S,
1125    copy: &'a mut String,
1126}
1127impl<S: TextSink> TextSink for Tee<'_, S> {
1128    fn push_str(&mut self, text: &str) {
1129        self.copy.push_str(text);
1130        self.sink.push_str(text);
1131    }
1132}
1133
1134struct PairRender<S> {
1135    cutoff_ms: i64,
1136    repo_lower: String,
1137    number: u64,
1138    expected: HistoryCounts,
1139    seen: HistoryCounts,
1140    endings: LineEndings,
1141    sink: S,
1142    /// The header as emitted.
1143    header: String,
1144}
1145
1146impl<S: TextSink> PairRender<S> {
1147    fn put(&mut self, s: &str) {
1148        self.endings.push(s, &mut self.sink);
1149    }
1150    fn put_header(&mut self, s: &str) {
1151        self.sink.mark(None);
1152        let mut tee = Tee {
1153            sink: &mut self.sink,
1154            copy: &mut self.header,
1155        };
1156        self.endings.push(s, &mut tee);
1157    }
1158    fn include(
1159        &mut self,
1160        row: &RowRender,
1161        ordinal: usize,
1162        created_at_ms: i64,
1163        changed_ms: i64,
1164    ) -> Result<()> {
1165        if created_at_ms > self.cutoff_ms || changed_ms > self.cutoff_ms {
1166            return Ok(());
1167        }
1168        let Some(text) = &row.text else {
1169            return Ok(());
1170        };
1171        if let Some((n, repo)) = &row.notice
1172            && notice_names_item(*n, repo.as_deref(), self.number, &self.repo_lower)
1173        {
1174            self.seen.notices += 1;
1175            return Ok(());
1176        }
1177        if self.seen.included > 0 {
1178            self.put("\n\n");
1179        }
1180        self.seen.included += 1;
1181        let ts = row
1182            .created
1183            .as_ref()
1184            .map_err(|()| anyhow::anyhow!("timestamp out of range"))?;
1185        self.sink.mark(Some(ordinal));
1186        self.put("[");
1187        self.put(ts);
1188        self.put("] ");
1189        self.put(text);
1190        Ok(())
1191    }
1192}
1193
1194/// Collects a range of code points and the stamp that starts at one position.
1195struct Slice {
1196    from: u64,
1197    to: u64,
1198    pos: u64,
1199    out: String,
1200    stamp_at: Option<u64>,
1201    /// 0 before the stamp, 1 inside it, 2 after its closing bracket.
1202    stamp_state: u8,
1203    stamp: String,
1204}
1205impl Slice {
1206    fn done(&self) -> bool {
1207        self.pos >= self.to && (self.stamp_at.is_none() || self.stamp_state == 2)
1208    }
1209}
1210impl TextSink for Slice {
1211    fn is_full(&self) -> bool {
1212        self.done()
1213    }
1214    fn push_str(&mut self, text: &str) {
1215        for c in text.chars() {
1216            if self.done() {
1217                return;
1218            }
1219            if (self.from..self.to).contains(&self.pos) {
1220                self.out.push(c);
1221            }
1222            if self.stamp_state == 1 {
1223                if c == ']' {
1224                    self.stamp_state = 2;
1225                } else {
1226                    self.stamp.push(c);
1227                }
1228            } else if self.stamp_state == 0 && self.stamp_at == Some(self.pos) {
1229                self.stamp_state = 1;
1230            }
1231            self.pos += 1;
1232        }
1233    }
1234}
1235
1236/// Gives back the stored rows the passes saw.
1237pub trait RowFetch {
1238    /// The body of the row the second pass was given under `key`.
1239    fn body(&mut self, key: i64) -> Result<String>;
1240}
1241
1242/// What the second pass knows about each row it was given, 24 bytes a row and
1243/// shared by every item: enough to tell which rows an item includes and to
1244/// fetch the ones a window needs.
1245#[derive(Clone, Copy)]
1246struct RowInfo {
1247    key: i64,
1248    created_at_ms: i64,
1249    last_changed_at_ms: i64,
1250}
1251
1252/// One item's cutoff and notice rule, kept to render rows again.
1253struct PairFilter {
1254    cutoff_ms: i64,
1255    repo_lower: String,
1256    number: u64,
1257    header: String,
1258}
1259
1260/// A window being rendered again.
1261struct Replay {
1262    pair: usize,
1263    window: usize,
1264    slice: Slice,
1265    endings: LineEndings,
1266    /// The ordinal to look from for the next row this item includes.
1267    next: usize,
1268    chunks: usize,
1269    /// Whether the header was already replayed, so the first row may be any included one.
1270    endings_started: bool,
1271    done: bool,
1272    /// Key of the stamp this replay collects, if it is the one to.
1273    stamp_key: (Option<usize>, u32, u32),
1274}
1275
1276/// One item's windows with their recovered text.
1277#[derive(Debug)]
1278pub struct HistoryResult<D> {
1279    pub done: D,
1280    pub spans: Vec<Span>,
1281}
1282
1283/// One item's transcript view of a session: its cutoff, the item it is about,
1284/// and where its rendered text goes.
1285pub struct HistoryPairSpec<S> {
1286    pub cutoff_ms: i64,
1287    pub repo: String,
1288    pub number: u64,
1289    pub sink: S,
1290}
1291
1292/// Renders one session's rows for several items at once. Rows are read twice,
1293/// in the same snapshot: `count_row` over all of them fixes each header, then
1294/// `row` over them in `(position, stable_id)` order renders each exactly once
1295/// and hands it to every pair that includes it. The rendered text is
1296/// byte-identical to the whole-string rendering of the frozen format; it is
1297/// never held whole. `complete` then renders again, once, only the rows around
1298/// the windows the sinks selected.
1299pub struct SessionHistory<S> {
1300    session_id: String,
1301    pairs: Vec<PairRender<S>>,
1302    started: bool,
1303    rows: Vec<RowInfo>,
1304    /// Rows that may be item-specific notices: ordinal to number and repository.
1305    notices: std::collections::HashMap<usize, (Option<u64>, Option<String>)>,
1306}
1307
1308impl<S: HistorySink> SessionHistory<S> {
1309    pub fn new(session_id: &str, pairs: Vec<HistoryPairSpec<S>>) -> Self {
1310        Self {
1311            session_id: session_id.to_string(),
1312            pairs: pairs
1313                .into_iter()
1314                .map(|p| PairRender {
1315                    cutoff_ms: p.cutoff_ms,
1316                    repo_lower: p.repo.to_lowercase(),
1317                    number: p.number,
1318                    expected: HistoryCounts::default(),
1319                    seen: HistoryCounts::default(),
1320                    endings: LineEndings::default(),
1321                    sink: p.sink,
1322                    header: String::new(),
1323                })
1324                .collect(),
1325            started: false,
1326            rows: Vec::new(),
1327            notices: Default::default(),
1328        }
1329    }
1330
1331    /// The latest cutoff of any pair. A row created or changed after it is
1332    /// withheld from every pair, so it only needs counting.
1333    pub fn max_cutoff_ms(&self) -> Option<i64> {
1334        self.pairs.iter().map(|p| p.cutoff_ms).max()
1335    }
1336
1337    /// First pass.
1338    pub fn count_row(&mut self, row: &RowMeta<'_>) {
1339        for pair in &mut self.pairs {
1340            let counts = &mut pair.expected;
1341            if row.created_at_ms > pair.cutoff_ms {
1342                counts.later += 1;
1343            } else if row.last_changed_at_ms > pair.cutoff_ms {
1344                counts.changed += 1;
1345            } else if row.kind == "message" {
1346                if is_notice_type(row.event_type)
1347                    && notice_names_item(
1348                        row.event_number,
1349                        row.event_repo,
1350                        pair.number,
1351                        &pair.repo_lower,
1352                    )
1353                {
1354                    counts.notices += 1;
1355                } else {
1356                    counts.included += 1;
1357                }
1358            } else if kind_renders(row.kind) {
1359                counts.included += 1;
1360            }
1361        }
1362    }
1363
1364    /// Writes every header; call once between the passes.
1365    pub fn begin(&mut self) -> Result<()> {
1366        for pair in &mut self.pairs {
1367            let c = pair.expected;
1368            let header = format!(
1369                "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",
1370                timestamp(pair.cutoff_ms)?,
1371                self.session_id,
1372                c.included,
1373                c.changed,
1374                c.later,
1375                c.notices
1376            );
1377            pair.put_header(&header);
1378        }
1379        self.started = true;
1380        Ok(())
1381    }
1382
1383    /// Second pass, over the rows in order. `key` is how `RowFetch` finds the
1384    /// row again. Rows nobody includes are not decoded; rows of a kind that
1385    /// never renders may be left out.
1386    pub fn row(
1387        &mut self,
1388        key: i64,
1389        created_at_ms: i64,
1390        last_changed_at_ms: i64,
1391        body_json: &str,
1392    ) -> Result<()> {
1393        anyhow::ensure!(self.started, "history rows rendered before the headers");
1394        let info = RowInfo {
1395            key,
1396            created_at_ms,
1397            last_changed_at_ms,
1398        };
1399        if !self
1400            .pairs
1401            .iter()
1402            .any(|p| created_at_ms <= p.cutoff_ms && last_changed_at_ms <= p.cutoff_ms)
1403        {
1404            self.rows.push(info);
1405            return Ok(());
1406        }
1407        let body: Value = serde_json::from_str(body_json)?;
1408        let rendered = render_row(created_at_ms, &body);
1409        drop(body);
1410        if rendered.text.is_none() {
1411            return Ok(());
1412        }
1413        let ordinal = self.rows.len();
1414        self.rows.push(info);
1415        if let Some(notice) = &rendered.notice {
1416            self.notices.insert(ordinal, notice.clone());
1417        }
1418        for pair in &mut self.pairs {
1419            pair.include(&rendered, ordinal, created_at_ms, last_changed_at_ms)?;
1420        }
1421        Ok(())
1422    }
1423
1424    /// Ends every transcript, lets each sink select its windows, and renders
1425    /// the rows around the selected windows again, once for all of them, with
1426    /// `fetch` reading the same rows as the passes did. Fails when the second
1427    /// pass disagrees with the counts in the headers, which means the rows
1428    /// changed between the passes or the counting query drifted from the
1429    /// renderer. `check` is called often; an error from it ends the work.
1430    pub fn complete(
1431        self,
1432        fetch: &mut dyn RowFetch,
1433        check: &dyn Fn() -> Result<()>,
1434    ) -> Result<Vec<HistoryResult<S::Done>>> {
1435        let Self {
1436            pairs,
1437            rows,
1438            notices,
1439            ..
1440        } = self;
1441        let mut filters = Vec::new();
1442        let mut dones = Vec::new();
1443        let mut selections = Vec::new();
1444        for mut pair in pairs {
1445            check()?;
1446            anyhow::ensure!(
1447                pair.seen.included == pair.expected.included
1448                    && pair.seen.notices == pair.expected.notices,
1449                "history header counts {:?} disagree with the rendered rows {:?}",
1450                pair.expected,
1451                pair.seen
1452            );
1453            pair.put("\n");
1454            filters.push(PairFilter {
1455                cutoff_ms: pair.cutoff_ms,
1456                repo_lower: pair.repo_lower,
1457                number: pair.number,
1458                header: pair.header,
1459            });
1460            let (done, selected) = pair.sink.select(check)?;
1461            dones.push(done);
1462            selections.push(selected);
1463        }
1464        let included = |pair: &PairFilter, ordinal: usize| {
1465            let row = &rows[ordinal];
1466            row.created_at_ms <= pair.cutoff_ms
1467                && row.last_changed_at_ms <= pair.cutoff_ms
1468                && !notices.get(&ordinal).is_some_and(|(n, repo)| {
1469                    notice_names_item(*n, repo.as_deref(), pair.number, &pair.repo_lower)
1470                })
1471        };
1472        // One replay per window; windows with the same stamp share one collector.
1473        let mut replays = Vec::new();
1474        let mut collectors = std::collections::HashSet::new();
1475        for (p, selected) in selections.iter().enumerate() {
1476            for (w, s) in selected.iter().enumerate() {
1477                let header = s.ordinal == HEADER;
1478                let segment = s.start - s.offset as usize;
1479                let stamp_at = match s.stamp {
1480                    Some(at) => Some(at.checked_sub(segment).ok_or_else(|| {
1481                        anyhow::anyhow!("a window's stamp lies before its part of the transcript")
1482                    })? as u64),
1483                    None => None,
1484                };
1485                let key = (
1486                    header.then_some(p),
1487                    s.ordinal,
1488                    stamp_at.map_or(u32::MAX, |at| at as u32),
1489                );
1490                let collect = stamp_at.is_some() && collectors.insert(key);
1491                let mut replay = Replay {
1492                    pair: p,
1493                    window: w,
1494                    slice: Slice {
1495                        from: s.offset as u64,
1496                        to: (s.offset as usize + s.end - s.start) as u64,
1497                        pos: 0,
1498                        out: String::new(),
1499                        stamp_at: if collect { stamp_at } else { None },
1500                        stamp_state: 0,
1501                        stamp: String::new(),
1502                    },
1503                    endings: LineEndings::default(),
1504                    next: if header { 0 } else { s.ordinal as usize },
1505                    chunks: 0,
1506                    endings_started: header,
1507                    done: false,
1508                    stamp_key: key,
1509                };
1510                if header {
1511                    replay.endings.push(&filters[p].header, &mut replay.slice);
1512                }
1513                replays.push(replay);
1514            }
1515        }
1516        loop {
1517            check()?;
1518            let mut target: Option<usize> = None;
1519            for replay in replays.iter_mut().filter(|r| !r.done) {
1520                if replay.slice.done() {
1521                    replay.done = true;
1522                    continue;
1523                }
1524                let filter = &filters[replay.pair];
1525                let anchor = replay.next;
1526                while replay.next < rows.len() && !included(filter, replay.next) {
1527                    replay.next += 1;
1528                }
1529                anyhow::ensure!(
1530                    replay.chunks > 0
1531                        || replay.endings_started
1532                        || replay.next == anchor
1533                        || replay.next >= rows.len(),
1534                    "a window's row is not one its item includes"
1535                );
1536                if replay.next < rows.len() {
1537                    target = Some(target.map_or(replay.next, |t| t.min(replay.next)));
1538                } else {
1539                    // No more rows: the transcript ends with a newline.
1540                    replay.endings.push("\n", &mut replay.slice);
1541                    replay.done = true;
1542                }
1543            }
1544            let Some(target) = target else { break };
1545            let body = fetch.body(rows[target].key)?;
1546            let rendered = render_row(
1547                rows[target].created_at_ms,
1548                &serde_json::from_str::<Value>(&body)?,
1549            );
1550            drop(body);
1551            let text = rendered
1552                .text
1553                .as_ref()
1554                .ok_or_else(|| anyhow::anyhow!("history row {target} no longer renders"))?;
1555            let ts = rendered
1556                .created
1557                .as_ref()
1558                .map_err(|()| anyhow::anyhow!("timestamp out of range"))?;
1559            for replay in replays.iter_mut().filter(|r| !r.done && r.next == target) {
1560                if replay.chunks > 0 {
1561                    replay.endings.push("\n\n", &mut replay.slice);
1562                }
1563                for piece in ["[", ts, "] ", text] {
1564                    if replay.slice.done() {
1565                        break;
1566                    }
1567                    replay.endings.push(piece, &mut replay.slice);
1568                }
1569                replay.chunks += 1;
1570                replay.next += 1;
1571            }
1572        }
1573        let mut stamps = std::collections::HashMap::new();
1574        for replay in &mut replays {
1575            anyhow::ensure!(
1576                replay.slice.pos >= replay.slice.to
1577                    && (replay.slice.stamp_at.is_none() || replay.slice.stamp_state == 2),
1578                "history rows changed between reading them and recovering a window"
1579            );
1580            if replay.slice.stamp_at.is_some() {
1581                stamps.insert(replay.stamp_key, std::mem::take(&mut replay.slice.stamp));
1582            }
1583        }
1584        let mut results = dones
1585            .into_iter()
1586            .map(|done| HistoryResult {
1587                done,
1588                spans: Vec::new(),
1589            })
1590            .collect::<Vec<_>>();
1591        for replay in replays {
1592            let s = &selections[replay.pair][replay.window];
1593            let time = s.stamp.map(|_| stamps[&replay.stamp_key].clone());
1594            results[replay.pair].spans.push(Span {
1595                start: s.start,
1596                end: s.end,
1597                score: s.score,
1598                snippet: Snippet {
1599                    time,
1600                    text: redact(replay.slice.out.trim_matches(|c| u::contains(u::SPACE, c))),
1601                },
1602            });
1603        }
1604        Ok(results)
1605    }
1606}
1607
1608/// A scanner for one item against one session. `base` must already be bounded
1609/// and redacted once; the original item's full body is used only for retrieval.
1610/// None when the item has no searchable identifiers, which gives empty history.
1611pub fn history_scanner(
1612    original: &mj_core::github_item::GithubItem,
1613    base: &mj_core::github_item::GithubItemEvidence,
1614) -> Result<Option<HistoryScanner>> {
1615    let original: Value = serde_json::from_str(&serde_json::to_string(original)?)?;
1616    let base: Value = serde_json::from_str(&serde_json::to_string(base)?)?;
1617    // An item without searchable identifiers can never select a snippet.
1618    let ids = identifiers(&original);
1619    if ids.is_empty() {
1620        return Ok(None);
1621    }
1622    Ok(Some(HistoryScanner::with_identifiers(
1623        ids,
1624        &base["session"],
1625    )))
1626}
1627
1628/// Build classifier-ready evidence from the spans a scanner retrieved.
1629/// Diagnostics retain overflow rather than trimming base.
1630#[cfg(any(test, feature = "github-history"))]
1631pub fn build_evidence(
1632    base: &mj_core::github_item::GithubItemEvidence,
1633    spans: Vec<Span>,
1634) -> Result<(mj_core::github_item::GithubItemEvidence, HistoryEvidence)> {
1635    let base = serde_json::from_str(&serde_json::to_string(base)?)?;
1636    let result = evidence_from_spans(&base, spans)?;
1637    let typed = serde_json::from_str(&result.evidence.to_string())?;
1638    Ok((typed, result))
1639}
1640
1641/// Training-format segments, item first, with history last in the session.
1642/// Evidence is already bounded/redacted; serialization never bounds it again.
1643pub fn student_segments(
1644    evidence: &mj_core::github_item::GithubItemEvidence,
1645) -> Result<(String, String)> {
1646    Ok((
1647        serde_json::to_string(&evidence.item)?,
1648        serde_json::to_string(&evidence.session)?,
1649    ))
1650}
1651
1652#[cfg(test)]
1653mod tests {
1654    use super::*;
1655    use std::collections::{BTreeMap, HashSet};
1656    fn slice(s: &[char], a: usize, b: usize) -> String {
1657        s[a..b].iter().collect()
1658    }
1659    // The implementation that streaming replaced, kept only as the oracle for
1660    // the differential test: whole-text retrieval over `Vec<char>` and the
1661    // whole-string renderer.
1662    /// Original title/body must be supplied, independently of the bounded classifier item.
1663    fn retrieve_reference(item: &Value, text: &str, session: &Value) -> Vec<Span> {
1664        let t = chars(text);
1665        let byte_positions = text
1666            .char_indices()
1667            .map(|(byte, _)| byte)
1668            .collect::<Vec<_>>();
1669        let digest = chars(&spaced(session));
1670        let known: HashSet<String> = (0..digest.len().saturating_sub(99))
1671            .map(|i| slice(&digest, i, i + 100))
1672            .collect();
1673        let existing = session["conversation"].as_str().unwrap_or("");
1674        let mut candidates: BTreeMap<usize, (f64, usize, HashSet<String>)> = BTreeMap::new();
1675        for (id, base) in identifiers(item) {
1676            let numeric = id.chars().all(|c| u::contains(u::ISDIGIT, c));
1677            let mut hits = Vec::new();
1678            let mut offset = 0;
1679            while let Some(p) = text[offset..].find(&id) {
1680                let b = offset + p;
1681                let pos = byte_positions.partition_point(|&byte| byte < b);
1682                let end = pos + id.chars().count();
1683                offset = b + id.len();
1684                let ok = if numeric {
1685                    (pos == 0 || !u::contains(u::ISDIGIT, t[pos - 1]))
1686                        && (end == t.len() || !u::contains(u::ISDIGIT, t[end]))
1687                } else {
1688                    (pos == 0 || !(u::contains(u::ISALNUM, t[pos - 1]) || t[pos - 1] == '_'))
1689                        && (end == t.len() || !u::contains(u::ISALNUM, t[end]))
1690                };
1691                if ok {
1692                    hits.push(pos);
1693                }
1694            }
1695            // `f64::ln_1p` calls the platform's C library, whose log1p is not
1696            // correctly rounded: glibc, Apple's libm and MSVC each differ by an
1697            // ulp on some inputs, which broke byte parity on Windows. The pure
1698            // Rust fdlibm port gives the same bits on every platform and
1699            // reproduces every reference fixture.
1700            let weight = base
1701                * (1.0 + libm::log1p((t.len() as f64 / 500.0).max(1.0) / (1 + hits.len()) as f64));
1702            for pos in hits {
1703                let start = (pos / 250 * 250).saturating_sub(125);
1704                let c = candidates.entry(start).or_insert((
1705                    0.0,
1706                    (start + 500).min(t.len()),
1707                    HashSet::new(),
1708                ));
1709                if c.2.insert(id.clone()) {
1710                    c.0 += weight;
1711                }
1712            }
1713        }
1714        let stamps = re(r"(?m)^\[([^\]\n]+)\]")
1715            .captures_iter(text)
1716            .map(|m| {
1717                (
1718                    byte_positions.partition_point(|&byte| byte < m.get(0).unwrap().start()),
1719                    m[1].to_string(),
1720                )
1721            })
1722            .collect::<Vec<_>>();
1723        let mut ranked = Vec::new();
1724        for (start, (score, end, _)) in candidates {
1725            let raw = slice(&t, start, end);
1726            let raw = raw.trim_matches(|c| u::contains(u::SPACE, c));
1727            let rt = redact(raw);
1728            let r = chars(&rt);
1729            if existing.contains(&rt)
1730                || (0..r.len().saturating_sub(99))
1731                    .step_by(50)
1732                    .any(|i| known.contains(&slice(&r, i, i + 100)))
1733            {
1734                continue;
1735            }
1736            let score = score * (1.0 + 0.1 * start as f64 / t.len().max(1) as f64);
1737            let time = stamps
1738                .iter()
1739                .rev()
1740                .find(|(p, _)| *p <= start)
1741                .map(|(_, s)| s.clone());
1742            ranked.push((
1743                Span {
1744                    start,
1745                    end,
1746                    score,
1747                    snippet: Snippet { time, text: rt },
1748                },
1749                raw.chars().count(),
1750            ));
1751        }
1752        ranked.sort_by(|a, b| {
1753            b.0.score
1754                .total_cmp(&a.0.score)
1755                .then(b.0.start.cmp(&a.0.start))
1756        });
1757        let mut selected: Vec<Span> = Vec::new();
1758        let mut used = 0;
1759        for (span, len) in ranked {
1760            if used + len > 2100
1761                || selected
1762                    .iter()
1763                    .any(|s| span.start < s.end && span.end > s.start)
1764            {
1765                continue;
1766            }
1767            used += len;
1768            selected.push(span);
1769        }
1770        selected.sort_by_key(|s| s.start);
1771        selected
1772    }
1773    /// Raw persisted rows retain tool-call JSON order and unknown row kinds for cutoff counts.
1774    #[derive(Clone, Debug, Deserialize)]
1775    struct HistoryRow {
1776        pub stable_id: String,
1777        pub position: i64,
1778        pub created_at_ms: i64,
1779        pub last_changed_at_ms: i64,
1780        pub body: Value,
1781    }
1782    /// Render one shared snapshot at the item's creation time; never use edited later bodies.
1783    fn render_reference(
1784        session_id: &str,
1785        rows: &[HistoryRow],
1786        cutoff_ms: i64,
1787        repo: &str,
1788        number: u64,
1789    ) -> Result<String> {
1790        let mut ordered = rows.iter().collect::<Vec<_>>();
1791        ordered.sort_by(|a, b| {
1792            a.position
1793                .cmp(&b.position)
1794                .then(a.stable_id.cmp(&b.stable_id))
1795        });
1796        let (mut changed, mut later, mut notices) = (0, 0, 0);
1797        let mut chunks = Vec::new();
1798        for row in ordered {
1799            if row.created_at_ms > cutoff_ms {
1800                later += 1;
1801                continue;
1802            }
1803            if row.last_changed_at_ms > cutoff_ms {
1804                changed += 1;
1805                continue;
1806            }
1807            let b = &row.body;
1808            let s = |v: &Value| v.as_str().unwrap_or("").to_string();
1809            let rendered = match b["kind"].as_str().unwrap_or("") {
1810                "user" => Some(format!(
1811                    "USER\n{}",
1812                    b["content"]
1813                        .as_array()
1814                        .into_iter()
1815                        .flatten()
1816                        .filter(|x| x["type"] == "text")
1817                        .map(|x| s(&x["text"]))
1818                        .collect::<Vec<_>>()
1819                        .join("\n")
1820                )),
1821                "agent" => Some(format!(
1822                    "AGENT\n{}",
1823                    b["chunks"]
1824                        .as_array()
1825                        .into_iter()
1826                        .flatten()
1827                        .filter(|x| x["content"]["type"] == "text")
1828                        .map(|x| s(&x["content"]["text"]))
1829                        .collect::<String>()
1830                )),
1831                "tool" => {
1832                    let call = &b["call"];
1833                    Some(format!(
1834                        "TOOL {}\nTITLE: {}\nCALL: {}",
1835                        call["kind"]
1836                            .as_str()
1837                            .filter(|x| !x.is_empty())
1838                            .unwrap_or("call")
1839                            .to_uppercase(),
1840                        s(&call["title"]),
1841                        call
1842                    ))
1843                }
1844                "message" => {
1845                    let body = &b["event"]["body"];
1846                    let typ = body["type"].as_str().unwrap_or("");
1847                    if (typ == "new_github_item" || typ.starts_with("github_"))
1848                        && body["number"].as_u64() == Some(number)
1849                        && body["repo"]
1850                            .as_str()
1851                            .is_none_or(|r| r.to_lowercase() == repo.to_lowercase())
1852                    {
1853                        notices += 1;
1854                        continue;
1855                    }
1856                    Some(format!(
1857                        "PEER MESSAGE {}\n{}",
1858                        s(&body["from"]["title"]),
1859                        s(&body["text"])
1860                    ))
1861                }
1862                _ => None,
1863            };
1864            if let Some(text) = rendered {
1865                chunks.push(format!("[{}] {}", timestamp(row.created_at_ms)?, text));
1866            }
1867        }
1868        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"))
1869    }
1870
1871    /// Runs both passes of the streaming renderer over rows held in memory,
1872    /// the way the store feeds them, into the given sinks.
1873    struct MemoryRows(Vec<String>);
1874    impl RowFetch for MemoryRows {
1875        fn body(&mut self, key: i64) -> Result<String> {
1876            Ok(self.0[key as usize].clone())
1877        }
1878    }
1879    fn stream_pairs<S: HistorySink>(
1880        session_id: &str,
1881        rows: &[HistoryRow],
1882        pairs: Vec<HistoryPairSpec<S>>,
1883    ) -> Vec<HistoryResult<S::Done>> {
1884        let mut ordered = rows.iter().collect::<Vec<_>>();
1885        ordered.sort_by(|a, b| {
1886            a.position
1887                .cmp(&b.position)
1888                .then(a.stable_id.cmp(&b.stable_id))
1889        });
1890        let mut memory = MemoryRows(
1891            ordered
1892                .iter()
1893                .map(|r| serde_json::to_string(&r.body).unwrap())
1894                .collect(),
1895        );
1896        let mut history = SessionHistory::new(session_id, pairs);
1897        for row in &ordered {
1898            let b = &row.body;
1899            let event = &b["event"]["body"];
1900            history.count_row(&RowMeta {
1901                created_at_ms: row.created_at_ms,
1902                last_changed_at_ms: row.last_changed_at_ms,
1903                kind: b["kind"].as_str().unwrap_or(""),
1904                event_type: event["type"].as_str().unwrap_or(""),
1905                event_number: event["number"].as_u64(),
1906                event_repo: event["repo"].as_str(),
1907            });
1908        }
1909        history.begin().unwrap();
1910        for (n, row) in ordered.iter().enumerate() {
1911            history
1912                .row(
1913                    n as i64,
1914                    row.created_at_ms,
1915                    row.last_changed_at_ms,
1916                    &memory.0[n],
1917                )
1918                .unwrap();
1919        }
1920        history.complete(&mut memory, &|| Ok(())).unwrap()
1921    }
1922    fn stream_render(
1923        session_id: &str,
1924        rows: &[HistoryRow],
1925        cutoff_ms: i64,
1926        repo: &str,
1927        number: u64,
1928    ) -> String {
1929        stream_pairs(
1930            session_id,
1931            rows,
1932            vec![HistoryPairSpec {
1933                cutoff_ms,
1934                repo: repo.into(),
1935                number,
1936                sink: String::new(),
1937            }],
1938        )
1939        .pop()
1940        .unwrap()
1941        .done
1942    }
1943    struct Rng(u64);
1944    impl Rng {
1945        fn next(&mut self) -> u64 {
1946            self.0 ^= self.0 << 13;
1947            self.0 ^= self.0 >> 7;
1948            self.0 ^= self.0 << 17;
1949            self.0
1950        }
1951        fn below(&mut self, n: usize) -> usize {
1952            (self.next() % n as u64) as usize
1953        }
1954    }
1955    const PIECES: &[&str] = &[
1956        "#42",
1957        "#420",
1958        "x#42",
1959        "#42y",
1960        "#4",
1961        "42",
1962        "src/foo_bar.rs",
1963        "foo_bar.rs",
1964        "foo_bar",
1965        "foo_bar_baz_qux",
1966        "FooBar",
1967        "fooBar_x",
1968        "CAFÉ",
1969        "CAFE",
1970        "AB",
1971        "ABC",
1972        "ABCD",
1973        "é",
1974        "😀",
1975        "日本語",
1976        "²",
1977        "٣",
1978        "_",
1979        ".",
1980        "-",
1981        "/",
1982        " ",
1983        " ",
1984        " ",
1985        "word",
1986        "words",
1987        "\n",
1988        "\n",
1989        "\r\n",
1990        "\r",
1991        "\r\n\r\n",
1992        "\n[2024-01-01 10:00]\n",
1993        "\n[x",
1994        "]",
1995        "[]",
1996        "\n[a\nb]",
1997        "\u{a0}",
1998        "\t",
1999        "tokenaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2000        "https://example.com/src/foo_bar.rs",
2001        "the quick brown fox jumps over the lazy dog ",
2002    ];
2003    fn random_text(rng: &mut Rng, pieces: usize) -> String {
2004        let mut text = String::new();
2005        for _ in 0..pieces {
2006            text.push_str(PIECES[rng.below(PIECES.len())]);
2007            if rng.below(6) == 0 {
2008                text.push_str(&"lorem ipsum ".repeat(rng.below(60)));
2009            }
2010        }
2011        text
2012    }
2013    fn random_rows(rng: &mut Rng, count: usize) -> Vec<HistoryRow> {
2014        (0..count)
2015            .map(|n| {
2016                let text = if rng.below(40) == 0 {
2017                    // More than a pipe buffer in one row.
2018                    format!("{}{}", random_text(rng, 30), "padding ".repeat(9000))
2019                } else {
2020                    {
2021                        let pieces = 1 + rng.below(40);
2022                        random_text(rng, pieces)
2023                    }
2024                };
2025                let created = 500 + rng.below(1200) as i64;
2026                let changed = if rng.below(6) == 0 { created + rng.below(900) as i64 } else { created };
2027                let body = match rng.below(7) {
2028                    0 => json!({"kind": "user", "content": [{"type": "text", "text": text}, {"type": "image"}, {"type": "text", "text": "#42"}]}),
2029                    1 => json!({"kind": "agent", "chunks": [{"content": {"type": "text", "text": text}}, {"content": {"type": "text", "text": "src/foo_bar.rs"}}]}),
2030                    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"}}),
2031                    3 | 4 => {
2032                        let typ = ["github_issue", "new_github_item", "peer", "github_comment"][rng.below(4)];
2033                        let repo = [json!("Owner/Repo"), json!("other/repo"), json!(null), json!(7)][rng.below(4)].clone();
2034                        let number = [json!(42), json!(43), json!(42.0), json!("42")][rng.below(4)].clone();
2035                        json!({"kind": "message", "event": {"body": {"type": typ, "number": number, "repo": repo, "text": text, "from": {"title": "peer"}}}})
2036                    }
2037                    5 => json!({"kind": "thought", "text": text}),
2038                    _ => json!({"kind": 5, "x": text}),
2039                };
2040                HistoryRow {
2041                    stable_id: format!("row-{}", rng.below(count + 3)),
2042                    position: n as i64 / 2,
2043                    created_at_ms: created,
2044                    last_changed_at_ms: changed,
2045                    body: serde_json::from_value(body).unwrap(),
2046                }
2047            })
2048            .collect()
2049    }
2050    fn random_item(rng: &mut Rng) -> Value {
2051        let title = random_text(rng, 4);
2052        let body = format!(
2053            "{} #42 src/foo_bar.rs foo_bar_baz_qux FooBar CAFÉ ABC {}",
2054            random_text(rng, 8),
2055            random_text(rng, 8)
2056        );
2057        serde_json::from_value(json!({"title": title, "body": body})).unwrap()
2058    }
2059    fn spans_json(spans: &[Span]) -> String {
2060        spans
2061            .iter()
2062            .map(|s| {
2063                format!(
2064                    "{}:{}:{:016x}:{:?}:{:?}",
2065                    s.start,
2066                    s.end,
2067                    s.score.to_bits(),
2068                    s.snippet.time,
2069                    s.snippet.text
2070                )
2071            })
2072            .collect::<Vec<_>>()
2073            .join("\n")
2074    }
2075
2076    fn finish_whole(scanner: HistoryScanner, text: &str) -> Vec<Span> {
2077        spans_from_whole_text(scanner.finish(&|| Ok(())).unwrap(), text)
2078    }
2079
2080    // An identifier in every window of a long transcript, with a megabyte-long
2081    // bracketed line that opens a stamp under hundreds of windows, must not make
2082    // the scanner keep a string per window.
2083    #[test]
2084    fn scanner_holds_a_constant_number_of_window_strings() {
2085        let item: Value =
2086            serde_json::from_value(json!({"title": "t", "body": "src/zz_marker.rs"})).unwrap();
2087        let session: Value = serde_json::from_value(json!({"conversation": ""})).unwrap();
2088        let mut text = String::from("[2024-01-01T00:00:00.000Z] USER\n");
2089        for _ in 0..4000 {
2090            text.push_str("src/zz_marker.rs lorem ipsum dolor sit amet ééé 😀 consectetur\n");
2091        }
2092        text.push_str("\n[");
2093        for _ in 0..40_000 {
2094            text.push_str("src/zz_marker.rs padding padding padding ");
2095        }
2096        text.push_str("]\n");
2097        for _ in 0..4000 {
2098            text.push_str("lorem src/zz_marker.rs ipsum dolor sit amet\n");
2099        }
2100        assert!(text.len() > 1_000_000);
2101        let mut scanner = HistoryScanner::new(&item, &session);
2102        let mut rest = text.as_str();
2103        while !rest.is_empty() {
2104            let mut cut = 4096.min(rest.len());
2105            while !rest.is_char_boundary(cut) {
2106                cut += 1;
2107            }
2108            scanner.push_str(&rest[..cut]);
2109            rest = &rest[cut..];
2110        }
2111        assert!(scanner.live.len() > 8000, "{}", scanner.live.len());
2112        assert_eq!(std::mem::size_of::<Candidate>(), 24);
2113        assert_eq!(std::mem::size_of::<RowInfo>(), 24);
2114        assert!(scanner.peak_texts <= 3, "peak {}", scanner.peak_texts);
2115        assert!(scanner.open.len() <= 3);
2116        let expected = retrieve_reference(&item, &text, &session);
2117        assert!(!expected.is_empty());
2118        assert_eq!(
2119            spans_json(&finish_whole(scanner, &text)),
2120            spans_json(&expected)
2121        );
2122    }
2123
2124    // Streaming must reproduce the whole-text implementation exactly: header
2125    // counts, line-ending replacement, notices, rows that changed after the
2126    // cutoff, multi-byte text, identifiers across the window grid and the row
2127    // boundaries, bracket lines, and rows larger than a pipe buffer.
2128    #[test]
2129    fn streaming_history_matches_the_whole_text_reference() {
2130        let mut rng = Rng(0x9e3779b97f4a7c15);
2131        let mut retrieved = 0;
2132        for round in 0..30 {
2133            let count = 1 + rng.below(40);
2134            let rows = random_rows(&mut rng, count);
2135            let item = random_item(&mut rng);
2136            let session: Value = serde_json::from_value(json!({
2137                "conversation": if round % 3 == 0 { "lorem ipsum lorem ipsum" } else { "" },
2138                "files": [], "references": if round % 2 == 0 { json!(["lorem ipsum ".repeat(30)]) } else { json!([]) }
2139            }))
2140            .unwrap();
2141            let pairs = [
2142                (1200, "owner/repo", 42),
2143                (900, "OWNER/REPO", 42),
2144                (700, "owner/repo", 43),
2145            ];
2146            let specs = pairs
2147                .iter()
2148                .map(|&(cutoff_ms, repo, number)| HistoryPairSpec {
2149                    cutoff_ms,
2150                    repo: repo.into(),
2151                    number,
2152                    sink: HistoryScanner::new(&item, &session),
2153                })
2154                .collect();
2155            let outputs = stream_pairs("session-é", &rows, specs);
2156            for (result, &(cutoff, repo, number)) in outputs.into_iter().zip(&pairs) {
2157                let spans = result.spans;
2158                let text = render_reference("session-é", &rows, cutoff, repo, number).unwrap();
2159                let expected = retrieve_reference(&item, &text, &session);
2160                retrieved += expected.len();
2161                assert_eq!(
2162                    spans_json(&spans),
2163                    spans_json(&expected),
2164                    "round {round} pair {cutoff} {number}"
2165                );
2166                assert_eq!(
2167                    stream_render("session-é", &rows, cutoff, repo, number),
2168                    text,
2169                    "round {round} text"
2170                );
2171                // Pushing the text in arbitrary pieces changes nothing.
2172                let mut scanner = HistoryScanner::new(&item, &session);
2173                let mut rest = text.as_str();
2174                while !rest.is_empty() {
2175                    let mut cut = (1 + rng.below(700)).min(rest.len());
2176                    while !rest.is_char_boundary(cut) {
2177                        cut += 1;
2178                    }
2179                    scanner.push_str(&rest[..cut]);
2180                    rest = &rest[cut..];
2181                }
2182                assert_eq!(
2183                    spans_json(&finish_whole(scanner, &text)),
2184                    spans_json(&expected),
2185                    "round {round} pieces"
2186                );
2187            }
2188        }
2189        assert!(
2190            retrieved > 100,
2191            "the generator must produce retrievals; got {retrieved}"
2192        );
2193    }
2194
2195    // Hard-won: #1505: JSON float exponents and notation differed from Python tool rendering.
2196    #[test]
2197    fn github_history_python_tool_numbers() {
2198        let fixture: Value = serde_json::from_str(include_str!(
2199            "../tests/fixtures/github-history/tool-numbers.json"
2200        ))
2201        .unwrap();
2202        let row = HistoryRow {
2203            stable_id: "tool".into(),
2204            position: 1,
2205            created_at_ms: 1000,
2206            last_changed_at_ms: 1000,
2207            body: fixture["body"].clone(),
2208        };
2209        assert_eq!(
2210            stream_render("floats", &[row], 2000, "owner/repo", 42),
2211            fixture["expected"].as_str().unwrap()
2212        );
2213    }
2214    // Hard-won: #1505: Rust word/digit categories differ from the training Python interpreter.
2215    #[test]
2216    fn github_history_python_unicode_boundaries() {
2217        let f: Value = serde_json::from_str(include_str!(
2218            "../tests/fixtures/github-history/unicode-adversarial.json"
2219        ))
2220        .unwrap();
2221        assert_eq!(
2222            serde_json::to_string(&identifiers(&f["item"])).unwrap(),
2223            f["identifiers"].to_string()
2224        );
2225        let raw = retrieve(&f["item"], f["transcript"].as_str().unwrap(), &f["session"]);
2226        assert_eq!(
2227            serde_json::to_string(&raw.iter().map(|s| &s.snippet).collect::<Vec<_>>()).unwrap(),
2228            f["snippets"].to_string()
2229        );
2230    }
2231    #[test]
2232    fn github_history_python_format_fixtures() {
2233        for line in include_str!("../tests/fixtures/github-history/reference.jsonl").lines() {
2234            let f: Value = serde_json::from_str(line).unwrap();
2235            let id = &f["pid"];
2236            let raw = retrieve(
2237                &f["item"],
2238                f["transcript_text"].as_str().unwrap(),
2239                &f["bounded_evidence_without_history"]["session"],
2240            );
2241            assert_eq!(
2242                serde_json::to_string(&raw.iter().map(|s| &s.snippet).collect::<Vec<_>>()).unwrap(),
2243                f["expected_retrieved_json"].as_str().unwrap(),
2244                "lexical {id}"
2245            );
2246            let prepared: mj_core::github_item::GithubItemEvidence =
2247                serde_json::from_str(f["expected_evidence_json"].as_str().unwrap()).unwrap();
2248            let (item_segment, session_segment) = student_segments(&prepared).unwrap();
2249            assert_eq!(
2250                item_segment,
2251                f["expected_item_segment"].as_str().unwrap(),
2252                "item segment {id}"
2253            );
2254            assert_eq!(
2255                session_segment,
2256                f["expected_session_segment"].as_str().unwrap(),
2257                "session segment {id}"
2258            );
2259            for (span, expected) in raw.iter().zip(f["expected_raw_spans"].as_array().unwrap()) {
2260                assert_eq!(span.start as u64, expected["start"].as_u64().unwrap());
2261                assert_eq!(span.end as u64, expected["end"].as_u64().unwrap());
2262                assert_eq!(
2263                    format!("{:016x}", span.score.to_bits()),
2264                    expected["score_bits"].as_str().unwrap(),
2265                    "score {id}"
2266                );
2267            }
2268            let actual = evidence(
2269                &f["item"],
2270                f["transcript_text"].as_str().unwrap(),
2271                &f["bounded_evidence_without_history"],
2272            )
2273            .unwrap();
2274            assert_eq!(
2275                actual.evidence["session"]["history"].to_string(),
2276                f["expected_history_json"].as_str().unwrap(),
2277                "budget {id}"
2278            );
2279            assert_eq!(
2280                actual.evidence.to_string(),
2281                f["expected_evidence_json"].as_str().unwrap(),
2282                "evidence {id}"
2283            );
2284            assert_eq!(
2285                actual.history_tokens as u64,
2286                f["expected_stats"]["history_tokens"].as_u64().unwrap(),
2287                "tokens {id}"
2288            );
2289            assert_eq!(
2290                actual.total_tokens as u64,
2291                f["expected_stats"]["total_tokens"].as_u64().unwrap(),
2292                "pair tokens {id}"
2293            );
2294        }
2295    }
2296}