Skip to main content

mj_transcript/
github_item.rs

1//! Compact GitHub relevance evidence from the materialized transcript.
2use mj_core::github_item::*;
3use mj_core::state::{MaterializedSession, TranscriptBody};
4use mj_core::transcript::{materialized_chunks_text, materialized_content_text};
5
6fn prefix(text: &str, bytes: usize) -> String {
7    text[..text.floor_char_boundary(bytes.min(text.len()))].to_owned()
8}
9
10const MENTION_ELISION: &str = "…";
11/// Bytes kept before the reference, so the subject that relates the session
12/// to it ("reviewing", "blocked on") usually survives.
13const MENTION_LEAD_BYTES: usize = 96;
14
15/// The part of `line` around the reference parsed at byte offset `at`, at
16/// most [`MENTION_BYTES`]. Agent paragraphs are often one long line, so a
17/// plain prefix would drop the reference the mention was chosen for. The
18/// parser's offset, not a text search, places the window: `#12` must not
19/// land on `#123`, and each occurrence keeps its own context.
20fn mention_window(line: &str, at: usize, reference_len: usize) -> String {
21    if line.len() <= MENTION_BYTES {
22        return line.to_owned();
23    }
24    // Shrink the lead so the whole reference fits: a URL with long owner and
25    // repository names can take most of the window by itself.
26    let lead_bytes = MENTION_LEAD_BYTES
27        .min(MENTION_BYTES.saturating_sub(reference_len + 2 * MENTION_ELISION.len()));
28    let start = line.floor_char_boundary(at.saturating_sub(lead_bytes));
29    let lead = if start > 0 { MENTION_ELISION } else { "" };
30    let rest = &line[start..];
31    let room = MENTION_BYTES - lead.len();
32    if rest.len() <= room {
33        return format!("{lead}{rest}");
34    }
35    let end = rest.floor_char_boundary(room - MENTION_ELISION.len());
36    format!("{lead}{}{MENTION_ELISION}", &rest[..end])
37}
38
39const MESSAGE_TRUNCATION_MARKER: &str = "\n[Message truncated.]";
40
41fn distinct(values: impl Iterator<Item = String>, count: usize) -> Vec<String> {
42    let mut result = Vec::new();
43    for value in values {
44        if !result.contains(&value) {
45            result.push(value);
46        }
47        if result.len() == count {
48            break;
49        }
50    }
51    result
52}
53
54pub fn session_digest(session: &MaterializedSession) -> SessionContext {
55    let boundary = session
56        .transcript
57        .iter()
58        .rposition(|i| mj_core::archive::is_context_boundary(&i.stable_id))
59        .map_or(0, |i| i + 1);
60    let items = &session.transcript[boundary..];
61    let start = items
62        .iter()
63        .enumerate()
64        .rev()
65        .filter(|(_, i)| matches!(i.body, TranscriptBody::User { .. }))
66        .nth(SESSION_TURNS - 1)
67        .map_or(0, |(i, _)| i);
68    let items = &items[start..];
69    let mut digest = SessionContext::default();
70    let mut messages = Vec::new();
71    let mut files = Vec::new();
72    let mut refs = Vec::new();
73    for item in items {
74        let text = match &item.body {
75            TranscriptBody::User { content } => {
76                let text = materialized_content_text(content);
77                if text.trim() != mj_core::continuation::PROMPT
78                    && mj_core::acp::context_command_text(&text).is_none()
79                    && !text.trim().is_empty()
80                {
81                    messages.push(("User: ", text.clone()));
82                }
83                text
84            }
85            TranscriptBody::Message { event } => {
86                if event.message_text().is_some() {
87                    messages.push(("User: ", mj_core::mailbox::render_mailbox_event(event)));
88                }
89                if event.message_text().is_some() {
90                    mj_core::mailbox::render_mailbox_event(event)
91                } else {
92                    String::new()
93                }
94            }
95            TranscriptBody::Agent { chunks, .. } => {
96                let text = materialized_chunks_text(chunks);
97                if !text.trim().is_empty() {
98                    messages.push(("Agent: ", text.clone()));
99                }
100                text
101            }
102            TranscriptBody::Tool { call, .. } => {
103                if let Ok(call) = call.decode() {
104                    files.extend(
105                        call.locations
106                            .iter()
107                            .map(|l| prefix(&l.path.to_string_lossy(), FILE_BYTES)),
108                    );
109                    call.title.to_string()
110                } else {
111                    String::new()
112                }
113            }
114            _ => String::new(),
115        };
116        // Index full lines before conversation truncation or the reference-list cap.
117        for line in text.lines().map(str::trim).filter(|line| !line.is_empty()) {
118            for reference in mj_core::github_reference::github_references(line) {
119                let window = mention_window(line, reference.start, reference.text.len());
120                digest.mention_candidates.push((reference, window));
121            }
122        }
123        refs.extend(
124            mj_core::github_reference::github_references(&text)
125                .into_iter()
126                .map(|r| prefix(&r.text, REFERENCE_BYTES)),
127        );
128    }
129    // Reserve newest messages first, then restore their chronological order.
130    // Labels, newlines and truncation markers all count against the budget.
131    let mut remaining = CONVERSATION_BYTES;
132    let mut selected = Vec::new();
133    for (role, text) in messages.into_iter().rev() {
134        let Some(available) = remaining.checked_sub(role.len() + 1) else {
135            break;
136        };
137        let cap = MESSAGE_BYTES.min(available);
138        let message = if text.len() > cap {
139            let Some(head) = cap.checked_sub(MESSAGE_TRUNCATION_MARKER.len()) else {
140                break;
141            };
142            format!("{}{}", prefix(&text, head), MESSAGE_TRUNCATION_MARKER)
143        } else {
144            text
145        };
146        let rendered = format!("{role}{message}\n");
147        remaining -= rendered.len();
148        selected.push(rendered);
149    }
150    digest.conversation = selected.into_iter().rev().collect();
151    digest.files = distinct(files.into_iter().rev(), MAX_FILES);
152    digest.references = distinct(refs.into_iter().rev(), MAX_REFERENCES);
153    digest
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use mj_core::state::TranscriptItem;
160    use serde_json::json;
161    use std::sync::Arc;
162
163    #[test]
164    fn mentions_survive_reference_and_conversation_truncation_with_utf8() {
165        let mut session = MaterializedSession::empty("mention-index");
166        let text = format!(
167            "pending #1\n{}\n{}",
168            "é".repeat(MESSAGE_BYTES),
169            (2..50)
170                .map(|n| format!("pending #{n}"))
171                .collect::<Vec<_>>()
172                .join("\n")
173        );
174        session.transcript.push(Arc::new(TranscriptItem {
175            stable_id: "user:1".into(),
176            position: 1,
177            latest_content_event_ordinal: None,
178            created_at_ms: 0,
179            last_changed_at_ms: 0,
180            body: TranscriptBody::User {
181                content: vec![json!({"type":"text","text":text})],
182            },
183        }));
184        let digest = session_digest(&session);
185        assert!(!digest.references.contains(&"#1".to_owned()));
186        let item = GithubItem {
187            repo: "owner/repo".into(),
188            kind: GithubItemKind::Issue,
189            number: 49,
190            title: "Fix #1".into(),
191            body: String::new(),
192            author: String::new(),
193            url: "https://github.com/owner/repo/issues/49".into(),
194        };
195        assert_eq!(
196            digest.for_item(&item, true).mentions,
197            ["pending #49", "pending #1"]
198        );
199        let long = format!(
200            "#123 first {} reviewing #12 next {}",
201            "é".repeat(200),
202            "x".repeat(400)
203        );
204        let at = mj_core::github_reference::github_references(&long)
205            .into_iter()
206            .find(|r| r.number == 12)
207            .unwrap()
208            .start;
209        let window = mention_window(&long, at, "#12".len());
210        assert!(window.len() <= MENTION_BYTES && window.contains("reviewing #12 next"));
211        // GitHub allows 39-byte owners and 100-byte repository names.
212        let url = format!(
213            "https://github.com/{}/{}/pull/123456",
214            "o".repeat(39),
215            "r".repeat(100)
216        );
217        let long = format!("{} {url} {}", "x".repeat(300), "y".repeat(300));
218        let at = long.find(&url).unwrap();
219        let window = mention_window(&long, at, url.len());
220        assert!(window.len() <= MENTION_BYTES && window.contains(&url));
221        assert!(window.starts_with(MENTION_ELISION) && window.ends_with(MENTION_ELISION));
222    }
223
224    #[test]
225    fn digest_preserves_recency_and_utf8_across_turn_boundaries() {
226        let mut session = MaterializedSession::empty("digest-test");
227        let bodies = [
228            TranscriptBody::User {
229                content: vec![json!({"type":"text","text":"old #1"})],
230            },
231            TranscriptBody::User {
232                content: vec![json!({"type":"text","text":"first #2 owner/repo#3"})],
233            },
234            TranscriptBody::User {
235                content: vec![json!({"type":"text","text":"second #2"})],
236            },
237            TranscriptBody::Tool {
238                call: json!({"toolCallId":"t","title":"Read https://github.com/owner/repo/pull/4", "status":"completed","locations":[{"path":"src/lib.rs"}]}).into(),
239                terminal_outputs: vec![],
240                terminal_refs: vec![],
241                presentation: None,
242            },
243            TranscriptBody::User {
244                content: vec![
245                    json!({"type":"text","text":"x".repeat(MESSAGE_BYTES - MESSAGE_TRUNCATION_MARKER.len() - 1) + "🦀" + &"tail".repeat(20)}),
246                ],
247            },
248        ];
249        for (i, body) in bodies.into_iter().enumerate() {
250            session.transcript.push(Arc::new(TranscriptItem {
251                stable_id: format!("item:{i}"),
252                position: i as u64 + 1,
253                latest_content_event_ordinal: None,
254                created_at_ms: 0,
255                last_changed_at_ms: 0,
256                body,
257            }));
258        }
259        let digest = session_digest(&session);
260        assert_eq!(
261            digest.conversation,
262            format!(
263                "User: first #2 owner/repo#3\nUser: second #2\nUser: {}{}\n",
264                "x".repeat(MESSAGE_BYTES - MESSAGE_TRUNCATION_MARKER.len() - 1),
265                MESSAGE_TRUNCATION_MARKER
266            )
267        );
268        assert_eq!(digest.files, ["src/lib.rs"]);
269        assert_eq!(
270            digest.references,
271            ["https://github.com/owner/repo/pull/4", "#2", "owner/repo#3"]
272        );
273        Arc::make_mut(session.transcript.last_mut().unwrap()).stable_id =
274            format!("{}clear", mj_core::archive::CONTEXT_BOUNDARY_PREFIX);
275        let cleared = session_digest(&session);
276        assert!(cleared.conversation.is_empty());
277        assert!(cleared.files.is_empty());
278        assert!(cleared.references.is_empty());
279    }
280
281    #[test]
282    fn digest_keeps_peer_relationships_and_newest_messages_within_budget() {
283        let mut session = MaterializedSession::empty("digest-budget");
284        let mut add = |stable_id: String, body| {
285            session.transcript.push(Arc::new(TranscriptItem {
286                stable_id,
287                position: session.transcript.len() as u64 + 1,
288                latest_content_event_ordinal: None,
289                created_at_ms: 0,
290                last_changed_at_ms: 0,
291                body,
292            }));
293        };
294        let user = |text: String| TranscriptBody::User {
295            content: vec![json!({"type":"text","text":text})],
296        };
297        add("user:old".into(), user("discard before clear".into()));
298        add("context-cleared:1".into(), user("/clear".into()));
299        add("user:task".into(), user("Review the pending fix".into()));
300        add(
301            "user:continuation".into(),
302            user(mj_core::continuation::PROMPT.into()),
303        );
304        add(
305            "user:compact".into(),
306            user(" /compact retain pending reviews".into()),
307        );
308        // Enough assistant messages to exhaust even the largest replay budget.
309        for i in 0..CONVERSATION_BYTES / MESSAGE_BYTES + 2 {
310            add(
311                format!("agent:{i}"),
312                TranscriptBody::Agent {
313                    chunks: vec![
314                        json!({"content":{"type":"text","text":format!("reply {i}: {}", "é".repeat(MESSAGE_BYTES))}}),
315                    ],
316                    streaming: false,
317                },
318            );
319        }
320        add(
321            "user:peer".into(),
322            user("Message from session reviewer: awaiting #42 final head".into()),
323        );
324        let peer = mj_core::mailbox::MailboxEvent {
325            key: "peer-review".into(),
326            source: "peer".into(),
327            wake: false,
328            created_at_ms: 0,
329            body: mj_core::mailbox::MailboxEventBody::ParentMessage {
330                text: "The review for issue 42 is pending".into(),
331            },
332        };
333        let peer_text = mj_core::mailbox::render_mailbox_event(&peer);
334        add(
335            "message:peer-review".into(),
336            TranscriptBody::Message {
337                event: Box::new(peer),
338            },
339        );
340        let digest = session_digest(&session);
341        assert!(digest.conversation.len() <= CONVERSATION_BYTES);
342        assert!(!digest.conversation.contains("discard before clear"));
343        assert!(!digest.conversation.contains("Review the pending fix"));
344        assert!(!digest.conversation.contains(mj_core::continuation::PROMPT));
345        assert!(!digest.conversation.contains("/compact"));
346        assert!(!digest.conversation.contains("reply 0:"));
347        assert!(
348            digest
349                .conversation
350                .ends_with(&format!("User: {peer_text}\n"))
351        );
352        assert!(
353            digest
354                .conversation
355                .contains("User: Message from session reviewer: awaiting #42 final head\n")
356        );
357        assert!(digest.conversation.contains(MESSAGE_TRUNCATION_MARKER));
358        assert_eq!(digest.references, ["#42"]);
359    }
360}