1use std::collections::HashMap;
24use std::time::Instant;
25
26use crate::message::{Message, Role};
27
28use super::{
29 call_summary, clean, facts, split_sections, strip_think, Facts, Limits, Options, LOG_HEADING,
30};
31
32const MIN_FRAGMENT: usize = 3;
35
36const WHOLE: usize = 1 << 40;
39
40const KEEP_MISSING: usize = 8;
43
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct Tally {
51 pub total: usize,
52 pub present: usize,
53 pub missing: Vec<String>,
54}
55
56impl Tally {
57 fn of<I: IntoIterator<Item = String>>(items: I, handoff: &str) -> Self {
58 let mut tally = Tally::default();
59 for item in items {
60 tally.total += 1;
61 if handoff.contains(&item) {
62 tally.present += 1;
63 } else if tally.missing.len() < KEEP_MISSING {
64 tally.missing.push(item);
65 }
66 }
67 tally
68 }
69
70 pub fn all_present(&self) -> bool {
71 self.present == self.total
72 }
73}
74
75#[derive(Debug, Clone, Default, PartialEq, Eq)]
79pub struct Retention {
80 pub files: Tally,
81 pub commands: Tally,
82 pub errors: Tally,
83 pub blocked: Tally,
84}
85
86impl Retention {
87 pub fn totals(&self) -> (usize, usize) {
89 let all = [&self.files, &self.commands, &self.errors, &self.blocked];
90 (
91 all.iter().map(|t| t.present).sum(),
92 all.iter().map(|t| t.total).sum(),
93 )
94 }
95
96 pub fn ledgers(&self) -> [(&'static str, &Tally); 4] {
97 [
98 ("files", &self.files),
99 ("commands", &self.commands),
100 ("errors", &self.errors),
101 ("blocked", &self.blocked),
102 ]
103 }
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct Violation {
109 pub at: u64,
111 pub line: String,
113 pub fragment: String,
116 pub why: String,
117}
118
119#[derive(Debug, Clone, Default, PartialEq, Eq)]
121pub struct Faithfulness {
122 pub lines: usize,
123 pub fragments: usize,
126 pub unreferenced: usize,
129 pub violations: Vec<Violation>,
130}
131
132impl Faithfulness {
133 pub fn ok(&self) -> bool {
134 self.violations.is_empty()
135 }
136}
137
138#[derive(Debug, Clone)]
140pub struct Measurement {
141 pub session: String,
142 pub messages: usize,
144 pub total_messages: usize,
147 pub drops: bool,
150 pub middle_chars: usize,
152 pub handoff_chars: usize,
153 pub budget_chars: usize,
154 pub compile_micros: u128,
155 pub passes: usize,
156 pub identical: bool,
158 pub faithfulness: Faithfulness,
159 pub retention: Option<Retention>,
162}
163
164impl Measurement {
165 pub fn share(&self) -> f64 {
168 if self.middle_chars == 0 {
169 0.0
170 } else {
171 self.handoff_chars as f64 / self.middle_chars as f64
172 }
173 }
174
175 pub fn millis(&self) -> f64 {
176 self.compile_micros as f64 / 1000.0
177 }
178}
179
180pub fn measure(
188 rows: &[Message],
189 dropped: &[Message],
190 session: &str,
191 budget: usize,
192 passes: usize,
193 with_retention: bool,
194) -> Measurement {
195 let limits = Limits::default();
196
197 let started = Instant::now();
198 let first = super::compile(dropped, &Options::new(session, budget));
199 let compile_micros = started.elapsed().as_micros();
200
201 let mut identical = true;
202 for _ in 1..passes.max(1) {
203 if super::compile(dropped, &Options::new(session, budget)) != first {
206 identical = false;
207 }
208 }
209
210 Measurement {
211 session: session.to_string(),
212 messages: dropped.len(),
213 total_messages: rows.len(),
216 drops: dropped.len() < rows.len(),
217 middle_chars: raw_chars(dropped),
218 handoff_chars: first.chars().count(),
219 budget_chars: budget,
220 compile_micros,
221 passes: passes.max(1),
222 identical,
223 faithfulness: faithfulness(&first, rows),
224 retention: with_retention.then(|| retention(&first, &facts(dropped, &limits))),
225 }
226}
227
228pub fn verify(
230 rows: &[Message],
231 dropped: &[Message],
232 session: &str,
233 budget: usize,
234 passes: usize,
235) -> Measurement {
236 measure(rows, dropped, session, budget, passes, false)
237}
238
239pub fn compare(rows: &[Message], dropped: &[Message], session: &str, budget: usize) -> Measurement {
241 measure(rows, dropped, session, budget, 1, true)
242}
243
244pub fn retention(handoff: &str, facts: &Facts) -> Retention {
246 Retention {
247 files: Tally::of(facts.files.iter().map(|(path, _)| path.clone()), handoff),
248 commands: Tally::of(facts.commands.iter().cloned(), handoff),
249 errors: Tally::of(facts.errors.iter().map(|(name, _)| name.clone()), handoff),
250 blocked: Tally::of(
253 facts.blocked.iter().map(|entry| head_of(entry).to_string()),
254 handoff,
255 ),
256 }
257}
258
259fn head_of(entry: &str) -> &str {
260 entry.split(" — ").next().unwrap_or(entry).trim()
261}
262
263fn raw_chars(messages: &[Message]) -> usize {
266 messages
267 .iter()
268 .map(|m| {
269 m.content.as_deref().map(|c| c.chars().count()).unwrap_or(0)
270 + m.tool_calls
271 .iter()
272 .map(|tc| {
273 tc.function.name.chars().count() + tc.function.arguments.chars().count()
274 })
275 .sum::<usize>()
276 })
277 .sum()
278}
279
280struct Checked {
286 fragments: usize,
287 violations: Vec<Violation>,
288}
289
290impl Checked {
291 fn ok(fragments: usize) -> Self {
292 Checked {
293 fragments,
294 violations: Vec::new(),
295 }
296 }
297
298 fn bad(fragments: usize, violation: Violation) -> Self {
299 Checked {
300 fragments,
301 violations: vec![violation],
302 }
303 }
304}
305
306pub fn faithfulness(handoff: &str, rows: &[Message]) -> Faithfulness {
308 let limits = Limits::default();
309 let index: HashMap<u64, &Message> = rows
310 .iter()
311 .filter_map(|m| m.seq.map(|seq| (seq, m)))
312 .collect();
313 let calls: HashMap<&str, String> = rows
316 .iter()
317 .flat_map(|m| m.tool_calls.iter())
318 .filter(|tc| !tc.id.is_empty())
319 .map(|tc| (tc.id.as_str(), call_summary(tc, &limits).0))
320 .collect();
321
322 let mut report = Faithfulness::default();
323 let (_, sections) = split_sections(handoff);
324 let Some((_, log)) = sections.iter().find(|(heading, _)| heading == LOG_HEADING) else {
325 return report;
326 };
327
328 for line in log.lines() {
329 let Some((reference, rest)) = parse_ref(line) else {
330 continue; };
332 report.lines += 1;
333 let Ref::Row(seq) = reference else {
334 report.unreferenced += 1;
337 continue;
338 };
339 let Some(row) = index.get(&seq) else {
340 report.unreferenced += 1;
341 continue;
342 };
343
344 let checked = if let Some(body) = rest.strip_prefix("→ ") {
345 check_call(&seq, line, body, row, &limits)
346 } else if let Some(body) = rest.strip_prefix("← ") {
347 check_result(&seq, line, body, row, &calls)
348 } else if let Some((role, body)) = rest.split_once(": ") {
349 check_role(&seq, line, role, body, row)
350 } else {
351 Checked::bad(
352 0,
353 Violation {
354 at: seq,
355 line: line.to_string(),
356 fragment: rest.to_string(),
357 why: "the line has no shape the renderer produces".to_string(),
358 },
359 )
360 };
361
362 report.fragments += checked.fragments;
363 report.violations.extend(checked.violations);
364 }
365 report
366}
367
368fn parse_ref(line: &str) -> Option<(Ref, &str)> {
370 if let Some(rest) = line.strip_prefix("[#") {
371 let (digits, after) = rest.split_once(']')?;
372 return Some((Ref::Row(digits.parse::<u64>().ok()?), after.trim_start()));
373 }
374 let rest = line.strip_prefix("[t")?;
375 let (digits, after) = rest.split_once(']')?;
376 digits.parse::<usize>().ok()?;
377 Some((Ref::Position, after.trim_start()))
378}
379
380enum Ref {
382 Row(u64),
383 Position,
384}
385
386fn check_role(seq: &u64, line: &str, role: &str, body: &str, row: &Message) -> Checked {
387 let expected = match role {
388 "user" => Role::User,
389 "assistant" => Role::Assistant,
390 other => {
391 return Checked::bad(
392 0,
393 Violation {
394 at: *seq,
395 line: line.to_string(),
396 fragment: other.to_string(),
397 why: "the line names a role the compiler never writes".to_string(),
398 },
399 )
400 }
401 };
402 let fragments = fragments_of(body);
403 let mut violations = Vec::new();
404 if row.role != expected {
405 violations.push(Violation {
406 at: *seq,
407 line: line.to_string(),
408 fragment: role.to_string(),
409 why: format!("row {seq} is a {:?} row, not {role}", row.role),
410 });
411 }
412 let hay = haystack(row, expected);
413 for fragment in &fragments {
414 if !hay.iter().any(|text| text.contains(fragment)) {
415 violations.push(Violation {
416 at: *seq,
417 line: line.to_string(),
418 fragment: fragment.clone(),
419 why: format!("row {seq} does not contain it"),
420 });
421 }
422 }
423 Checked {
424 fragments: fragments.len(),
425 violations,
426 }
427}
428
429fn check_call(seq: &u64, line: &str, body: &str, row: &Message, limits: &Limits) -> Checked {
430 let (name, target) = match body.split_once(": `") {
432 Some((name, rest)) => (name.trim(), rest.strip_suffix('`').unwrap_or(rest)),
433 None => (body.trim(), ""),
434 };
435 let matched = row.tool_calls.iter().any(|tc| {
436 let (call_name, call_target) = call_summary(tc, limits);
437 call_name == name && (target.is_empty() || call_target == target)
438 });
439 if matched {
440 return Checked::ok(1);
441 }
442 Checked::bad(
443 1,
444 Violation {
445 at: *seq,
446 line: line.to_string(),
447 fragment: name.to_string(),
448 why: if row.tool_calls.is_empty() {
449 format!("row {seq} is not a call row")
450 } else {
451 format!("no call on row {seq} names `{name}` with that target")
452 },
453 },
454 )
455}
456
457fn check_result(
458 seq: &u64,
459 line: &str,
460 body: &str,
461 row: &Message,
462 calls: &HashMap<&str, String>,
463) -> Checked {
464 let (name, rest) = match body.split_once(' ') {
465 Some((name, rest)) => (name, rest),
466 None => (body, ""),
467 };
468 let excerpt = rest.split_once(": ").map(|(_, e)| e).unwrap_or("");
469 let fragments = fragments_of(excerpt);
470 let mut violations = Vec::new();
471
472 if let Some(id) = row.tool_call_id.as_deref() {
473 if let Some(paired) = calls.get(id) {
474 if paired != name {
475 violations.push(Violation {
476 at: *seq,
477 line: line.to_string(),
478 fragment: name.to_string(),
479 why: format!("row {seq} answers a call to `{paired}`"),
480 });
481 }
482 }
483 }
484 let hay = haystack(row, Role::Tool);
485 for fragment in &fragments {
486 if !hay.iter().any(|text| text.contains(fragment)) {
487 violations.push(Violation {
488 at: *seq,
489 line: line.to_string(),
490 fragment: fragment.clone(),
491 why: format!("row {seq} does not contain it"),
492 });
493 }
494 }
495 Checked {
496 fragments: fragments.len(),
497 violations,
498 }
499}
500
501fn haystack(row: &Message, role: Role) -> Vec<String> {
513 let raw = row.text_with_pictures();
514 let raw = if role == Role::Assistant {
515 strip_think(&raw)
516 } else {
517 raw.to_string()
518 };
519 let mut out = vec![normalise(&raw)];
520 if let Ok(serde_json::Value::Object(map)) =
521 serde_json::from_str::<serde_json::Value>(raw.trim())
522 {
523 for value in map.values() {
524 let mut strings = Vec::new();
525 collect_strings(value, &mut strings);
526 for text in strings {
527 out.push(normalise(&text));
528 }
529 }
530 }
531 out
532}
533
534fn collect_strings(value: &serde_json::Value, out: &mut Vec<String>) {
535 match value {
536 serde_json::Value::String(text) => out.push(text.clone()),
537 serde_json::Value::Array(items) => items.iter().for_each(|v| collect_strings(v, out)),
538 serde_json::Value::Object(map) => map.values().for_each(|v| collect_strings(v, out)),
539 _ => {}
540 }
541}
542
543fn normalise(text: &str) -> String {
544 clean(text, WHOLE)
545}
546
547fn fragments_of(text: &str) -> Vec<String> {
549 let mut seen: Vec<String> = Vec::new();
550 for fragment in text.split(|c: char| !c.is_alphanumeric()) {
551 if fragment.chars().count() < MIN_FRAGMENT {
552 continue;
553 }
554 if !seen.iter().any(|s| s == fragment) {
555 seen.push(fragment.to_string());
556 }
557 }
558 seen
559}
560
561#[cfg(test)]
562mod tests;