1use anyhow::Result;
3use mj_core::github_item::history_unicode as u;
4use regex::Regex;
5use serde::{Deserialize, Serialize};
6use serde_json::json;
7#[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}
85fn 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
142use std::collections::{BTreeMap, HashSet};
143
144fn re(s: &str) -> Regex {
145 Regex::new(s).expect("frozen expression")
146}
147fn chars(s: &str) -> Vec<char> {
148 s.chars().collect()
149}
150fn slice(s: &[char], a: usize, b: usize) -> String {
151 s[a..b].iter().collect()
152}
153pub fn redact(s: &str) -> String {
154 re(r"[A-Za-z0-9_.+\-]{24,}")
155 .replace_all(s, "[redacted]")
156 .into_owned()
157}
158fn spaced(v: &Value) -> String {
160 match v {
161 Value::Object(o) => format!(
162 "{{{}}}",
163 o.iter()
164 .map(|(k, v)| format!("{}: {}", json!(k), spaced(v)))
165 .collect::<Vec<_>>()
166 .join(", ")
167 ),
168 Value::Array(a) => format!("[{}]", a.iter().map(spaced).collect::<Vec<_>>().join(", ")),
169 _ => v.to_string(),
170 }
171}
172pub use mj_core::github_item::HistorySnippet as Snippet;
173#[derive(Clone, Debug)]
174pub struct Span {
175 pub start: usize,
176 pub end: usize,
177 pub score: f64,
178 pub snippet: Snippet,
179}
180fn identifiers(item: &Value) -> Vec<(String, f64)> {
181 let title = item["title"].as_str().unwrap_or("");
182 let text = format!("{}\n{}", title, item["body"].as_str().unwrap_or(""));
183 let word = u::class(u::WORD);
184 let decimal = u::class(u::DECIMAL);
185 let boundary = format!("(?:$|[^{w}])", w = &word[1..word.len() - 1]);
186 let mut ids = Vec::<(String, f64)>::new();
187 let mut put = |s: &str, w| {
188 if let Some(x) = ids.iter_mut().find(|x| x.0 == s) {
189 x.1 = w;
190 } else if !s.is_empty() {
191 ids.push((s.into(), w));
192 }
193 };
194 for m in re(&format!("#({decimal}+)")).captures_iter(&text) {
196 let end = m.get(0).unwrap().end();
197 if text[end..]
198 .chars()
199 .next()
200 .is_none_or(|c| !u::contains(u::WORD, c))
201 {
202 put(&m[1], 1.3);
203 }
204 }
205 for m in re(&format!(
206 r"[{w}.-]+(?:/[{w}.:-]+)+",
207 w = &word[1..word.len() - 1]
208 ))
209 .find_iter(&text)
210 {
211 let before = text[..m.start()].chars().rev().take(8).collect::<Vec<_>>();
212 let nearby = before
213 .iter()
214 .rev()
215 .copied()
216 .chain(text[m.start()..].chars().take(3))
217 .collect::<String>();
218 if nearby.contains("://") || re("[a-f0-9]{16,}").is_match(m.as_str()) {
219 continue;
220 }
221 put(m.as_str(), 1.2);
222 put(m.as_str().rsplit('/').next().unwrap(), 1.0);
223 }
224 for m in re(r"[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*").find_iter(&text) {
225 let a = m.as_str();
226 if re("^[a-fA-F0-9]{7,}$").is_match(a) {
227 continue;
228 }
229 for s in std::iter::once(a).chain(a.split('.')) {
230 if s.len() >= 6 && (s.contains('_') || re("[a-z][A-Z]").is_match(s)) {
231 put(s, 1.0);
232 }
233 let bits = s.split('_').collect::<Vec<_>>();
234 if bits.len() > 2 {
235 let p = bits[..2].join("_");
236 if p.len() >= 6 {
237 put(&p, 0.7);
238 }
239 }
240 }
241 }
242 for (source, pattern, weight) in [
243 (
244 &text,
245 format!(
246 r"[A-Za-z_][{w}-]*\.(?:rs|py|sql|json|tsv)",
247 w = &word[1..word.len() - 1]
248 ),
249 1.0,
250 ),
251 (&title.to_string(), "[A-Z]{3,}".into(), 0.5),
252 ] {
253 let pattern = re(&pattern);
254 let right = re(&format!("^{boundary}"));
255 let mut offset = 0;
256 while let Some(m) = pattern.find_at(source, offset) {
257 if source[..m.start()]
258 .chars()
259 .next_back()
260 .is_none_or(|c| !u::contains(u::WORD, c))
261 && right.is_match(&source[m.end()..])
262 {
263 put(m.as_str(), weight);
264 offset = m.end();
265 } else {
266 offset = m.start() + source[m.start()..].chars().next().unwrap().len_utf8();
269 }
270 }
271 }
272 ids
273}
274pub fn retrieve(item: &Value, text: &str, session: &Value) -> Vec<Span> {
276 let t = chars(text);
277 let byte_positions = text
278 .char_indices()
279 .map(|(byte, _)| byte)
280 .collect::<Vec<_>>();
281 let digest = chars(&spaced(session));
282 let known: HashSet<String> = (0..digest.len().saturating_sub(99))
283 .map(|i| slice(&digest, i, i + 100))
284 .collect();
285 let existing = session["conversation"].as_str().unwrap_or("");
286 let mut candidates: BTreeMap<usize, (f64, usize, HashSet<String>)> = BTreeMap::new();
287 for (id, base) in identifiers(item) {
288 let numeric = id.chars().all(|c| u::contains(u::ISDIGIT, c));
289 let mut hits = Vec::new();
290 let mut offset = 0;
291 while let Some(p) = text[offset..].find(&id) {
292 let b = offset + p;
293 let pos = byte_positions.partition_point(|&byte| byte < b);
294 let end = pos + id.chars().count();
295 offset = b + id.len();
296 let ok = if numeric {
297 (pos == 0 || !u::contains(u::ISDIGIT, t[pos - 1]))
298 && (end == t.len() || !u::contains(u::ISDIGIT, t[end]))
299 } else {
300 (pos == 0 || !(u::contains(u::ISALNUM, t[pos - 1]) || t[pos - 1] == '_'))
301 && (end == t.len() || !u::contains(u::ISALNUM, t[end]))
302 };
303 if ok {
304 hits.push(pos);
305 }
306 }
307 let weight =
313 base * (1.0 + libm::log1p((t.len() as f64 / 500.0).max(1.0) / (1 + hits.len()) as f64));
314 for pos in hits {
315 let start = (pos / 250 * 250).saturating_sub(125);
316 let c = candidates.entry(start).or_insert((
317 0.0,
318 (start + 500).min(t.len()),
319 HashSet::new(),
320 ));
321 if c.2.insert(id.clone()) {
322 c.0 += weight;
323 }
324 }
325 }
326 let stamps = re(r"(?m)^\[([^\]\n]+)\]")
327 .captures_iter(text)
328 .map(|m| {
329 (
330 byte_positions.partition_point(|&byte| byte < m.get(0).unwrap().start()),
331 m[1].to_string(),
332 )
333 })
334 .collect::<Vec<_>>();
335 let mut ranked = Vec::new();
336 for (start, (score, end, _)) in candidates {
337 let raw = slice(&t, start, end);
338 let raw = raw.trim_matches(|c| u::contains(u::SPACE, c));
339 let rt = redact(raw);
340 let r = chars(&rt);
341 if existing.contains(&rt)
342 || (0..r.len().saturating_sub(99))
343 .step_by(50)
344 .any(|i| known.contains(&slice(&r, i, i + 100)))
345 {
346 continue;
347 }
348 let score = score * (1.0 + 0.1 * start as f64 / t.len().max(1) as f64);
349 let time = stamps
350 .iter()
351 .rev()
352 .find(|(p, _)| *p <= start)
353 .map(|(_, s)| s.clone());
354 ranked.push((
355 Span {
356 start,
357 end,
358 score,
359 snippet: Snippet { time, text: rt },
360 },
361 raw.chars().count(),
362 ));
363 }
364 ranked.sort_by(|a, b| {
365 b.0.score
366 .total_cmp(&a.0.score)
367 .then(b.0.start.cmp(&a.0.start))
368 });
369 let mut selected: Vec<Span> = Vec::new();
370 let mut used = 0;
371 for (span, len) in ranked {
372 if used + len > 2100
373 || selected
374 .iter()
375 .any(|s| span.start < s.end && span.end > s.start)
376 {
377 continue;
378 }
379 used += len;
380 selected.push(span);
381 }
382 selected.sort_by_key(|s| s.start);
383 selected
384}
385#[derive(Debug)]
386pub struct HistoryEvidence {
387 pub evidence: Value,
388 pub history_tokens: usize,
389 pub total_tokens: usize,
390 pub base_tokens: usize,
391 pub original_snippets: usize,
392 pub retained: Vec<Span>,
393 pub removed: Vec<(usize, &'static str)>,
394 pub over_limit: bool,
395}
396#[cfg(any(test, feature = "github-history"))]
398pub fn evidence(original_item: &Value, text: &str, base: &Value) -> Result<HistoryEvidence> {
399 let tokenizer = mj_core::github_item::history_tokenizer()?;
400 let count = |a: &str, b: Option<&str>, special| -> Result<usize> {
401 let input = match b {
402 Some(b) => tokenizers_input(a, b),
403 None => a.into(),
404 };
405 Ok(tokenizer
406 .encode(input, special)
407 .map_err(|e| anyhow::anyhow!("{e}"))?
408 .len())
409 };
410 let mut work = retrieve(original_item, text, &base["session"]);
411 let original_snippets = work.len();
412 for s in &mut work {
413 s.snippet.time = s.snippet.time.as_deref().map(redact);
414 }
415 let mut session = indexmap::IndexMap::new();
416 let source = base["session"]
417 .as_object()
418 .ok_or_else(|| anyhow::anyhow!("session must be object"))?;
419 for k in ["conversation", "files", "references", "mentions"] {
420 if let Some(v) = source.get(k) {
421 session.insert(k.into(), v.clone());
422 }
423 }
424 let mut extra = source
425 .keys()
426 .filter(|k| !session.contains_key(*k) && *k != "history")
427 .collect::<Vec<_>>();
428 extra.sort();
429 for k in extra {
430 session.insert(k.clone(), source[k].clone());
431 }
432 let item = base["item"].to_string();
433 let base_tokens = count(
434 &item,
435 Some(&Value::Object(session.clone()).to_string()),
436 true,
437 )?;
438 let mut removed = Vec::new();
439 loop {
440 let history = serde_json::from_str::<Value>(&serde_json::to_string(
441 &work.iter().map(|s| &s.snippet).collect::<Vec<_>>(),
442 )?)?;
443 let ht = count(&history.to_string(), None, false)?;
444 session.insert("history".into(), history);
445 let total = count(
446 &item,
447 Some(&Value::Object(session.clone()).to_string()),
448 true,
449 )?;
450 if work.is_empty() || (ht <= 800 && total <= 7999) {
451 return Ok(HistoryEvidence {
452 evidence: Value::Object(indexmap::IndexMap::from([
453 ("item".into(), base["item"].clone()),
454 ("session".into(), Value::Object(session)),
455 ])),
456 history_tokens: ht,
457 total_tokens: total,
458 base_tokens,
459 original_snippets,
460 retained: work,
461 removed,
462 over_limit: total > 7999,
463 });
464 }
465 let worst = (0..work.len())
466 .min_by(|&a, &b| {
467 work[a]
468 .score
469 .total_cmp(&work[b].score)
470 .then(work[a].start.cmp(&work[b].start))
471 })
472 .unwrap();
473 removed.push((
474 work[worst].start,
475 if ht > 800 {
476 "history_budget"
477 } else {
478 "input_capacity"
479 },
480 ));
481 work.remove(worst);
482 }
483}
484#[cfg(any(test, feature = "github-history"))]
485fn tokenizers_input<'a>(a: &'a str, b: &'a str) -> tokenizers::EncodeInput<'a> {
486 (a, b).into()
487}
488
489#[derive(Clone, Debug, Deserialize)]
491pub struct HistoryRow {
492 pub stable_id: String,
493 pub position: i64,
494 pub created_at_ms: i64,
495 pub last_changed_at_ms: i64,
496 pub body: Value,
497}
498fn timestamp(ms: i64) -> Result<String> {
499 Ok(chrono::DateTime::from_timestamp_millis(ms)
500 .ok_or_else(|| anyhow::anyhow!("timestamp out of range"))?
501 .to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
502}
503pub fn render(
505 session_id: &str,
506 rows: &[HistoryRow],
507 cutoff_ms: i64,
508 repo: &str,
509 number: u64,
510) -> Result<String> {
511 let mut ordered = rows.iter().collect::<Vec<_>>();
512 ordered.sort_by(|a, b| {
513 a.position
514 .cmp(&b.position)
515 .then(a.stable_id.cmp(&b.stable_id))
516 });
517 let (mut changed, mut later, mut notices) = (0, 0, 0);
518 let mut chunks = Vec::new();
519 for row in ordered {
520 if row.created_at_ms > cutoff_ms {
521 later += 1;
522 continue;
523 }
524 if row.last_changed_at_ms > cutoff_ms {
525 changed += 1;
526 continue;
527 }
528 let b = &row.body;
529 let s = |v: &Value| v.as_str().unwrap_or("").to_string();
530 let rendered = match b["kind"].as_str().unwrap_or("") {
531 "user" => Some(format!(
532 "USER\n{}",
533 b["content"]
534 .as_array()
535 .into_iter()
536 .flatten()
537 .filter(|x| x["type"] == "text")
538 .map(|x| s(&x["text"]))
539 .collect::<Vec<_>>()
540 .join("\n")
541 )),
542 "agent" => Some(format!(
543 "AGENT\n{}",
544 b["chunks"]
545 .as_array()
546 .into_iter()
547 .flatten()
548 .filter(|x| x["content"]["type"] == "text")
549 .map(|x| s(&x["content"]["text"]))
550 .collect::<String>()
551 )),
552 "tool" => {
553 let call = &b["call"];
554 Some(format!(
555 "TOOL {}\nTITLE: {}\nCALL: {}",
556 call["kind"]
557 .as_str()
558 .filter(|x| !x.is_empty())
559 .unwrap_or("call")
560 .to_uppercase(),
561 s(&call["title"]),
562 call
563 ))
564 }
565 "message" => {
566 let body = &b["event"]["body"];
567 let typ = body["type"].as_str().unwrap_or("");
568 if (typ == "new_github_item" || typ.starts_with("github_"))
569 && body["number"].as_u64() == Some(number)
570 && body["repo"]
571 .as_str()
572 .is_none_or(|r| r.to_lowercase() == repo.to_lowercase())
573 {
574 notices += 1;
575 continue;
576 }
577 Some(format!(
578 "PEER MESSAGE {}\n{}",
579 s(&body["from"]["title"]),
580 s(&body["text"])
581 ))
582 }
583 _ => None,
584 };
585 if let Some(text) = rendered {
586 chunks.push(format!("[{}] {}", timestamp(row.created_at_ms)?, text));
587 }
588 }
589 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"))
590}
591
592#[cfg(any(test, feature = "github-history"))]
596pub fn build_evidence(
597 original: &mj_core::github_item::GithubItem,
598 transcript: &str,
599 base: &mj_core::github_item::GithubItemEvidence,
600) -> Result<(mj_core::github_item::GithubItemEvidence, HistoryEvidence)> {
601 let original = serde_json::from_str(&serde_json::to_string(original)?)?;
602 let base = serde_json::from_str(&serde_json::to_string(base)?)?;
603 let result = evidence(&original, transcript, &base)?;
604 let typed = serde_json::from_str(&result.evidence.to_string())?;
605 Ok((typed, result))
606}
607
608pub fn student_segments(
611 evidence: &mj_core::github_item::GithubItemEvidence,
612) -> Result<(String, String)> {
613 Ok((
614 serde_json::to_string(&evidence.item)?,
615 serde_json::to_string(&evidence.session)?,
616 ))
617}
618
619#[cfg(test)]
620mod tests {
621 use super::*;
622 #[test]
624 fn github_history_python_tool_numbers() {
625 let fixture: Value = serde_json::from_str(include_str!(
626 "../tests/fixtures/github-history/tool-numbers.json"
627 ))
628 .unwrap();
629 let row = HistoryRow {
630 stable_id: "tool".into(),
631 position: 1,
632 created_at_ms: 1000,
633 last_changed_at_ms: 1000,
634 body: fixture["body"].clone(),
635 };
636 assert_eq!(
637 render("floats", &[row], 2000, "owner/repo", 42).unwrap(),
638 fixture["expected"].as_str().unwrap()
639 );
640 }
641 #[test]
643 fn github_history_python_unicode_boundaries() {
644 let f: Value = serde_json::from_str(include_str!(
645 "../tests/fixtures/github-history/unicode-adversarial.json"
646 ))
647 .unwrap();
648 assert_eq!(
649 serde_json::to_string(&identifiers(&f["item"])).unwrap(),
650 f["identifiers"].to_string()
651 );
652 let raw = retrieve(&f["item"], f["transcript"].as_str().unwrap(), &f["session"]);
653 assert_eq!(
654 serde_json::to_string(&raw.iter().map(|s| &s.snippet).collect::<Vec<_>>()).unwrap(),
655 f["snippets"].to_string()
656 );
657 }
658 #[test]
659 fn github_history_python_format_fixtures() {
660 for line in include_str!("../tests/fixtures/github-history/reference.jsonl").lines() {
661 let f: Value = serde_json::from_str(line).unwrap();
662 let id = &f["pid"];
663 let raw = retrieve(
664 &f["item"],
665 f["transcript_text"].as_str().unwrap(),
666 &f["bounded_evidence_without_history"]["session"],
667 );
668 assert_eq!(
669 serde_json::to_string(&raw.iter().map(|s| &s.snippet).collect::<Vec<_>>()).unwrap(),
670 f["expected_retrieved_json"].as_str().unwrap(),
671 "lexical {id}"
672 );
673 let prepared: mj_core::github_item::GithubItemEvidence =
674 serde_json::from_str(f["expected_evidence_json"].as_str().unwrap()).unwrap();
675 let (item_segment, session_segment) = student_segments(&prepared).unwrap();
676 assert_eq!(
677 item_segment,
678 f["expected_item_segment"].as_str().unwrap(),
679 "item segment {id}"
680 );
681 assert_eq!(
682 session_segment,
683 f["expected_session_segment"].as_str().unwrap(),
684 "session segment {id}"
685 );
686 for (span, expected) in raw.iter().zip(f["expected_raw_spans"].as_array().unwrap()) {
687 assert_eq!(span.start as u64, expected["start"].as_u64().unwrap());
688 assert_eq!(span.end as u64, expected["end"].as_u64().unwrap());
689 assert_eq!(
690 format!("{:016x}", span.score.to_bits()),
691 expected["score_bits"].as_str().unwrap(),
692 "score {id}"
693 );
694 }
695 let actual = evidence(
696 &f["item"],
697 f["transcript_text"].as_str().unwrap(),
698 &f["bounded_evidence_without_history"],
699 )
700 .unwrap();
701 assert_eq!(
702 actual.evidence["session"]["history"].to_string(),
703 f["expected_history_json"].as_str().unwrap(),
704 "budget {id}"
705 );
706 assert_eq!(
707 actual.evidence.to_string(),
708 f["expected_evidence_json"].as_str().unwrap(),
709 "evidence {id}"
710 );
711 assert_eq!(
712 actual.history_tokens as u64,
713 f["expected_stats"]["history_tokens"].as_u64().unwrap(),
714 "tokens {id}"
715 );
716 assert_eq!(
717 actual.total_tokens as u64,
718 f["expected_stats"]["total_tokens"].as_u64().unwrap(),
719 "pair tokens {id}"
720 );
721 }
722 }
723}