1use anyhow::{Result, ensure};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7pub const MAX_BODY_BYTES: usize = 64 * 1024;
8pub const QUESTIONS: &str = include_str!("github_item/questions_v2.json");
9pub const ITEM_BODY_BYTES: usize = 4096;
12pub const SESSION_TURNS: usize = 3;
13pub const CONVERSATION_BYTES: usize = 8 * 1024;
14pub const MESSAGE_BYTES: usize = 2 * 1024;
15pub const MAX_FILES: usize = 32;
16pub const FILE_BYTES: usize = 256;
17pub const MAX_REFERENCES: usize = 32;
18pub const REFERENCE_BYTES: usize = 128;
19pub const MAX_MENTIONS: usize = 16;
21pub const MENTION_BYTES: usize = 256;
22const BODY_TRUNCATION_MARKER: &str = "\n[GitHub item body truncated.]";
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum GithubItemKind {
27 Issue,
28 PullRequest,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct GithubItem {
34 pub repo: String,
35 pub kind: GithubItemKind,
36 pub number: u64,
37 pub title: String,
38 pub body: String,
39 pub author: String,
40 pub url: String,
41}
42
43#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(deny_unknown_fields)]
45pub struct HistorySnippet {
46 pub time: Option<String>,
47 pub text: String,
48}
49
50#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(deny_unknown_fields)]
52pub struct SessionContext {
53 pub conversation: String,
54 pub files: Vec<String>,
55 pub references: Vec<String>,
56 #[serde(default)]
57 pub mentions: Vec<String>,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub history: Option<Vec<HistorySnippet>>,
60 #[serde(skip)]
62 pub mention_candidates: Vec<(crate::github_reference::GithubReference, String)>,
63}
64
65impl SessionContext {
66 pub fn for_item(mut self, item: &GithubItem, bare_is_item_repo: bool) -> Self {
73 use crate::github_reference::{GithubReference, github_references};
74 let mut targets = github_references(&format!("{}\n{}", item.title, item.body));
75 targets.extend(github_references(&format!("{}#{}", item.repo, item.number)));
76 let identity = |r: &GithubReference, bare_is_item_repo: bool| {
77 let repo = match (&r.owner, &r.repo) {
78 (Some(owner), Some(repo)) => format!("{owner}/{repo}"),
79 _ if bare_is_item_repo => item.repo.clone(),
80 _ => return None,
81 };
82 Some((repo.to_ascii_lowercase(), r.number))
83 };
84 let targets: Vec<_> = targets.iter().filter_map(|t| identity(t, true)).collect();
85 self.mentions.clear();
86 for (reference, line) in self.mention_candidates.iter().rev() {
87 if identity(reference, bare_is_item_repo).is_some_and(|r| targets.contains(&r))
88 && !self.mentions.contains(line)
89 {
90 self.mentions.push(line.clone());
91 if self.mentions.len() == MAX_MENTIONS {
92 break;
93 }
94 }
95 }
96 self.mention_candidates.clear();
97 self
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(deny_unknown_fields)]
105pub struct GithubItemEvidence {
106 pub item: GithubItem,
107 pub session: SessionContext,
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct GithubItemVerdict {
112 pub interested: bool,
113}
114
115#[derive(Serialize)]
116struct UpstreamBody<'a> {
117 model: &'static str,
118 state: &'a GithubItemEvidence,
119 questions: Value,
120}
121
122pub fn questions() -> Value {
123 serde_json::from_str(QUESTIONS).expect("checked-in GitHub item questions are valid JSON")
124}
125
126impl GithubItemEvidence {
127 pub fn bounded_for_request(&self) -> Result<Self> {
130 self.validate_fixed_fields()?;
131 let mut bounded = self.clone();
132 if bounded.item.body.len() > ITEM_BODY_BYTES {
133 bounded.item.body = format!(
134 "{}{}",
135 utf8_prefix(&bounded.item.body, ITEM_BODY_BYTES),
136 BODY_TRUNCATION_MARKER
137 );
138 }
139 bounded.validate()?;
140 Ok(bounded)
141 }
142
143 pub fn validate(&self) -> Result<()> {
144 self.validate_fixed_fields()?;
145 ensure!(
146 self.session.conversation.len() <= CONVERSATION_BYTES,
147 "GitHub session conversation is too long"
148 );
149 ensure!(
150 self.session.files.len() <= MAX_FILES
151 && self
152 .session
153 .files
154 .iter()
155 .all(|s| !s.trim().is_empty() && s.len() <= FILE_BYTES),
156 "invalid GitHub session files"
157 );
158 ensure!(
159 self.session.references.len() <= MAX_REFERENCES
160 && self
161 .session
162 .references
163 .iter()
164 .all(|s| !s.trim().is_empty() && s.len() <= REFERENCE_BYTES),
165 "invalid GitHub session references"
166 );
167 ensure!(
168 self.session.mentions.len() <= MAX_MENTIONS
169 && self
170 .session
171 .mentions
172 .iter()
173 .all(|s| !s.trim().is_empty() && s.len() <= MENTION_BYTES),
174 "invalid GitHub session mentions"
175 );
176 ensure!(
177 self.item.body.len() <= ITEM_BODY_BYTES + BODY_TRUNCATION_MARKER.len(),
178 "GitHub item body is too long"
179 );
180 ensure!(
181 upstream_len(self)? <= MAX_BODY_BYTES,
182 "GitHub item request exceeds byte limit"
183 );
184 Ok(())
185 }
186
187 pub fn upstream_body(&self) -> impl Serialize + '_ {
190 UpstreamBody {
191 model: "jev-latest",
192 state: self,
193 questions: questions(),
194 }
195 }
196
197 fn validate_fixed_fields(&self) -> Result<()> {
198 ensure!(
199 !self.item.repo.trim().is_empty() && self.item.repo.len() <= 256,
200 "invalid GitHub repository"
201 );
202 ensure!(
203 self.item.number > 0 && self.item.number <= 9_007_199_254_740_991,
204 "invalid GitHub item number"
205 );
206 ensure!(
207 !self.item.title.trim().is_empty() && self.item.title.len() <= 1024,
208 "invalid GitHub item title"
209 );
210 ensure!(
211 self.item.author.len() <= 256,
212 "GitHub item author is too long"
213 );
214 ensure!(
215 !self.item.url.trim().is_empty() && self.item.url.len() <= 2048,
216 "invalid GitHub item URL"
217 );
218 Ok(())
219 }
220}
221
222impl GithubItemVerdict {
223 pub fn parse(response: &Value) -> Result<Self> {
224 fn affirmative_probability(response: &Value, key: &str) -> Result<bool> {
225 let answer = &response["answers"][key];
226 ensure!(answer["type"] == "noul", "invalid GitHub item answer type");
227 let probability = answer["noul"]
228 .as_f64()
229 .ok_or_else(|| anyhow::anyhow!("missing GitHub item probability"))?;
230 ensure!(
231 probability.is_finite() && (0.0..=1.0).contains(&probability),
232 "invalid GitHub item probability"
233 );
234 Ok(probability >= 0.4)
236 }
237
238 let answers = response["answers"]
239 .as_object()
240 .ok_or_else(|| anyhow::anyhow!("missing GitHub item answers"))?;
241 ensure!(
242 answers.len() == 1 && answers.contains_key("interested"),
243 "incomplete GitHub item answers"
244 );
245 Ok(Self {
246 interested: affirmative_probability(response, "interested")?,
247 })
248 }
249}
250
251fn upstream_len(evidence: &GithubItemEvidence) -> Result<usize> {
252 Ok(serde_json::to_vec(&evidence.upstream_body())?.len())
253}
254
255fn utf8_prefix(text: &str, limit: usize) -> &str {
256 let mut end = limit.min(text.len());
257 while !text.is_char_boundary(end) {
258 end -= 1;
259 }
260 &text[..end]
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266 use serde_json::json;
267
268 fn evidence() -> GithubItemEvidence {
269 GithubItemEvidence {
270 item: GithubItem {
271 repo: "brokkai/mjolnir".into(),
272 kind: GithubItemKind::PullRequest,
273 number: 42,
274 title: "Add mailbox support".into(),
275 body: "Add mailbox support".into(),
276 author: "agent".into(),
277 url: "https://github.com/brokkai/mjolnir/pull/42".into(),
278 },
279 session: SessionContext {
280 conversation: "User: Implement mailbox support\nAgent: Checking the worker\n"
281 .into(),
282 files: vec!["mj-worker/src/lib.rs".into()],
283 references: vec!["#42".into()],
284 ..Default::default()
285 },
286 }
287 }
288
289 #[test]
290 fn item_mentions_resolve_bare_references_without_crossing_repositories() {
291 let item = GithubItem {
292 repo: "owner/repo".into(),
293 kind: GithubItemKind::Issue,
294 number: 42,
295 title: "Fix #7642".into(),
296 body: String::new(),
297 author: String::new(),
298 url: "https://github.com/owner/repo/issues/42".into(),
299 };
300 let mut session = SessionContext::default();
301 for line in [
302 "pending #7642",
303 "other/repo#42",
304 "owner/repo#42",
305 "pending #7642",
306 ] {
307 for reference in crate::github_reference::github_references(line) {
308 session.mention_candidates.push((reference, line.into()));
309 }
310 }
311 let ambiguous = session.clone().for_item(&item, false);
313 assert_eq!(ambiguous.mentions, ["owner/repo#42"]);
314 let selected = session.for_item(&item, true);
315 assert_eq!(selected.mentions, ["pending #7642", "owner/repo#42"]);
316 assert!(
317 !serde_json::to_string(&selected)
318 .unwrap()
319 .contains("mention_candidates")
320 );
321 }
322
323 #[test]
324 fn bounded_request_marks_truncation_without_splitting_utf8() {
325 let typical = evidence();
326 println!(
327 "typical v2 request: {} bytes",
328 upstream_len(&typical).unwrap()
329 );
330 let mut maximal = typical.clone();
331 maximal.item.repo = "r".repeat(256);
332 maximal.item.title = "t".repeat(1024);
333 maximal.item.author = "a".repeat(256);
334 maximal.item.url = "u".repeat(2048);
335 maximal.item.number = 9_007_199_254_740_991;
336 maximal.item.body = "x".repeat(ITEM_BODY_BYTES - 1) + "🦀";
337 maximal.session = SessionContext {
338 conversation: "x".repeat(CONVERSATION_BYTES),
339 files: vec!["x".repeat(FILE_BYTES); MAX_FILES],
340 references: vec!["x".repeat(REFERENCE_BYTES); MAX_REFERENCES],
341 ..Default::default()
342 };
343 let bounded = maximal.bounded_for_request().unwrap();
344 assert_eq!(
345 bounded.item.body,
346 "x".repeat(ITEM_BODY_BYTES - 1) + BODY_TRUNCATION_MARKER
347 );
348 println!(
349 "maximal v2 request: {} bytes",
350 upstream_len(&bounded).unwrap()
351 );
352 assert!(upstream_len(&bounded).unwrap() <= MAX_BODY_BYTES);
353 let mut escaped = bounded.clone();
354 escaped.item.repo = "\"".repeat(256);
355 escaped.item.title = "\"".repeat(1024);
356 escaped.item.author = "\"".repeat(256);
357 escaped.item.url = "\"".repeat(2048);
358 escaped.item.body = format!("{}{}", "\"".repeat(ITEM_BODY_BYTES), BODY_TRUNCATION_MARKER);
359 escaped.session.conversation = "\"".repeat(CONVERSATION_BYTES);
360 escaped.session.files = vec!["\"".repeat(FILE_BYTES); MAX_FILES];
361 escaped.session.references = vec!["\"".repeat(REFERENCE_BYTES); MAX_REFERENCES];
362 escaped.validate().unwrap();
363 println!(
364 "maximal escaped v2 request: {} bytes",
365 upstream_len(&escaped).unwrap()
366 );
367 escaped.item.body = "\0".repeat(ITEM_BODY_BYTES);
370 assert!(upstream_len(&escaped).unwrap() > MAX_BODY_BYTES);
371 assert!(escaped.validate().is_err());
372 let serialized = serde_json::to_string(&bounded.upstream_body()).unwrap();
373 assert!(serialized.find("\"item\"").unwrap() < serialized.find("\"session\"").unwrap());
374 }
375
376 #[test]
377 fn evidence_serialization_parses_only_typed_v2_answers() {
378 assert!(
379 GithubItemVerdict::parse(&json!({"answers":{"interested":{"type":"noul","noul":0.5}}}))
380 .unwrap()
381 .interested
382 );
383 for response in [
384 json!({"answers":{"interested":{"type":"choice","choice":"yes"}}}),
385 json!({"answers":{"interested":{"type":"noul","noul":1.1}}}),
386 json!({"answers":{"interested":{"type":"noul","noul":0.1},"created":{"type":"noul","noul":0.2}}}),
387 ] {
388 assert!(GithubItemVerdict::parse(&response).is_err());
389 }
390 }
391}
392
393#[path = "github_item/history_unicode.rs"]
394pub mod history_unicode;
395
396#[cfg(feature = "github-history")]
398pub fn history_tokenizer() -> Result<tokenizers::Tokenizer> {
399 let mut t =
400 tokenizers::Tokenizer::from_bytes(include_bytes!("github_item/ettin-tokenizer.json"))
401 .map_err(|e| anyhow::anyhow!("{e}"))?;
402 t.with_padding(None);
403 t.with_truncation(None)
404 .map_err(|e| anyhow::anyhow!("{e}"))?;
405 Ok(t)
406}