#![allow(dead_code)]
use super::*;
use session::{Kind, Source};
pub const PROMPT_TURNS: u32 = 3;
pub const GUARD_CALLS: u32 = 8;
const SLACK_SECS: u64 = 30;
const SETTLE_SECS: u64 = 3600;
pub const SMALL_N: u32 = 30;
#[derive(Debug, Clone, PartialEq)]
pub enum Ev {
Prompt(String),
Tool { id: String, text: String },
Result { id: String, error: bool },
Text(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Harness {
Claude,
Codex,
}
#[derive(Debug, Clone)]
pub struct Transcript {
pub session: String,
pub harness: Harness,
pub evs: Vec<(u64, Ev)>,
}
impl Transcript {
pub fn end(&self) -> u64 {
self.evs.iter().map(|(t, _)| *t).max().unwrap_or(0)
}
pub fn tool_calls(&self) -> u32 {
self.evs.iter().filter(|(_, e)| matches!(e, Ev::Tool { .. })).count() as u32
}
pub fn tool_errors(&self) -> u32 {
self.evs.iter().filter(|(_, e)| matches!(e, Ev::Result { error: true, .. })).count() as u32
}
fn results(&self) -> HashMap<&str, bool> {
self.evs
.iter()
.filter_map(|(_, e)| match e {
Ev::Result { id, error } => Some((id.as_str(), *error)),
_ => None,
})
.collect()
}
}
pub fn iso_secs(ts: &str) -> u64 {
let b = ts.as_bytes();
let num = |a: usize, n: usize| -> Option<i64> { ts.get(a..a + n)?.parse().ok() };
let (Some(y), Some(mo), Some(d), Some(h), Some(mi), Some(s)) =
(num(0, 4), num(5, 2), num(8, 2), num(11, 2), num(14, 2), num(17, 2))
else {
return 0;
};
if b.len() < 19 {
return 0;
}
let y = if mo <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let doy = (153 * (if mo > 2 { mo - 3 } else { mo + 9 }) + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
let secs = days * 86_400 + h * 3600 + mi * 60 + s;
secs.max(0) as u64
}
fn tool_text(input: &Json) -> String {
for k in ["command", "cmd", "file_path", "path", "pattern", "url", "query", "prompt"] {
if let Some(s) = input.get(k).and_then(Json::as_str) {
if !s.trim().is_empty() {
return s.to_owned();
}
}
}
String::new()
}
fn s(j: &Json, key: &str) -> String {
j.get(key).and_then(Json::as_str).unwrap_or("").to_owned()
}
fn result_body(item: &Json) -> String {
match item.get("content") {
Some(Json::Str(t)) => t.clone(),
Some(Json::Arr(a)) => a.iter().map(|x| s(x, "text")).collect::<Vec<_>>().join("\n"),
_ => String::new(),
}
}
fn parse_claude(text: &str, sid: &str, by_name: bool) -> Option<Transcript> {
let mut evs = Vec::new();
let mut identified = by_name;
for line in text.lines() {
if !(line.contains("\"user\"") || line.contains("\"assistant\"")) {
continue;
}
let Ok(j) = parse_json(line) else { continue };
let own = s(&j, "sessionId");
if !own.is_empty() && own != sid {
return None;
}
identified |= own == sid;
let ts = iso_secs(&s(&j, "timestamp"));
let Some(msg) = j.get("message") else { continue };
match s(&j, "type").as_str() {
"user" => {
if matches!(j.get("isMeta"), Some(Json::Bool(true))) {
continue;
}
match msg.get("content") {
Some(Json::Str(t)) if !t.starts_with('<') && !t.trim().is_empty() => {
evs.push((ts, Ev::Prompt(t.clone())));
}
Some(Json::Arr(items)) => {
let mut prose = String::new();
for it in items {
match s(it, "type").as_str() {
"tool_result" => {
let head: String = result_body(it).chars().take(400).collect();
let error = matches!(it.get("is_error"), Some(Json::Bool(true)))
|| (head.starts_with("Exit code") && !head.starts_with("Exit code 0"));
evs.push((ts, Ev::Result { id: s(it, "tool_use_id"), error }));
}
"text" => {
let t = s(it, "text");
if !t.starts_with('<') {
prose.push_str(&t);
prose.push(' ');
}
}
_ => {}
}
}
if !prose.trim().is_empty() && j.get("toolUseResult").is_none() {
evs.push((ts, Ev::Prompt(prose)));
}
}
_ => {}
}
}
"assistant" => {
if let Some(Json::Arr(items)) = msg.get("content") {
for it in items {
match s(it, "type").as_str() {
"tool_use" => {
let input = it.get("input").cloned().unwrap_or(Json::Null);
evs.push((ts, Ev::Tool { id: s(it, "id"), text: tool_text(&input) }));
}
"text" => {
let t = s(it, "text");
if !t.trim().is_empty() {
evs.push((ts, Ev::Text(t)));
}
}
_ => {}
}
}
}
}
_ => {}
}
}
if !identified {
return None;
}
evs.sort_by_key(|(t, _)| *t);
Some(Transcript { session: sid.to_owned(), harness: Harness::Claude, evs })
}
fn codex_error(out: &str) -> Option<bool> {
if let Ok(j) = parse_json(out) {
if let Some(n) = j.get("exit_code").and_then(Json::as_f64) {
return Some(n != 0.0);
}
if let Some(Json::Bool(b)) = j.get("is_error").or_else(|| j.get("isError")) {
return Some(*b);
}
}
for marker in ["Process exited with code ", "Exit code: ", "Exit code "] {
if let Some((_, tail)) = out.split_once(marker) {
let word: String = tail.chars().take_while(|c| c.is_ascii_digit() || *c == '-').collect();
if let Ok(n) = word.parse::<i64>() {
return Some(n != 0);
}
}
}
if out.starts_with("Error:") {
return Some(true);
}
None
}
fn parse_codex(text: &str, sid: &str) -> Option<Transcript> {
let mut evs = Vec::new();
let mut identified = false;
for line in text.lines() {
let Ok(j) = parse_json(line) else { continue };
let ts = iso_secs(&s(&j, "timestamp"));
let Some(p) = j.get("payload") else { continue };
match s(&j, "type").as_str() {
"session_meta" => {
if s(p, "id") != sid {
return None;
}
identified = true;
}
"event_msg" if s(p, "type") == "user_message" => evs.push((ts, Ev::Prompt(s(p, "message")))),
"response_item" => match s(p, "type").as_str() {
"function_call" | "custom_tool_call" => {
let raw = {
let a = s(p, "arguments");
if a.is_empty() { s(p, "input") } else { a }
};
let text = parse_json(&raw)
.map(|j| tool_text(&j))
.ok()
.filter(|t| !t.is_empty())
.unwrap_or(raw);
evs.push((ts, Ev::Tool { id: s(p, "call_id"), text }));
}
"function_call_output" | "custom_tool_call_output" => {
let out = match p.get("output") {
Some(Json::Str(t)) => t.clone(),
Some(other) => json_out(other),
None => String::new(),
};
if let Some(error) = codex_error(&out) {
evs.push((ts, Ev::Result { id: s(p, "call_id"), error }));
}
}
"message" if s(p, "role") == "assistant" => {
if let Some(Json::Arr(a)) = p.get("content") {
let t = a.iter().map(|x| s(x, "text")).collect::<Vec<_>>().join("\n");
if !t.trim().is_empty() {
evs.push((ts, Ev::Text(t)));
}
}
}
_ => {}
},
_ => {}
}
}
if !identified {
return None;
}
evs.sort_by_key(|(t, _)| *t);
Some(Transcript { session: sid.to_owned(), harness: Harness::Codex, evs })
}
pub fn load_transcript(path: &Path, sid: &str) -> Option<Transcript> {
let text = std::fs::read_to_string(path).ok()?;
if text.lines().take(5).any(|l| l.contains("\"session_meta\"")) {
parse_codex(&text, sid)
} else {
parse_claude(&text, sid, file_matches(path, sid))
}
}
fn file_matches(path: &Path, sid: &str) -> bool {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
let Some(stem) = name.strip_suffix(".jsonl") else { return false };
stem == sid || stem.ends_with(&format!("-{sid}"))
}
fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
if depth > 5 {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else { return };
for e in entries.flatten() {
let p = e.path();
match e.file_type() {
Ok(t) if t.is_dir() => walk(&p, depth + 1, out),
Ok(t) if t.is_file() && p.extension().is_some_and(|x| x == "jsonl") => out.push(p),
_ => {}
}
}
}
pub fn default_roots() -> Vec<PathBuf> {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
let mut roots = Vec::new();
let claude = std::env::var_os("CLAUDE_CONFIG_DIR")
.map(PathBuf::from)
.or_else(|| home.as_ref().map(|h| h.join(".claude")));
if let Some(c) = claude {
roots.push(c.join("projects"));
}
let codex = std::env::var_os("CODEX_HOME").map(PathBuf::from).or_else(|| home.map(|h| h.join(".codex")));
if let Some(c) = codex {
roots.push(c.join("sessions"));
}
roots
}
pub fn collect_files(inputs: &[PathBuf]) -> Vec<PathBuf> {
let mut out = Vec::new();
for p in inputs {
if p.is_dir() {
walk(p, 0, &mut out);
} else if p.is_file() {
out.push(p.clone());
}
}
out
}
const CORRECTION_STARTS: &[&str] = &[
"no ", "no,", "no.", "nope", "stop ", "stop,", "wrong", "wtf", "that's not", "thats not", "not that", "no no",
];
const CORRECTION_ANY: &[&str] = &[
"that's not how", "thats not how", "not how it works", "that is wrong", "that's wrong", "thats wrong",
"you broke", "you didn't", "you didnt", "you did not", "why did you", "why would you", "i said",
"i told you", "told you", "once again", "still not", "still doesn't", "still doesnt", "still broken",
"doesn't work", "doesnt work", "not working", "didn't work", "didnt work", "don't do that", "dont do that",
"stop doing", "not what i", "that's not what", "thats not what", "read again", "you ignored", "you skipped",
"you forgot", "undo that", "revert that",
];
pub fn is_correction(prompt: &str) -> bool {
let p = prompt.trim().to_lowercase();
if p.len() < 3 || p.starts_with('<') || p.starts_with('/') {
return false;
}
let head: String = p.chars().take(240).collect();
CORRECTION_STARTS.iter().any(|s| head.starts_with(s)) || CORRECTION_ANY.iter().any(|s| head.contains(s))
}
const STOP: &[&str] = &[
"this", "that", "with", "from", "have", "when", "then", "than", "them", "they", "will", "your", "into",
"does", "done", "also", "only", "each", "just", "like", "some", "such", "there", "which", "while", "would",
"about", "after", "again", "always", "before", "being", "could", "other", "should", "still", "using",
"where", "these", "those", "their", "because", "instead", "first", "never", "every", "check", "found",
"lesson", "seen", "twice", "must", "need", "make", "sure", "used", "uses", "same", "more", "most", "many",
];
fn words(text: &str) -> HashSet<String> {
text.to_lowercase()
.split(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/'))
.map(|w| w.trim_matches(|c: char| c == '-' || c == '.' || c == '/').to_owned())
.filter(|w| w.chars().count() >= 4 && !STOP.contains(&w.as_str()))
.collect()
}
pub fn novel_words(lesson_text: &str, situation: &str) -> Vec<String> {
let have = words(situation);
let mut v: Vec<String> = words(lesson_text).into_iter().filter(|w| !have.contains(w)).collect();
v.sort();
v
}
fn used_words<'a>(novel: &'a [String], haystack: &str) -> Vec<&'a str> {
let h = haystack.to_lowercase();
novel.iter().filter(|w| h.contains(w.as_str())).map(String::as_str).collect()
}
fn one_line(t: &str, n: usize) -> String {
let flat: String = t.split_whitespace().collect::<Vec<_>>().join(" ");
let c: String = flat.chars().take(n).collect();
if c.len() < flat.len() { format!("{c}...") } else { c }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Arm {
Delivered,
Hold,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Label {
Helped,
Misled,
Unused,
Unclear,
}
impl Label {
fn of(name: &str) -> Label {
match name {
"helped" => Label::Helped,
"misled" => Label::Misled,
"unused" => Label::Unused,
_ => Label::Unclear,
}
}
pub fn name(self) -> &'static str {
match self {
Label::Helped => "helped",
Label::Misled => "misled",
Label::Unused => "unused",
Label::Unclear => "unclear",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Delivery {
pub ts: u64,
pub session: String,
pub lesson: String,
pub arm: Arm,
pub source: Source,
}
impl Delivery {
pub fn outcome_id(&self) -> String {
format!("outcome:{}:{}:{}", self.session, self.lesson, self.ts)
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Window {
pub turns: u32,
pub tools: u32,
pub errors: u32,
pub corrected: bool,
pub warned_failed: Option<bool>,
pub repeat_failed: bool,
pub repeat_ok: bool,
pub used: Vec<String>,
pub complete: bool,
pub guard: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Outcome {
pub delivery: Delivery,
pub label: Option<Label>,
pub evidence: String,
pub window: Option<Window>,
}
fn command_key(text: &str) -> String {
text.to_lowercase().split_whitespace().take(2).collect::<Vec<_>>().join(" ")
}
fn prompt_anchor(t: &Transcript, ts: u64) -> Option<(usize, u64)> {
t.evs
.iter()
.enumerate()
.filter(|(_, (at, e))| matches!(e, Ev::Prompt(_)) && at.abs_diff(ts) <= SLACK_SECS)
.min_by_key(|(_, (at, _))| at.abs_diff(ts))
.map(|(i, (at, _))| (i, at.abs_diff(ts)))
}
fn tool_anchor(t: &Transcript, ts: u64) -> Option<(usize, u64)> {
t.evs
.iter()
.enumerate()
.rfind(|(_, (at, e))| matches!(e, Ev::Tool { .. }) && *at <= ts + 2 && ts - (*at).min(ts) <= SLACK_SECS)
.map(|(i, (at, _))| (i, at.abs_diff(ts)))
}
fn quiet(t: &Transcript, now: u64) -> bool {
now.saturating_sub(t.end()) >= SETTLE_SECS
}
fn prompt_window(t: &Transcript, at: usize, novel: &[String], now: u64) -> (Window, String) {
let results = t.results();
let mut w = Window::default();
let mut hay = String::new();
let mut correction = String::new();
let mut ended_inside = true;
for (_, e) in t.evs.iter().skip(at + 1) {
match e {
Ev::Prompt(p) => {
w.turns += 1;
if is_correction(p) && !w.corrected {
w.corrected = true;
correction = one_line(p, 90);
}
if w.turns >= PROMPT_TURNS {
ended_inside = false;
break;
}
}
Ev::Tool { id, text } => {
w.tools += 1;
if results.get(id.as_str()) == Some(&true) {
w.errors += 1;
}
hay.push_str(text);
hay.push('\n');
}
Ev::Text(x) => {
hay.push_str(x);
hay.push('\n');
}
Ev::Result { .. } => {}
}
}
w.used = used_words(novel, &hay).into_iter().map(str::to_owned).collect();
w.complete = !ended_inside || quiet(t, now);
(w, correction)
}
fn guard_window(t: &Transcript, at: usize, novel: &[String], now: u64) -> (Window, String) {
let results = t.results();
let Ev::Tool { id: anchor_id, text: anchor_text } = &t.evs[at].1 else { return (Window::default(), String::new()) };
let key = command_key(anchor_text);
let mut w = Window { guard: true, warned_failed: results.get(anchor_id.as_str()).copied(), ..Window::default() };
let mut hay = String::new();
let mut stopped = false;
let mut unresolved = false;
let mut repeat = String::new();
for (_, e) in t.evs.iter().skip(at + 1) {
match e {
Ev::Prompt(_) => {
stopped = true;
break;
}
Ev::Tool { id, text } => {
if w.tools >= GUARD_CALLS {
break;
}
w.tools += 1;
let result = results.get(id.as_str()).copied();
match result {
Some(true) => w.errors += 1,
Some(false) => {}
None => unresolved = true,
}
if !key.is_empty() && command_key(text) == key {
match result {
Some(true) => {
w.repeat_failed = true;
if repeat.is_empty() {
repeat = one_line(text, 80);
}
}
Some(false) => w.repeat_ok = true,
None => {}
}
}
hay.push_str(text);
hay.push('\n');
}
Ev::Text(x) => {
hay.push_str(x);
hay.push('\n');
}
Ev::Result { .. } => {}
}
}
w.used = used_words(novel, &hay).into_iter().map(str::to_owned).collect();
let aged = quiet(t, now);
w.complete = (w.tools >= GUARD_CALLS || stopped || aged) && (!unresolved || aged);
(w, repeat)
}
pub fn judge_delivery(d: &Delivery, t: Option<&Transcript>, lesson_text: &str, now: u64) -> Outcome {
let out = |label: Option<Label>, evidence: String, window: Option<Window>| Outcome {
delivery: d.clone(),
label,
evidence,
window,
};
let held = d.arm == Arm::Hold;
let unclear = |why: String| out(if held { None } else { Some(Label::Unclear) }, why, None);
let Some(t) = t else { return unclear("no transcript found for this session".into()) };
let p = prompt_anchor(t, d.ts);
let g = tool_anchor(t, d.ts);
let use_guard = match d.source {
Source::Guard => true,
Source::Prompt => false,
Source::Unknown => match (p, g) {
(Some((_, pd)), Some((_, gd))) => gd < pd,
(None, Some(_)) => true,
_ => false,
},
};
let situation = |at: usize| match &t.evs[at].1 {
Ev::Prompt(x) => x.clone(),
Ev::Tool { text, .. } => text.clone(),
_ => String::new(),
};
if use_guard {
let Some((at, _)) = g else { return unclear("no tool call near the delivery in the transcript".into()) };
let novel = novel_words(lesson_text, &situation(at));
let (w, repeat) = guard_window(t, at, &novel, now);
let n = w.tools;
let (name, case) = trust::guard_verdict(w.complete, w.repeat_failed, w.warned_failed, w.errors, n);
let label = Label::of(name);
let evidence = match case {
"open" => format!("window still open: {n} of {GUARD_CALLS} tool calls seen"),
"repeat_failed" => format!("the warned action failed again: `{repeat}`"),
"failed_once" => {
let how = if w.repeat_ok { "it was retried and passed" } else { "it was not repeated" };
format!("warned call failed once; {how}, and the next {n} calls ran clean")
}
"clean" => format!("the warned call succeeded and the next {n} calls ran clean"),
"no_result" => "the warned call has no recorded result".to_string(),
_ => format!("{} of the next {n} calls failed, none like the warned one", w.errors),
};
return out(if held { None } else { Some(label) }, evidence, Some(w));
}
let Some((at, _)) = p else { return unclear("no user turn near the delivery in the transcript".into()) };
let novel = novel_words(lesson_text, &situation(at));
let (w, correction) = prompt_window(t, at, &novel, now);
let acted = trust::acted(w.used.len(), novel.len());
let shown = w.used.iter().take(3).cloned().collect::<Vec<_>>().join(", ");
let (name, case) = trust::prompt_verdict(w.complete, w.corrected, acted);
let label = Label::of(name);
let evidence = match case {
"open" => format!("window still open: {} of {PROMPT_TURNS} user turns seen", w.turns),
"acted_then_corrected" => format!("acted on it ({shown}), then the user corrected: \"{correction}\""),
"acted" => format!("acted on it ({shown}); no correction in {} user turns", w.turns),
"corrected_anyway" => format!("not acted on (no lesson words in the next calls); a correction followed anyway: \"{correction}\""),
_ => format!("not acted on: no lesson words in the next {} calls; no correction", w.tools),
};
out(if held { None } else { Some(label) }, evidence, Some(w))
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Rates {
pub windows: u32,
pub corrected: u32,
pub tools: u32,
pub errors: u32,
}
impl Rates {
pub fn correction_rate(&self) -> Option<f64> {
(self.windows > 0).then(|| self.corrected as f64 / self.windows as f64)
}
pub fn error_rate(&self) -> Option<f64> {
(self.tools > 0).then(|| self.errors as f64 / self.tools as f64)
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Comparison {
pub lessons: Vec<String>,
pub prompt_delivered: Rates,
pub prompt_held: Rates,
pub guard_delivered: Rates,
pub guard_held: Rates,
}
pub fn two_proportion_z(x1: u32, n1: u32, x2: u32, n2: u32) -> Option<f64> {
if n1 == 0 || n2 == 0 {
return None;
}
let (p1, p2) = (x1 as f64 / n1 as f64, x2 as f64 / n2 as f64);
let p = (x1 + x2) as f64 / (n1 + n2) as f64;
let se = (p * (1.0 - p) * (1.0 / n1 as f64 + 1.0 / n2 as f64)).sqrt();
(se > 0.0).then(|| (p1 - p2) / se)
}
fn add(r: &mut Rates, w: &Window, guard: bool) {
r.windows += 1;
if guard {
r.tools += w.tools;
r.errors += w.errors;
} else if w.corrected {
r.corrected += 1;
}
}
pub fn compare(outcomes: &[Outcome]) -> Comparison {
let done = |o: &&Outcome| o.window.as_ref().is_some_and(|w| w.complete);
let both: Vec<String> = {
let has = |arm: Arm, lesson: &str| {
outcomes.iter().filter(done).any(|o| o.delivery.arm == arm && o.delivery.lesson == lesson)
};
let mut v: Vec<String> = outcomes
.iter()
.filter(done)
.map(|o| o.delivery.lesson.clone())
.filter(|l| has(Arm::Delivered, l) && has(Arm::Hold, l))
.collect();
v.sort();
v.dedup();
v
};
let mut c = Comparison { lessons: both.clone(), ..Comparison::default() };
for o in outcomes.iter().filter(done) {
if !both.contains(&o.delivery.lesson) {
continue;
}
let w = o.window.as_ref().unwrap();
let guard = w.guard;
let target = match (o.delivery.arm, guard) {
(Arm::Delivered, false) => &mut c.prompt_delivered,
(Arm::Hold, false) => &mut c.prompt_held,
(Arm::Delivered, true) => &mut c.guard_delivered,
(Arm::Hold, true) => &mut c.guard_held,
};
add(target, w, guard);
}
c
}
#[derive(Debug, Clone)]
pub struct Options {
pub since: u64,
pub now: u64,
pub transcripts: Vec<PathBuf>,
}
#[derive(Debug, Clone, Default)]
pub struct Report {
pub outcomes: Vec<Outcome>,
pub comparison: Comparison,
pub transcripts: u32,
pub base_error_rate: Option<f64>,
pub session_end: HashMap<String, u64>,
}
impl Report {
pub fn count(&self, label: Label) -> usize {
self.outcomes.iter().filter(|o| o.label == Some(label)).count()
}
pub fn held(&self) -> usize {
self.outcomes.iter().filter(|o| o.delivery.arm == Arm::Hold).count()
}
pub fn delivered(&self) -> usize {
self.outcomes.iter().filter(|o| o.delivery.arm == Arm::Delivered).count()
}
}
pub fn deliveries(store: &Path, since: u64) -> Vec<Delivery> {
let mut out: Vec<Delivery> = Vec::new();
for r in session::records(store) {
let arm = match r.kind {
Kind::Delivered => Arm::Delivered,
Kind::Held => Arm::Hold,
Kind::Reminded => continue,
};
if r.ts < since || out.iter().any(|d| d.session == r.session && d.lesson == r.lesson) {
continue;
}
out.push(Delivery { ts: r.ts, session: r.session, lesson: r.lesson, arm, source: r.source });
}
out
}
fn lesson_texts(store: &Path) -> HashMap<String, String> {
load(&store.to_path_buf())
.unwrap_or_default()
.into_iter()
.map(|d| (d.id.clone(), format!("{} {} {} {} {}", d.title, d.when, d.found, d.how, d.tags.replace(';', " "))))
.collect()
}
pub fn evaluate(store: &Path, opts: &Options) -> Report {
let ds = deliveries(store, opts.since);
let inputs = if opts.transcripts.is_empty() { default_roots() } else { opts.transcripts.clone() };
let explicit = !opts.transcripts.is_empty();
let files = collect_files(&inputs);
let lessons = lesson_texts(store);
let mut cache: HashMap<String, Option<Transcript>> = HashMap::new();
let mut report = Report::default();
let (mut calls, mut errors) = (0u32, 0u32);
for d in &ds {
if !cache.contains_key(&d.session) {
let found = files
.iter()
.filter(|f| file_matches(f, &d.session) || (explicit && f.is_file() && opts.transcripts.contains(f)))
.find_map(|f| load_transcript(f, &d.session));
if let Some(t) = &found {
report.transcripts += 1;
report.session_end.insert(d.session.clone(), t.end());
calls += t.tool_calls();
errors += t.tool_errors();
}
cache.insert(d.session.clone(), found);
}
let text = lessons.get(&d.lesson).map(String::as_str).unwrap_or("");
report.outcomes.push(judge_delivery(d, cache[&d.session].as_ref(), text, opts.now));
}
report.comparison = compare(&report.outcomes);
report.base_error_rate = (calls > 0).then(|| errors as f64 / calls as f64);
report
}
#[derive(Debug, Default, PartialEq)]
pub struct Applied {
pub hits: u32,
pub misses: u32,
pub already: u32,
pub explicit: u32,
pub errors: Vec<String>,
}
fn explicit_marks(store: &Path) -> Vec<(String, u64)> {
journal::read(store)
.unwrap_or_default()
.lines()
.filter(|l| l.contains("\"hit\"") || l.contains("\"miss\""))
.filter_map(|l| parse_json(l).ok())
.filter(|v| matches!(v.get("kind").and_then(Json::as_str), Some("hit" | "miss")))
.filter(|v| !v.get("outcome_id").and_then(Json::as_str).unwrap_or("").starts_with("outcome:"))
.filter_map(|v| Some((v.get("id")?.as_str()?.to_owned(), v.get("ts").and_then(Json::as_f64)? as u64)))
.collect()
}
pub fn apply(store: &Path, report: &Report) -> Applied {
let marks = explicit_marks(store);
let mut a = Applied::default();
let path = store.to_path_buf();
for o in &report.outcomes {
let kind = match o.label {
Some(Label::Helped) if o.delivery.arm == Arm::Delivered => "hit",
Some(Label::Misled) if o.delivery.arm == Arm::Delivered => "miss",
_ => continue,
};
let d = &o.delivery;
let until = report.session_end.get(&d.session).copied().unwrap_or(d.ts) + 300;
if marks.iter().any(|(id, ts)| *id == d.lesson && *ts >= d.ts && *ts <= until) {
a.explicit += 1;
continue;
}
match op_mark(&path, kind, &d.lesson, &format!("observed: {}", o.evidence), &d.outcome_id()) {
Ok(m) if m.starts_with("outcome already recorded") => a.already += 1,
Ok(_) if kind == "hit" => a.hits += 1,
Ok(_) => a.misses += 1,
Err(e) => a.errors.push(format!("{}: {e}", d.lesson)),
}
}
a
}
pub fn parse_since(v: &str) -> Result<u64, String> {
let v = v.trim();
if v == "all" {
return Ok(36_500 * 86_400);
}
let (num, unit) = match v.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
Some((i, _)) => v.split_at(i),
None => (v, "d"),
};
let n: u64 = num.parse().map_err(|_| format!("--since needs a duration like 7d, 36h or 90m, not {v:?}"))?;
let mult = match unit {
"m" => 60,
"h" => 3600,
"d" => 86_400,
"w" => 604_800,
_ => return Err(format!("--since needs a duration like 7d, 36h or 90m, not {v:?}")),
};
Ok(n * mult)
}
fn pct(x: f64) -> String {
format!("{:.1}%", x * 100.0)
}
fn compare_lines(label: &str, unit: &str, d: &Rates, h: &Rates, guard: bool) -> Option<String> {
let (nd, nh) = if guard { (d.tools, h.tools) } else { (d.windows, h.windows) };
if nd == 0 && nh == 0 {
return None;
}
let (rd, rh, xd, xh) = if guard {
(d.error_rate(), h.error_rate(), d.errors, h.errors)
} else {
(d.correction_rate(), h.correction_rate(), d.corrected, h.corrected)
};
let show = |r: Option<f64>, x: u32, n: u32| r.map_or("n/a".to_owned(), |r| format!("{} ({x}/{n})", pct(r)));
let _ = unit;
let mut line = format!(" {label}: delivered {} vs withheld {}", show(rd, xd, nd), show(rh, xh, nh));
if let (Some(a), Some(b)) = (rd, rh) {
let z = two_proportion_z(xd, nd, xh, nh).map_or("z n/a".to_owned(), |z| format!("z {z:.2}"));
line.push_str(&format!("\n difference {:+.1} points ({z})", (a - b) * 100.0));
}
if nd < SMALL_N || nh < SMALL_N {
line.push_str(&format!(
"\n caveat: only {nd} delivered and {nh} withheld observations (under {SMALL_N} each). Read it as a direction, not a result."
));
}
Some(line)
}
fn short(s: &str) -> &str {
s.get(..8).unwrap_or(s)
}
pub fn comparison_text(r: &Report) -> String {
let c = &r.comparison;
let lines: Vec<String> = [
compare_lines("prompt, corrections in the next 3 turns", "", &c.prompt_delivered, &c.prompt_held, false),
compare_lines("tripwire, failed share of the next 8 calls", "", &c.guard_delivered, &c.guard_held, true),
]
.into_iter()
.flatten()
.collect();
let mut o = String::new();
if !lines.is_empty() {
o.push_str(&format!(
"delivered vs withheld, same lessons ({} lesson(s) with both arms)\n{}\n",
c.lessons.len(),
lines.join("\n")
));
if let Some(b) = r.base_error_rate {
o.push_str(&format!(" base failure rate over all tool calls read: {}\n", pct(b)));
}
} else if r.held() > 0 {
o.push_str("delivered vs withheld: no lesson has a finished window in both arms yet\n");
}
o
}
pub fn render_text(r: &Report, days_label: &str, applied: Option<&Applied>) -> String {
let mut o = format!(
"instinct outcomes: {days_label}, {} delivered, {} withheld, {} transcript(s) read\n",
r.delivered(),
r.held(),
r.transcripts
);
o.push_str(&format!(
" helped {} . misled {} . unused {} . unclear {}\n",
r.count(Label::Helped),
r.count(Label::Misled),
r.count(Label::Unused),
r.count(Label::Unclear)
));
for x in r.outcomes.iter().filter(|x| x.label.is_some()) {
let hook = match x.delivery.source {
Source::Prompt => "prompt",
Source::Guard => "guard ",
Source::Unknown => "? ",
};
o.push_str(&format!(
" {:<7} {} {} {} {}\n",
x.label.map_or("", Label::name),
x.delivery.lesson,
hook,
short(&x.delivery.session),
x.evidence
));
}
o.push_str(&comparison_text(r));
match applied {
Some(a) => {
o.push_str(&format!(
"applied: {} hit(s), {} miss(es) recorded; {} already recorded; {} skipped because the agent marked them itself\n",
a.hits, a.misses, a.already, a.explicit
));
for e in &a.errors {
o.push_str(&format!(" could not record {e}\n"));
}
}
None => o.push_str("dry run: nothing written. Add --apply to record hits and misses.\n"),
}
o
}
fn jstr(s: &str) -> String {
format!("\"{}\"", escape_json(s))
}
fn rates_json(r: &Rates) -> String {
format!(
"{{\"windows\":{},\"corrected\":{},\"tool_calls\":{},\"errors\":{}}}",
r.windows, r.corrected, r.tools, r.errors
)
}
pub fn render_json(r: &Report, applied: Option<&Applied>) -> String {
let rows: Vec<String> = r
.outcomes
.iter()
.map(|x| {
let d = &x.delivery;
let hook = match d.source {
Source::Prompt => "prompt",
Source::Guard => "guard",
Source::Unknown => "unknown",
};
format!(
"{{\"session\":{},\"lesson\":{},\"ts\":{},\"hook\":\"{hook}\",\"arm\":\"{}\",\"label\":{},\"evidence\":{},\"outcome_id\":{}}}",
jstr(&d.session),
jstr(&d.lesson),
d.ts,
if d.arm == Arm::Hold { "hold" } else { "delivered" },
x.label.map_or("null".to_owned(), |l| jstr(l.name())),
jstr(&x.evidence),
jstr(&d.outcome_id())
)
})
.collect();
let c = &r.comparison;
let z = |a: &Rates, b: &Rates, guard: bool| {
let v = if guard {
two_proportion_z(a.errors, a.tools, b.errors, b.tools)
} else {
two_proportion_z(a.corrected, a.windows, b.corrected, b.windows)
};
v.map_or("null".to_owned(), |v| format!("{v:.3}"))
};
let applied = applied.map_or("null".to_owned(), |a| {
format!(
"{{\"hits\":{},\"misses\":{},\"already\":{},\"explicit\":{},\"errors\":{}}}",
a.hits,
a.misses,
a.already,
a.explicit,
a.errors.len()
)
});
format!(
"{{\"delivered\":{},\"withheld\":{},\"transcripts\":{},\"helped\":{},\"misled\":{},\"unused\":{},\"unclear\":{},\"base_error_rate\":{},\"comparison\":{{\"lessons\":{},\"prompt\":{{\"delivered\":{},\"withheld\":{},\"z\":{}}},\"guard\":{{\"delivered\":{},\"withheld\":{},\"z\":{}}},\"small_n\":{SMALL_N}}},\"applied\":{applied},\"outcomes\":[{}]}}",
r.delivered(),
r.held(),
r.transcripts,
r.count(Label::Helped),
r.count(Label::Misled),
r.count(Label::Unused),
r.count(Label::Unclear),
r.base_error_rate.map_or("null".to_owned(), |b| format!("{b:.4}")),
c.lessons.len(),
rates_json(&c.prompt_delivered),
rates_json(&c.prompt_held),
z(&c.prompt_delivered, &c.prompt_held, false),
rates_json(&c.guard_delivered),
rates_json(&c.guard_held),
z(&c.guard_delivered, &c.guard_held, true),
rows.join(",")
)
}
pub fn comparison_json(r: &Report) -> String {
let c = &r.comparison;
let z = |v: Option<f64>| v.map_or("null".to_owned(), |v| format!("{v:.3}"));
format!(
"{{\"delivered\":{},\"withheld\":{},\"lessons\":{},\"prompt\":{{\"delivered\":{},\"withheld\":{},\"z\":{}}},\"guard\":{{\"delivered\":{},\"withheld\":{},\"z\":{}}},\"base_error_rate\":{},\"small_n\":{SMALL_N}}}",
r.delivered(),
r.held(),
c.lessons.len(),
rates_json(&c.prompt_delivered),
rates_json(&c.prompt_held),
z(two_proportion_z(c.prompt_delivered.corrected, c.prompt_delivered.windows, c.prompt_held.corrected, c.prompt_held.windows)),
rates_json(&c.guard_delivered),
rates_json(&c.guard_held),
z(two_proportion_z(c.guard_delivered.errors, c.guard_delivered.tools, c.guard_held.errors, c.guard_held.tools)),
r.base_error_rate.map_or("null".to_owned(), |b| format!("{b:.4}")),
)
}
fn since_label(v: &str) -> String {
match v.trim() {
"all" => "all recorded time".to_string(),
d => format!("last {d}"),
}
}
pub fn run(store: &Path, a: &Args) -> Result<String, String> {
let since_secs = parse_since(a.opt("since").filter(|v| !v.is_empty()).unwrap_or("7d"))?;
let mut named: Vec<PathBuf> = a.pos.iter().map(PathBuf::from).collect();
for key in ["apply", "json"] {
if let Some(v) = a.opt(key).filter(|v| !v.is_empty()) {
named.push(PathBuf::from(v));
}
}
let now = now_secs();
let opts = Options { since: now.saturating_sub(since_secs), now, transcripts: named };
let report = evaluate(store, &opts);
let applied = a.flag("apply").then(|| apply(store, &report));
let label = since_label(a.opt("since").filter(|v| !v.is_empty()).unwrap_or("7d"));
Ok(if a.flag("json") { render_json(&report, applied.as_ref()) } else { render_text(&report, &label, applied.as_ref()) })
}
#[cfg(test)]
mod tests {
use super::*;
fn d(arm: Arm, source: Source, ts: u64) -> Delivery {
Delivery { ts, session: "s".into(), lesson: "in-l".into(), arm, source }
}
fn claude(lines: &[(u64, Ev)]) -> Transcript {
Transcript { session: "s".into(), harness: Harness::Claude, evs: lines.to_vec() }
}
fn tool(id: &str, text: &str) -> Ev {
Ev::Tool { id: id.into(), text: text.into() }
}
fn res(id: &str, error: bool) -> Ev {
Ev::Result { id: id.into(), error }
}
const LESSON: &str = "Registry outage fetch fails vendored dir";
const LATE: u64 = 10_000_000;
#[test]
fn a_window_that_is_still_open_is_unclear() {
let t = claude(&[
(100, Ev::Prompt("the registry is down".into())),
(110, tool("a", "cargo fetch vendored")),
(111, res("a", false)),
(200, Ev::Prompt("ok".into())),
]);
let o = judge_delivery(&d(Arm::Delivered, Source::Prompt, 101), Some(&t), LESSON, 260);
assert_eq!(o.label, Some(Label::Unclear), "{}", o.evidence);
assert!(o.evidence.contains("1 of 3"), "{}", o.evidence);
let o = judge_delivery(&d(Arm::Delivered, Source::Prompt, 101), Some(&t), LESSON, LATE);
assert_eq!(o.label, Some(Label::Helped), "{}", o.evidence);
}
#[test]
fn words_already_in_the_prompt_do_not_count_as_use() {
let t = claude(&[
(100, Ev::Prompt("registry outage again".into())),
(110, tool("a", "echo registry outage")),
(111, res("a", false)),
]);
let o = judge_delivery(&d(Arm::Delivered, Source::Prompt, 101), Some(&t), "Registry outage", LATE);
assert_eq!(o.label, Some(Label::Unused), "{}", o.evidence);
}
#[test]
fn a_correction_without_use_is_unused_not_misled() {
let t = claude(&[
(100, Ev::Prompt("fix the build".into())),
(110, tool("a", "ls")),
(111, res("a", false)),
(200, Ev::Prompt("no, that's wrong".into())),
]);
let o = judge_delivery(&d(Arm::Delivered, Source::Prompt, 101), Some(&t), LESSON, LATE);
assert_eq!(o.label, Some(Label::Unused), "{}", o.evidence);
assert!(o.window.unwrap().corrected);
}
#[test]
fn a_withheld_delivery_gets_a_window_and_no_label() {
let t = claude(&[(100, Ev::Prompt("fix the build".into())), (110, tool("a", "ls")), (111, res("a", true))]);
let o = judge_delivery(&d(Arm::Hold, Source::Prompt, 101), Some(&t), LESSON, LATE);
assert_eq!(o.label, None);
assert_eq!(o.window.unwrap().errors, 1);
}
#[test]
fn tripwire_window_is_eight_calls_and_excludes_the_warned_call() {
let mut evs = vec![(100, Ev::Prompt("go".into())), (110, tool("w", "pkill -f x")), (111, res("w", true))];
for i in 0..10u64 {
evs.push((120 + i * 2, tool(&format!("c{i}"), &format!("echo {i}"))));
evs.push((121 + i * 2, res(&format!("c{i}"), i == 9)));
}
let t = claude(&evs);
let o = judge_delivery(&d(Arm::Delivered, Source::Guard, 111), Some(&t), LESSON, LATE);
let w = o.window.unwrap();
assert_eq!((w.tools, w.errors), (8, 0), "the 10th call is outside the window");
assert_eq!(o.label, Some(Label::Helped), "{}", o.evidence);
}
#[test]
fn unknown_source_picks_the_nearer_anchor() {
let t = claude(&[
(100, Ev::Prompt("go".into())),
(500, tool("w", "pkill -f x")),
(501, res("w", false)),
(502, tool("n", "ls")),
(503, res("n", false)),
]);
let o = judge_delivery(&d(Arm::Delivered, Source::Unknown, 501), Some(&t), LESSON, LATE);
assert!(o.window.unwrap().guard);
let o = judge_delivery(&d(Arm::Delivered, Source::Unknown, 101), Some(&t), LESSON, LATE);
assert!(!o.window.unwrap().guard);
}
#[test]
fn two_proportion_z_matches_the_textbook_value() {
let z = two_proportion_z(30, 100, 20, 100).unwrap();
assert!((z - 1.63299).abs() < 1e-4, "{z}");
assert!((two_proportion_z(20, 100, 30, 100).unwrap() + 1.63299).abs() < 1e-4);
assert_eq!(two_proportion_z(0, 0, 1, 2), None);
assert_eq!(two_proportion_z(0, 10, 0, 10), None, "no spread, no z");
assert_eq!(two_proportion_z(5, 5, 5, 5), None);
}
fn done(arm: Arm, lesson: &str, guard: bool, corrected: bool, tools: u32, errors: u32) -> Outcome {
let source = if guard { Source::Guard } else { Source::Prompt };
Outcome {
delivery: Delivery { ts: 1, session: "s".into(), lesson: lesson.into(), arm, source },
label: None,
evidence: String::new(),
window: Some(Window { complete: true, guard, corrected, tools, errors, ..Window::default() }),
}
}
#[test]
fn compare_uses_only_lessons_present_in_both_arms_and_finished_windows() {
let mut os = vec![];
for c in [true, false, false, false] {
os.push(done(Arm::Delivered, "A", false, c, 0, 0));
}
for c in [true, false] {
os.push(done(Arm::Hold, "A", false, c, 0, 0));
}
os.push(done(Arm::Delivered, "B", false, true, 0, 0));
os.push(done(Arm::Delivered, "C", true, false, 8, 1));
os.push(done(Arm::Hold, "C", true, false, 8, 3));
let mut open = done(Arm::Hold, "A", false, true, 0, 0);
open.window.as_mut().unwrap().complete = false;
os.push(open);
let c = compare(&os);
assert_eq!(c.lessons, vec!["A".to_string(), "C".to_string()]);
assert_eq!((c.prompt_delivered.windows, c.prompt_delivered.corrected), (4, 1));
assert_eq!((c.prompt_held.windows, c.prompt_held.corrected), (2, 1));
assert_eq!((c.guard_delivered.tools, c.guard_delivered.errors), (8, 1));
assert_eq!((c.guard_held.tools, c.guard_held.errors), (8, 3));
assert_eq!(c.prompt_delivered.correction_rate(), Some(0.25));
assert_eq!(c.guard_held.error_rate(), Some(0.375));
}
#[test]
fn since_all_reads_as_all_recorded_time() {
assert_eq!(since_label("all"), "all recorded time");
assert_eq!(since_label("7d"), "last 7d");
let text = render_text(&Report::default(), &since_label("all"), None);
assert!(text.contains("instinct outcomes: all recorded time,"), "{text}");
assert!(!text.contains("last all"), "{text}");
}
#[test]
fn the_report_prints_the_difference_counts_and_the_small_n_caveat() {
let os = vec![done(Arm::Delivered, "A", false, false, 0, 0), done(Arm::Hold, "A", false, true, 0, 0)];
let r = Report { comparison: compare(&os), outcomes: os, ..Report::default() };
let text = render_text(&r, "last 7d", None);
assert!(text.contains("delivered 0.0% (0/1) vs withheld 100.0% (1/1)"), "{text}");
assert!(text.contains("difference -100.0 points"), "{text}");
assert!(text.contains("only 1 delivered and 1 withheld observations (under 30 each)"), "{text}");
}
#[test]
fn durations_and_timestamps_parse() {
assert_eq!(parse_since("7d").unwrap(), 7 * 86_400);
assert_eq!(parse_since("36h").unwrap(), 36 * 3600);
assert_eq!(parse_since("90m").unwrap(), 5400);
assert_eq!(parse_since("2w").unwrap(), 14 * 86_400);
assert_eq!(parse_since("3").unwrap(), 3 * 86_400);
assert!(parse_since("soon").is_err());
assert_eq!(iso_secs("1970-01-02T00:00:01.500Z"), 86_401);
assert_eq!(iso_secs("2026-11-25T10:00:00Z"), 1_795_600_800);
assert_eq!(iso_secs("nonsense"), 0);
}
#[test]
fn the_correction_detector_is_strict() {
assert!(is_correction("no, that's wrong"));
assert!(is_correction("You didn't run the tests"));
assert!(!is_correction("now add a test for it"));
assert!(!is_correction("<task-notification> no ... </task-notification>"));
assert!(!is_correction("/clear"));
}
}