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 middle_chars: usize,
146 pub handoff_chars: usize,
147 pub budget_chars: usize,
148 pub compile_micros: u128,
149 pub passes: usize,
150 pub identical: bool,
152 pub faithfulness: Faithfulness,
153 pub retention: Option<Retention>,
156}
157
158impl Measurement {
159 pub fn share(&self) -> f64 {
162 if self.middle_chars == 0 {
163 0.0
164 } else {
165 self.handoff_chars as f64 / self.middle_chars as f64
166 }
167 }
168
169 pub fn millis(&self) -> f64 {
170 self.compile_micros as f64 / 1000.0
171 }
172}
173
174pub fn measure(
182 rows: &[Message],
183 dropped: &[Message],
184 session: &str,
185 budget: usize,
186 passes: usize,
187 with_retention: bool,
188) -> Measurement {
189 let limits = Limits::default();
190
191 let started = Instant::now();
192 let first = super::compile(dropped, &Options::new(session, budget));
193 let compile_micros = started.elapsed().as_micros();
194
195 let mut identical = true;
196 for _ in 1..passes.max(1) {
197 if super::compile(dropped, &Options::new(session, budget)) != first {
200 identical = false;
201 }
202 }
203
204 Measurement {
205 session: session.to_string(),
206 messages: dropped.len(),
207 middle_chars: raw_chars(dropped),
208 handoff_chars: first.chars().count(),
209 budget_chars: budget,
210 compile_micros,
211 passes: passes.max(1),
212 identical,
213 faithfulness: faithfulness(&first, rows),
214 retention: with_retention.then(|| retention(&first, &facts(dropped, &limits))),
215 }
216}
217
218pub fn verify(
220 rows: &[Message],
221 dropped: &[Message],
222 session: &str,
223 budget: usize,
224 passes: usize,
225) -> Measurement {
226 measure(rows, dropped, session, budget, passes, false)
227}
228
229pub fn compare(rows: &[Message], dropped: &[Message], session: &str, budget: usize) -> Measurement {
231 measure(rows, dropped, session, budget, 1, true)
232}
233
234pub fn retention(handoff: &str, facts: &Facts) -> Retention {
236 Retention {
237 files: Tally::of(facts.files.iter().map(|(path, _)| path.clone()), handoff),
238 commands: Tally::of(facts.commands.iter().cloned(), handoff),
239 errors: Tally::of(facts.errors.iter().map(|(name, _)| name.clone()), handoff),
240 blocked: Tally::of(
243 facts.blocked.iter().map(|entry| head_of(entry).to_string()),
244 handoff,
245 ),
246 }
247}
248
249fn head_of(entry: &str) -> &str {
250 entry.split(" — ").next().unwrap_or(entry).trim()
251}
252
253fn raw_chars(messages: &[Message]) -> usize {
256 messages
257 .iter()
258 .map(|m| {
259 m.content.as_deref().map(|c| c.chars().count()).unwrap_or(0)
260 + m.tool_calls
261 .iter()
262 .map(|tc| {
263 tc.function.name.chars().count() + tc.function.arguments.chars().count()
264 })
265 .sum::<usize>()
266 })
267 .sum()
268}
269
270struct Checked {
276 fragments: usize,
277 violations: Vec<Violation>,
278}
279
280impl Checked {
281 fn ok(fragments: usize) -> Self {
282 Checked {
283 fragments,
284 violations: Vec::new(),
285 }
286 }
287
288 fn bad(fragments: usize, violation: Violation) -> Self {
289 Checked {
290 fragments,
291 violations: vec![violation],
292 }
293 }
294}
295
296pub fn faithfulness(handoff: &str, rows: &[Message]) -> Faithfulness {
298 let limits = Limits::default();
299 let index: HashMap<u64, &Message> = rows
300 .iter()
301 .filter_map(|m| m.seq.map(|seq| (seq, m)))
302 .collect();
303 let calls: HashMap<&str, String> = rows
306 .iter()
307 .flat_map(|m| m.tool_calls.iter())
308 .filter(|tc| !tc.id.is_empty())
309 .map(|tc| (tc.id.as_str(), call_summary(tc, &limits).0))
310 .collect();
311
312 let mut report = Faithfulness::default();
313 let (_, sections) = split_sections(handoff);
314 let Some((_, log)) = sections.iter().find(|(heading, _)| heading == LOG_HEADING) else {
315 return report;
316 };
317
318 for line in log.lines() {
319 let Some((reference, rest)) = parse_ref(line) else {
320 continue; };
322 report.lines += 1;
323 let Ref::Row(seq) = reference else {
324 report.unreferenced += 1;
327 continue;
328 };
329 let Some(row) = index.get(&seq) else {
330 report.unreferenced += 1;
331 continue;
332 };
333
334 let checked = if let Some(body) = rest.strip_prefix("→ ") {
335 check_call(&seq, line, body, row, &limits)
336 } else if let Some(body) = rest.strip_prefix("← ") {
337 check_result(&seq, line, body, row, &calls)
338 } else if let Some((role, body)) = rest.split_once(": ") {
339 check_role(&seq, line, role, body, row)
340 } else {
341 Checked::bad(
342 0,
343 Violation {
344 at: seq,
345 line: line.to_string(),
346 fragment: rest.to_string(),
347 why: "the line has no shape the renderer produces".to_string(),
348 },
349 )
350 };
351
352 report.fragments += checked.fragments;
353 report.violations.extend(checked.violations);
354 }
355 report
356}
357
358fn parse_ref(line: &str) -> Option<(Ref, &str)> {
360 if let Some(rest) = line.strip_prefix("[#") {
361 let (digits, after) = rest.split_once(']')?;
362 return Some((Ref::Row(digits.parse::<u64>().ok()?), after.trim_start()));
363 }
364 let rest = line.strip_prefix("[t")?;
365 let (digits, after) = rest.split_once(']')?;
366 digits.parse::<usize>().ok()?;
367 Some((Ref::Position, after.trim_start()))
368}
369
370enum Ref {
372 Row(u64),
373 Position,
374}
375
376fn check_role(seq: &u64, line: &str, role: &str, body: &str, row: &Message) -> Checked {
377 let expected = match role {
378 "user" => Role::User,
379 "assistant" => Role::Assistant,
380 other => {
381 return Checked::bad(
382 0,
383 Violation {
384 at: *seq,
385 line: line.to_string(),
386 fragment: other.to_string(),
387 why: "the line names a role the compiler never writes".to_string(),
388 },
389 )
390 }
391 };
392 let fragments = fragments_of(body);
393 let mut violations = Vec::new();
394 if row.role != expected {
395 violations.push(Violation {
396 at: *seq,
397 line: line.to_string(),
398 fragment: role.to_string(),
399 why: format!("row {seq} is a {:?} row, not {role}", row.role),
400 });
401 }
402 let hay = haystack(row, expected);
403 for fragment in &fragments {
404 if !hay.iter().any(|text| text.contains(fragment)) {
405 violations.push(Violation {
406 at: *seq,
407 line: line.to_string(),
408 fragment: fragment.clone(),
409 why: format!("row {seq} does not contain it"),
410 });
411 }
412 }
413 Checked {
414 fragments: fragments.len(),
415 violations,
416 }
417}
418
419fn check_call(seq: &u64, line: &str, body: &str, row: &Message, limits: &Limits) -> Checked {
420 let (name, target) = match body.split_once(": `") {
422 Some((name, rest)) => (name.trim(), rest.strip_suffix('`').unwrap_or(rest)),
423 None => (body.trim(), ""),
424 };
425 let matched = row.tool_calls.iter().any(|tc| {
426 let (call_name, call_target) = call_summary(tc, limits);
427 call_name == name && (target.is_empty() || call_target == target)
428 });
429 if matched {
430 return Checked::ok(1);
431 }
432 Checked::bad(
433 1,
434 Violation {
435 at: *seq,
436 line: line.to_string(),
437 fragment: name.to_string(),
438 why: if row.tool_calls.is_empty() {
439 format!("row {seq} is not a call row")
440 } else {
441 format!("no call on row {seq} names `{name}` with that target")
442 },
443 },
444 )
445}
446
447fn check_result(
448 seq: &u64,
449 line: &str,
450 body: &str,
451 row: &Message,
452 calls: &HashMap<&str, String>,
453) -> Checked {
454 let (name, rest) = match body.split_once(' ') {
455 Some((name, rest)) => (name, rest),
456 None => (body, ""),
457 };
458 let excerpt = rest.split_once(": ").map(|(_, e)| e).unwrap_or("");
459 let fragments = fragments_of(excerpt);
460 let mut violations = Vec::new();
461
462 if let Some(id) = row.tool_call_id.as_deref() {
463 if let Some(paired) = calls.get(id) {
464 if paired != name {
465 violations.push(Violation {
466 at: *seq,
467 line: line.to_string(),
468 fragment: name.to_string(),
469 why: format!("row {seq} answers a call to `{paired}`"),
470 });
471 }
472 }
473 }
474 let hay = haystack(row, Role::Tool);
475 for fragment in &fragments {
476 if !hay.iter().any(|text| text.contains(fragment)) {
477 violations.push(Violation {
478 at: *seq,
479 line: line.to_string(),
480 fragment: fragment.clone(),
481 why: format!("row {seq} does not contain it"),
482 });
483 }
484 }
485 Checked {
486 fragments: fragments.len(),
487 violations,
488 }
489}
490
491fn haystack(row: &Message, role: Role) -> Vec<String> {
503 let raw = row.text_with_pictures();
504 let raw = if role == Role::Assistant {
505 strip_think(&raw)
506 } else {
507 raw.to_string()
508 };
509 let mut out = vec![normalise(&raw)];
510 if let Ok(serde_json::Value::Object(map)) =
511 serde_json::from_str::<serde_json::Value>(raw.trim())
512 {
513 for value in map.values() {
514 let mut strings = Vec::new();
515 collect_strings(value, &mut strings);
516 for text in strings {
517 out.push(normalise(&text));
518 }
519 }
520 }
521 out
522}
523
524fn collect_strings(value: &serde_json::Value, out: &mut Vec<String>) {
525 match value {
526 serde_json::Value::String(text) => out.push(text.clone()),
527 serde_json::Value::Array(items) => items.iter().for_each(|v| collect_strings(v, out)),
528 serde_json::Value::Object(map) => map.values().for_each(|v| collect_strings(v, out)),
529 _ => {}
530 }
531}
532
533fn normalise(text: &str) -> String {
534 clean(text, WHOLE)
535}
536
537fn fragments_of(text: &str) -> Vec<String> {
539 let mut seen: Vec<String> = Vec::new();
540 for fragment in text.split(|c: char| !c.is_alphanumeric()) {
541 if fragment.chars().count() < MIN_FRAGMENT {
542 continue;
543 }
544 if !seen.iter().any(|s| s == fragment) {
545 seen.push(fragment.to_string());
546 }
547 }
548 seen
549}
550
551#[cfg(test)]
552mod tests;