use std::io::Read;
use chrono::{NaiveDate, Utc};
use serde_json::{json, Value};
use crate::model::{Claim, Ledger, Outcome, Resolution, ResolvedBy};
use crate::report::{ReportData, Verdict};
use crate::store;
use crate::untrusted;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Event {
SessionStart,
UserPrompt,
PostTool,
PreTool,
PostToolFailure,
Stop,
}
impl Event {
fn name(self) -> &'static str {
match self {
Event::SessionStart => "SessionStart",
Event::UserPrompt => "UserPromptSubmit",
Event::PostTool => "PostToolUse",
Event::PreTool => "PreToolUse",
Event::PostToolFailure => "PostToolUseFailure",
Event::Stop => "Stop",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct HookStat {
pub event: &'static str,
pub last: Option<String>,
pub fires: u64,
pub model_bytes: u64,
}
const ALL_EVENTS: [Event; 6] = [
Event::SessionStart,
Event::UserPrompt,
Event::PreTool,
Event::PostTool,
Event::PostToolFailure,
Event::Stop,
];
fn stat_file(event: Event) -> Option<std::path::PathBuf> {
dirs_counters().map(|d| d.join(format!("hook-{}.stat", event.name())))
}
fn read_stat(event: Event) -> HookStat {
let text = stat_file(event)
.and_then(|f| std::fs::read_to_string(f).ok())
.unwrap_or_default();
let mut it = text.split_whitespace();
let fires = it.next().and_then(|x| x.parse().ok()).unwrap_or(0);
let model_bytes = it.next().and_then(|x| x.parse().ok()).unwrap_or(0);
HookStat {
event: event.name(),
last: it.next().map(str::to_string),
fires,
model_bytes,
}
}
fn note(event: Event, model_bytes: usize, fired: bool) {
let Some(file) = stat_file(event) else {
return;
};
let mut st = read_stat(event);
if fired {
st.fires += 1;
st.last = Some(Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true));
}
st.model_bytes += model_bytes as u64;
if let Some(dir) = file.parent() {
let _ = std::fs::create_dir_all(dir);
}
let tmp = file.with_extension("stat.tmp");
let line = format!(
"{} {} {}\n",
st.fires,
st.model_bytes,
st.last.as_deref().unwrap_or("-")
);
if std::fs::write(&tmp, line).is_ok() {
let _ = std::fs::rename(&tmp, &file);
}
}
pub fn hook_stats() -> Vec<HookStat> {
ALL_EVENTS.iter().map(|e| read_stat(*e)).collect()
}
const PROTOCOL_MAX_BYTES: usize = 6000;
fn owner_protocol(ledger_path: &std::path::Path) -> Option<String> {
let file = ledger_path.with_file_name("protocol.md");
let text = std::fs::read_to_string(&file).ok()?;
let text = text.trim();
if text.is_empty() {
return None;
}
let mut cut = text.len().min(PROTOCOL_MAX_BYTES);
while !text.is_char_boundary(cut) {
cut -= 1;
}
let tail = if cut < text.len() {
format!("\n(cut at {PROTOCOL_MAX_BYTES} bytes of {})", text.len())
} else {
String::new()
};
Some(format!(
"⟢ Standing protocol on this machine, set by its owner ({}):\n{}{tail}",
file.display(),
&text[..cut]
))
}
const MIN_N: usize = 6;
const DEFAULT_EVERY: u64 = 7;
const DEFAULT_LOCK_WAIT_MS: u64 = 2000;
const VERSION: &str = env!("CARGO_PKG_VERSION");
fn env_usize(key: &str, default: u64) -> u64 {
std::env::var(key)
.ok()
.and_then(|v| v.parse().ok())
.filter(|n| *n > 0)
.unwrap_or(default)
}
fn standing_line(d: &ReportData) -> Option<String> {
if d.evidence_n < MIN_N {
return None;
}
let n = d.evidence_n;
Some(match d.verdict {
Verdict::InsufficientData => return None,
Verdict::Withheld => format!(
"NO VERDICT: {} of your {} settled claims {}, so no reading of your {n} graded calls can be trusted. Resolve a claim when it answers, even when it went against you; void only a question that stopped making sense, and reword only before the answer is in sight.",
d.voids.edited().0, d.voids.settled, d.voids.edited().1
),
Verdict::NoEvidenceOfMiscalibration => format!(
"no miscalibration found across {n} graded calls — which is not proof you are calibrated, only that nothing shows otherwise"
),
Verdict::CalibratedButUninformative => format!(
"right on average across {n} calls, but your confidence does not separate the ones that come true — spread your probabilities out"
),
Verdict::Overconfident => format!(
"OVERCONFIDENT ({n} graded): right {} of the time while claiming about {}. Add slack.",
pct(d.accuracy),
pct(d.mean_confidence)
),
Verdict::Underconfident => format!(
"UNDERCONFIDENT ({n} graded): right {} while claiming about {}. Trust your sure calls more.",
pct(d.accuracy),
pct(d.mean_confidence)
),
Verdict::BiasedYes => format!(
"LEANS YES ({n} graded): you predict things happen more often than they do."
),
Verdict::BiasedNo => format!(
"LEANS NO ({n} graded): you predict things don't happen more often than holds up."
),
Verdict::MiscalibratedBothWays => format!(
"MISCALIBRATED BOTH WAYS ({n} graded): too sure at one end of your range and not sure enough at the other. Shading everything one way will not help."
),
})
}
fn pct(v: Option<f64>) -> String {
v.map_or_else(|| "—".into(), |x| format!("{:.0}%", x * 100.0))
}
fn worst_kind(d: &ReportData) -> Option<String> {
let ns = d.group_by.as_deref()?;
let threshold = d.kind_alarm_threshold?;
let (row, e) = d
.by_kind
.iter()
.filter_map(|t| t.eprocess.map(|e| (t, e)))
.filter(|&(_, e)| e >= threshold)
.max_by(|a, b| a.1.total_cmp(&b.1))?;
let dir = match row.confidence_gap {
Some(g) if g > 0.0 => "overconfident",
Some(_) => "underconfident",
None => "miscalibrated",
};
Some(format!(
" worst group: {}:{} is really {dir} (e={e:.0}, n={}, K={}) — trust those calls least",
untrusted::tag(ns),
untrusted::tag(&row.tag),
row.n,
d.group_k
))
}
const AGENT_WHO: [&str; 2] = ["who:claude", "who:claude-code"];
fn agent_claims(ledger: &Ledger) -> Ledger {
let mut claims = Vec::new();
for c in &ledger.claims {
if !c.tags.iter().any(|t| AGENT_WHO.contains(&t.as_str())) {
continue;
}
let mut c = c.clone();
let mut tags: Vec<String> = Vec::with_capacity(c.tags.len());
for t in c.tags.drain(..) {
let t = if t == "who:claude-code" {
"who:claude".to_string()
} else {
t
};
if !tags.contains(&t) {
tags.push(t);
}
}
c.tags = tags;
claims.push(c);
}
Ledger {
claims,
..Default::default()
}
}
pub(crate) fn project_slug(cwd: Option<&str>) -> String {
let dir = cwd
.map(std::path::PathBuf::from)
.or_else(|| std::env::current_dir().ok())
.unwrap_or_default();
dir.file_name()
.map(|n| n.to_string_lossy().to_lowercase())
.unwrap_or_else(|| "unknown".into())
}
fn due_lines(ledger: &Ledger, today: NaiveDate, slug: &str) -> Vec<String> {
let lines: Vec<String> = ledger
.claims
.iter()
.filter(|c| !c.is_void() && c.is_due(today))
.filter(|c| c.tags.iter().any(|t| t == &format!("project:{slug}")))
.take(5)
.map(|c| format!(" DUE {} — resolve it", quoted(c)))
.collect();
framed(lines)
}
fn quoted(c: &Claim) -> String {
format!(
"[{}] \"{}\"",
untrusted::tag(&c.id),
untrusted::line(&c.statement, untrusted::MAX_LINE)
)
}
fn framed(lines: Vec<String>) -> Vec<String> {
if lines.is_empty() {
return lines;
}
let mut out = vec![format!(" ({})", untrusted::FRAME)];
out.extend(lines);
out
}
pub(crate) fn checkpoint_drawn(session: &str, n: u64, every: u64) -> bool {
let mut h: u64 = 0xcbf2_9ce4_8422_2325; for b in session.bytes().chain(n.to_le_bytes()) {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
let mut z = h.wrapping_add(0x9e37_79b9_7f4a_7c15); z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^= z >> 31;
z.is_multiple_of(every.max(1))
}
fn log_checkpoint(
ledger_path: &std::path::Path,
session: &str,
n: u64,
every: u64,
drawn: bool,
shown: bool,
) {
let rec = json!({
"v": 2,
"at": Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
"session": untrusted::tag(session),
"prompt": n,
"p": 1.0 / every.max(1) as f64,
"drawn": drawn,
"shown": shown,
"arm": crate::trial::arm_today(ledger_path).map(crate::trial::Arm::label),
"engine": VERSION,
});
let _ = store::append_private(
&ledger_path.with_file_name("checkpoints.jsonl"),
&rec.to_string(),
);
}
fn bump_counter(session: &str) -> u64 {
let Some(dir) = dirs_counters() else {
return 1;
};
let _ = std::fs::create_dir_all(&dir);
let file = dir.join(format!("{}.count", sanitize(session)));
let n = std::fs::read_to_string(&file)
.ok()
.and_then(|s| s.trim().parse::<u64>().ok())
.unwrap_or(0)
+ 1;
let _ = std::fs::write(&file, n.to_string());
n
}
pub(crate) fn current_prompt(session: &str) -> Option<u64> {
let file = dirs_counters()?.join(format!("{}.count", sanitize(session)));
std::fs::read_to_string(file).ok()?.trim().parse().ok()
}
fn first_stop_of_session(session: &str) -> bool {
let Some(dir) = dirs_counters() else {
return true;
};
let _ = std::fs::create_dir_all(&dir);
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(dir.join(format!("{}.stop", sanitize(session))))
.is_ok()
}
pub(crate) fn dirs_counters() -> Option<std::path::PathBuf> {
#[allow(deprecated)]
std::env::home_dir().map(|h| h.join(".anamnesis").join("counters"))
}
pub(crate) fn sanitize(s: &str) -> String {
s.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.take(64)
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Runner {
Cargo,
Other,
}
impl Runner {
fn failure_codes(self) -> &'static [i64] {
match self {
Runner::Cargo => &[101],
Runner::Other => &[1],
}
}
fn confirms_failure(self, f: &RunFacts) -> bool {
match self {
Runner::Cargo => f.cargo_failed || f.compile_error,
Runner::Other => f.fail_marker && !f.env_error,
}
}
fn confirms_pass(self, f: &RunFacts) -> bool {
match self {
Runner::Cargo => f.cargo_passed > 0,
Runner::Other => true,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RunFacts {
pub cargo_passed: u64,
pub cargo_failed: bool,
pub compile_error: bool,
pub fail_marker: bool,
pub env_error: bool,
pub no_tests: bool,
pub saw_pass: bool,
}
const NO_TESTS: [&str; 6] = [
"no tests ran",
"collected 0 items",
"no tests collected",
"no tests found",
"[no test files]",
"ran 0 tests",
];
const ENV_ERRORS: [&str; 10] = [
"command not found",
"no such file or directory",
"no module named",
"no test specified",
"missing script",
"cannot find module",
"go.mod file not found",
"is not recognized as",
"permission denied",
"enoent",
];
impl RunFacts {
pub fn of(text: &str) -> RunFacts {
let mut f = RunFacts::default();
for line in text.lines() {
f.observe_line(line);
}
f
}
pub fn observe_line(&mut self, line: &str) {
let l = line.trim();
if l.is_empty() {
return;
}
if let Some(rest) = l.strip_prefix("test result: ok.") {
if let Some(n) = rest
.split(';')
.next()
.and_then(|part| counts_before(part, "passed").next())
{
self.cargo_passed = self.cargo_passed.saturating_add(n);
}
} else if l.starts_with("test result: FAILED") {
self.cargo_failed = true;
}
if l.contains("could not compile") {
self.compile_error = true;
}
let lower = l.to_ascii_lowercase();
if lower.starts_with("--- fail")
|| l == "FAIL"
|| l.starts_with("FAIL\t")
|| l.starts_with("FAIL ")
|| l.starts_with("FAILED ")
|| ["failed", "failing", "failures"]
.iter()
.any(|w| counts_before(&lower, w).any(|n| n > 0))
{
self.fail_marker = true;
}
if ENV_ERRORS.iter().any(|e| lower.contains(e)) {
self.env_error = true;
}
if NO_TESTS.iter().any(|e| lower.contains(e)) {
self.no_tests = true;
}
if counts_before(&lower, "passed").any(|n| n > 0)
|| l.starts_with("ok ")
|| l.starts_with("ok\t")
|| counts_before(&lower, "test").any(|n| n > 0) && lower.starts_with("ran ")
{
self.saw_pass = true;
}
}
pub fn merge(&mut self, other: &RunFacts) {
self.cargo_passed = self.cargo_passed.saturating_add(other.cargo_passed);
self.cargo_failed |= other.cargo_failed;
self.compile_error |= other.compile_error;
self.fail_marker |= other.fail_marker;
self.env_error |= other.env_error;
self.no_tests |= other.no_tests;
self.saw_pass |= other.saw_pass;
}
}
pub(crate) fn passed_count(text: &str) -> Option<u64> {
let f = RunFacts::of(text);
if f.cargo_passed > 0 {
return Some(f.cargo_passed);
}
text.lines()
.rev()
.find_map(|l| counts_before(&l.to_ascii_lowercase(), "passed").last())
}
fn counts_before<'a>(text: &'a str, word: &'a str) -> impl Iterator<Item = u64> + 'a {
let toks: Vec<&str> = text.split_whitespace().collect();
(0..toks.len().saturating_sub(1)).filter_map(move |i| {
if toks[i + 1].starts_with(word) {
toks[i]
.trim_matches(|c: char| !c.is_ascii_digit())
.parse()
.ok()
} else {
None
}
})
}
const NON_RUNNING_EXACT: [&str; 3] = ["--co", "-h", "-V"];
const NON_RUNNING_PREFIX: [&str; 11] = [
"--no-run",
"--collect-only",
"--help",
"--version",
"--list",
"-list",
"--setup-",
"--fixtures",
"--markers",
"--trace-config",
"--dry-run",
];
const HARMLESS_ENV: [&str; 12] = [
"RUST_BACKTRACE",
"RUST_LOG",
"CI",
"NO_COLOR",
"FORCE_COLOR",
"CARGO_TERM_COLOR",
"PYTHONUNBUFFERED",
"PYTHONDONTWRITEBYTECODE",
"PYTHONPATH",
"NODE_ENV",
"TERM",
"TZ",
];
const SHELL_SYNTAX: [char; 14] = [
'|', ';', '`', '(', ')', '\n', '#', '\'', '"', '\\', '$', '{', '}', '!',
];
fn test_run(cmd: &str) -> Option<Runner> {
let cmd = cmd.trim();
if cmd.is_empty() || cmd.contains(SHELL_SYNTAX) {
return None;
}
let flat = cmd
.replace("2>&1", " ")
.replace("1>&2", " ")
.replace(">&2", " ")
.replace("&>", " ");
let mut segments: Vec<&str> = flat.split("&&").map(str::trim).collect();
let last = segments.pop()?;
if segments.iter().any(|s| !is_plain_cd(s)) || last.contains('&') {
return None;
}
let mut toks: Vec<&str> = last.split_whitespace().collect();
while let Some((name, _)) = toks.first().and_then(|t| assignment(t)) {
if !HARMLESS_ENV.contains(&name) {
return None;
}
toks.remove(0);
}
runner_of(&toks)
}
fn is_plain_cd(segment: &str) -> bool {
let t: Vec<&str> = segment.split_whitespace().collect();
t.len() == 2
&& t[0] == "cd"
&& !t[1].is_empty()
&& t[1]
.chars()
.all(|c| c.is_ascii_alphanumeric() || "._/~+-".contains(c))
}
pub(crate) fn has_non_running_flag(t: &[&str]) -> bool {
t.iter().any(|w| {
NON_RUNNING_EXACT.contains(w) || NON_RUNNING_PREFIX.iter().any(|p| w.starts_with(p))
})
}
pub(crate) fn runner_of(t: &[&str]) -> Option<Runner> {
if has_non_running_flag(t) {
return None;
}
match t {
["cargo", rest @ ..] => {
let rest: &[&str] = match rest {
[first, tail @ ..] if first.starts_with('+') => tail,
_ => rest,
};
match rest {
["test", ..] => Some(Runner::Cargo),
_ => None,
}
}
["npm" | "pnpm" | "yarn" | "bun", "test" | "t" | "tst", ..]
| ["npm" | "pnpm" | "yarn" | "bun", "run" | "run-script", "test", ..] => {
Some(Runner::Other)
}
["pytest" | "py.test" | "jest" | "vitest", ..]
| ["python" | "python3", "-m", "pytest", ..]
| ["npx" | "pnpx" | "bunx", "jest" | "vitest" | "pytest", ..]
| ["go" | "flutter" | "dart", "test", ..] => Some(Runner::Other),
["gradle" | "./gradlew" | "gradlew" | "mvn" | "./mvnw", rest @ ..]
if rest.contains(&"test") =>
{
Some(Runner::Other)
}
_ => None,
}
}
pub(crate) fn assignment(tok: &str) -> Option<(&str, &str)> {
let (name, value) = tok.split_once('=')?;
let ok = !name.is_empty()
&& !name.starts_with(|c: char| c.is_ascii_digit())
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
ok.then_some((name, value))
}
pub(crate) fn is_ana_run(cmd: &str) -> bool {
let toks: Vec<&str> = cmd
.rsplit("&&")
.next()
.unwrap_or("")
.split_whitespace()
.collect();
let is_ana = |t: &str| {
let name = t.rsplit(['/', '\\']).next().unwrap_or(t);
name == "ana" || name == "ana.exe"
};
if !toks.first().is_some_and(|t| is_ana(t)) {
return false;
}
let mut rest = toks[1..].iter();
while let Some(t) = rest.next() {
match *t {
"--data" => {
rest.next();
}
"--json" => {}
t if t.starts_with("--data=") => {}
t => return t == "run",
}
}
false
}
fn exit_code_in(error: &str) -> Option<i64> {
let digits: String = error
.strip_prefix("Exit code ")?
.chars()
.take_while(char::is_ascii_digit)
.collect();
digits.parse().ok()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunJudgement {
Passed,
Failed,
NotGraded(&'static str),
}
fn judge(runner: Runner, code: i64, facts: &RunFacts) -> RunJudgement {
if facts.no_tests && !facts.saw_pass && !facts.fail_marker && !facts.cargo_failed {
return RunJudgement::NotGraded("the runner says no test ran");
}
if code == 0 {
if runner.confirms_pass(facts) {
RunJudgement::Passed
} else {
RunJudgement::NotGraded("no test was seen to pass")
}
} else if runner.failure_codes().contains(&code) && runner.confirms_failure(facts) {
RunJudgement::Failed
} else {
RunJudgement::NotGraded(
"that exit status is not a failed suite for this runner, or its output does not show one",
)
}
}
pub fn judge_run(argv: &[String], code: i64, facts: &RunFacts) -> RunJudgement {
let toks: Vec<&str> = argv.iter().map(String::as_str).collect();
if has_non_running_flag(&toks) {
return RunJudgement::NotGraded("that command lists or builds tests without running them");
}
match runner_of(&toks) {
Some(runner) => judge(runner, code, facts),
None if facts.no_tests && !facts.saw_pass && !facts.fail_marker => {
RunJudgement::NotGraded("the runner says no test ran")
}
None if code != 0 && facts.env_error && !facts.fail_marker => {
RunJudgement::NotGraded("the command never started")
}
None if code == 0 => RunJudgement::Passed,
None => RunJudgement::Failed,
}
}
enum Grade {
Exit(i64),
Untrusted,
NotATest,
}
fn grade_of(event: Event, input: &Value, cmd: &str) -> Grade {
if input
.pointer("/tool_input/run_in_background")
.and_then(Value::as_bool)
== Some(true)
{
return Grade::NotATest;
}
let Some(runner) = test_run(cmd) else {
return if event == Event::PostTool
&& !is_ana_run(cmd)
&& crate::pin::test_run_in(cmd).is_some()
{
Grade::Untrusted
} else {
Grade::NotATest
};
};
let text = |p: &str| input.pointer(p).and_then(Value::as_str).unwrap_or("");
match event {
Event::PostTool => {
let out = format!(
"{}\n{}",
text("/tool_response/stdout"),
text("/tool_response/stderr")
);
match judge(runner, 0, &RunFacts::of(&out)) {
RunJudgement::Passed => Grade::Exit(0),
_ => Grade::Untrusted,
}
}
Event::PostToolFailure => {
if input.get("is_interrupt").and_then(Value::as_bool) == Some(true) {
return Grade::NotATest;
}
let error = text("/error");
match exit_code_in(error) {
Some(code) => match judge(runner, code, &RunFacts::of(error)) {
RunJudgement::Failed => Grade::Exit(code),
_ => Grade::NotATest,
},
None => Grade::NotATest,
}
}
_ => Grade::NotATest,
}
}
pub fn run(event: Event, ledger_path: &std::path::Path) -> Result<(), String> {
let mut raw = String::new();
let _ = std::io::stdin().read_to_string(&mut raw);
let input: Value = serde_json::from_str(raw.trim()).unwrap_or_else(|_| json!({}));
note(event, 0, true);
let (ledger, load_error) = match store::load(ledger_path) {
Ok(l) => (l, None),
Err(e) => (Ledger::default(), Some(e)),
};
let today = Utc::now().date_naive();
let cwd = input.get("cwd").and_then(Value::as_str);
let slug = project_slug(cwd);
let speaks = crate::trial::speaks(ledger_path);
if event == Event::PostTool && crate::pin::is_edit(&input) {
crate::pin::log_edit(
&input,
ledger_path,
input
.get("session_id")
.and_then(Value::as_str)
.and_then(current_prompt),
);
return Ok(());
}
if event == Event::PreTool {
if (crate::pin::enabled() || crate::pin::audit_rate().is_some()) && speaks {
if let Some(out) = crate::pin::pre_tool(&input, &ledger, ledger_path) {
let said = out
.pointer("/hookSpecificOutput/permissionDecisionReason")
.and_then(Value::as_str)
.map_or(0, str::len);
note(event, said, false);
println!("{out}");
}
}
return Ok(());
}
if event == Event::SessionStart && crate::pin::enabled() {
crate::pin::prune_state();
}
let mut context: Vec<String> = Vec::new();
let mut user_message: Option<String> = None;
let mut bet_note: Option<String> = None;
let mut checkpoint: Option<(&str, u64, u64)> = None;
match event {
Event::PreTool => {} Event::SessionStart | Event::UserPrompt => {
if event == Event::SessionStart && !speaks {
return Ok(());
}
if event == Event::UserPrompt {
let session = input
.get("session_id")
.and_then(Value::as_str)
.unwrap_or("default");
if let Some(parsed) = input
.get("prompt")
.and_then(Value::as_str)
.and_then(crate::bet::parse)
{
let reason = match parsed.and_then(|p| {
crate::bet::record(
ledger_path,
session,
current_prompt(session).unwrap_or(0),
&slug,
p,
)
.map(|id| (id, p))
}) {
Ok((id, p)) => format!(
"anamnesis: bet [{}] logged, {:.0}% that {}. The agent was not told. It is graded by that run's exit status; `ana --data {} report` reads your bets.",
untrusted::tag(&id),
p * 100.0,
crate::bet::STATEMENT,
crate::bet::path(ledger_path).display()
),
Err(e) => format!(
"anamnesis: not a bet, and not sent to the agent: {}",
untrusted::line(&e, 160)
),
};
println!("{}", crate::bet::block(reason));
return Ok(());
}
let every = env_usize("ANAMNESIS_INTROSPECT_EVERY", DEFAULT_EVERY);
let n = bump_counter(session);
if !speaks {
log_checkpoint(ledger_path, session, n, every, false, false);
return Ok(());
}
let drawn = checkpoint_drawn(session, n, every);
if !drawn {
log_checkpoint(ledger_path, session, n, every, false, false);
return Ok(()); }
checkpoint = Some((session, n, every));
context.push(format!(
"⟢ Anamnesis (ana {VERSION}) — self-introspection checkpoint (prompt #{n})"
));
} else {
context.push(format!(
"⟢ Anamnesis (ana {VERSION}) — your standing calibration"
));
}
if let Some(e) = &load_error {
println!(
"{}",
json!({ "systemMessage": format!(
"anamnesis: the agent ledger could not be read ({}), so the calibration hooks have nothing to say. Nothing was changed; fix or restore it, or the hooks stay quiet.",
untrusted::line(&e.to_string(), 200)
) })
);
if let Some((s, n, every)) = checkpoint {
log_checkpoint(ledger_path, s, n, every, true, false);
}
return Ok(());
}
let d = ReportData::compute(&agent_claims(&ledger), Some("who:claude"), 10, today);
if let Some(line) = standing_line(&d) {
context.push(line);
if let Some(k) = worst_kind(&d) {
context.push(k);
}
}
if d.evidence_ungraded_due > 0 {
if let Some(id) = &d.evidence_oldest_gap {
context.push(format!(
" {} ungraded call(s) are costing you evidence, oldest [{}] — resolve or void them",
d.evidence_ungraded_due,
untrusted::tag(id)
));
}
}
context.extend(due_lines(&ledger, today, &slug));
if event == Event::SessionStart && crate::pin::enabled() {
context.push(crate::pin::standing_rule());
}
if event == Event::SessionStart {
if let Some(p) = owner_protocol(ledger_path) {
context.push(p);
}
}
if context.len() == 1 {
if let Some((s, n, every)) = checkpoint {
log_checkpoint(ledger_path, s, n, every, true, false);
}
return Ok(()); }
context.push(
"Log predictions with a probability BEFORE acting; resolve them the moment reality answers.".into(),
);
if let Some((s, n, every)) = checkpoint {
log_checkpoint(ledger_path, s, n, every, true, true);
}
}
Event::PostTool | Event::PostToolFailure => {
let cmd = input
.pointer("/tool_input/command")
.and_then(Value::as_str)
.unwrap_or("");
if event == Event::PostTool && crate::pin::edits_by_shell(cmd) {
crate::pin::log_shell_edit(
&input,
ledger_path,
cmd,
input
.get("session_id")
.and_then(Value::as_str)
.and_then(current_prompt),
);
}
let grade = grade_of(event, &input, cmd);
{
let background = input
.pointer("/tool_input/run_in_background")
.and_then(Value::as_bool)
== Some(true);
let exit = match event {
_ if background => None,
Event::PostTool => Some(0),
_ => input
.get("error")
.and_then(Value::as_str)
.and_then(exit_code_in),
};
let graded = match grade {
_ if background => "background",
Grade::Exit(0) => "pass",
Grade::Exit(_) => "fail",
Grade::Untrusted => "untrusted",
Grade::NotATest => "not_graded",
};
let session = input.get("session_id").and_then(Value::as_str);
let prompt = session.and_then(current_prompt);
let edited =
crate::pin::log_outcome(&input, ledger_path, cmd, exit, graded, prompt);
if let (Grade::Exit(code), Some(true), Some(s), Some(n)) =
(&grade, edited, session, prompt)
{
match crate::bet::grade(ledger_path, s, n, *code) {
Ok(bets) if !bets.is_empty() => {
bet_note = Some(format!(
"anamnesis: your bet{} on the agent {} ({}): the test run after its edit {}",
if bets.len() > 1 { "s" } else { "" },
bets.iter()
.map(|(id, p)| format!("[{}] {:.0}%", untrusted::tag(id), p * 100.0))
.collect::<Vec<_>>()
.join(", "),
if *code == 0 { "came true" } else { "did not come true" },
if *code == 0 { "passed".to_string() } else { format!("failed, exit {code}") }
));
}
Ok(_) => {}
Err(e) => {
bet_note = Some(format!(
"anamnesis: a bet was not graded ({})",
untrusted::line(&e, 160)
))
}
}
}
}
match grade {
Grade::NotATest => return Ok(()),
Grade::Exit(code) => {
match auto_resolve(
ledger_path,
&slug,
input.get("session_id").and_then(Value::as_str),
cmd,
code,
) {
Err(e) => {
user_message = Some(format!(
"anamnesis: this test run was not graded ({})",
untrusted::line(&e, 160)
));
}
Ok(resolved) if resolved.is_empty() => {}
Ok(resolved) => {
let happened = code == 0;
context.push(format!(
"⟢ Anamnesis (ana {VERSION}): resolved {} prediction(s) from the command's exit status ({code}) — {}, graded by the exit status, not by you: {}",
resolved.len(),
if happened { "it passed" } else { "it failed" },
resolved
.iter()
.map(|i| untrusted::tag(i))
.collect::<Vec<_>>()
.join(", ")
));
user_message = Some(format!(
"anamnesis: auto-resolved {} prediction(s) from exit code {code}",
resolved.len()
));
}
}
}
Grade::Untrusted => {
let project = format!("project:{slug}");
let session = input.get("session_id").and_then(Value::as_str);
let open: Vec<String> = ledger
.claims
.iter()
.filter(|c| c.is_open() && !c.is_void())
.filter(|c| {
c.tags.iter().any(|t| t == "kind:tests-pass")
|| c.tags.iter().any(|t| t == "kind:approach")
})
.filter(|c| {
c.tags.iter().any(|t| t == &project)
|| session.is_some_and(|s| {
c.extra
.get("origin")
.and_then(|o| o.get("session"))
.and_then(Value::as_str)
== Some(s)
})
})
.take(5)
.map(|c| untrusted::tag(&c.id))
.collect();
if open.is_empty() {
return Ok(());
}
context.push(format!(
"⟢ Anamnesis (ana {VERSION}) (moment of truth): a test command just ran, but its exit status cannot be trusted here (it was piped, chained, or ran no tests), so nothing was graded automatically. Resolve your open prediction(s) about it NOW ({}), before hindsight rewrites how sure you were; this one is on your word.",
open.join(", ")
));
}
}
}
Event::Stop => {
if input
.get("stop_hook_active")
.and_then(Value::as_bool)
.unwrap_or(false)
{
return Ok(());
}
let overdue = ledger
.claims
.iter()
.filter(|c| crate::evidence::came_due(c, today))
.count();
if overdue == 0 {
return Ok(());
}
let session = input
.get("session_id")
.and_then(Value::as_str)
.unwrap_or("default");
if !first_stop_of_session(session) {
return Ok(());
}
user_message = Some(format!(
"anamnesis (ana {VERSION}): {overdue} prediction(s) are past their due date (their --by, or 1 to 7 days after they were logged, by kind) and ungraded, which leaves the calibration numbers resting on a self-selected sample. Resolve or void them. (Said once per session.)"
));
}
}
if let Some(b) = bet_note {
user_message = Some(match user_message {
Some(m) => format!("{m}; {b}"),
None => b,
});
}
if !speaks {
context.clear();
}
if context.is_empty() && user_message.is_none() {
return Ok(());
}
let mut out = json!({});
if !context.is_empty() {
let said = context.join("\n");
note(event, said.len(), false);
out["hookSpecificOutput"] = json!({
"hookEventName": event.name(),
"additionalContext": said,
});
}
if let Some(msg) = user_message {
out["systemMessage"] = json!(msg);
}
println!("{out}");
Ok(())
}
const AUTO_UNSTAMPED_HOURS: i64 = 12;
fn same_session(c: &Claim, session: Option<&str>, now: chrono::DateTime<Utc>) -> bool {
let stamped = c
.extra
.get("origin")
.and_then(|o| o.get("session"))
.and_then(Value::as_str);
match (stamped, session) {
(Some(mine), Some(run)) => mine == untrusted::tag(run),
_ => now - c.created_at <= chrono::Duration::hours(AUTO_UNSTAMPED_HOURS),
}
}
fn auto_resolve(
ledger_path: &std::path::Path,
slug: &str,
session: Option<&str>,
cmd: &str,
exit_code: i64,
) -> Result<Vec<String>, String> {
let wait = std::time::Duration::from_millis(env_usize(
"ANAMNESIS_HOOK_LOCK_WAIT_MS",
DEFAULT_LOCK_WAIT_MS,
));
let _guard = store::lock_within(ledger_path, wait).map_err(|e| e.to_string())?;
let mut ledger = store::load(ledger_path).map_err(|e| e.to_string())?;
let now = Utc::now();
let passed = exit_code == 0;
let project = format!("project:{slug}");
let mut done = Vec::new();
for c in ledger.claims.iter_mut() {
if !c.is_open() || c.is_void() {
continue;
}
if !c.tags.iter().any(|t| t == "kind:tests-pass") {
continue;
}
if c.check.is_some() {
continue;
}
if !c.tags.iter().any(|t| t == &project) {
continue;
}
if c.created_at > now || !same_session(c, session, now) {
continue;
}
c.resolution = Some(Resolution {
at: now,
outcome: Some(if passed {
Outcome::True
} else {
Outcome::False
}),
value: None,
note: Some(format!("auto: `{}` exited {exit_code}", cmd.trim())),
resolved_by: Some(ResolvedBy::Auto),
});
done.push(c.id.clone());
}
if !done.is_empty() {
store::save(ledger_path, &ledger).map_err(|e| e.to_string())?;
}
Ok(done)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn passed_count_reads_each_runners_own_number() {
let cargo = "test result: ok. 3 passed; 0 failed\ntest result: ok. 2 passed; 0 failed";
assert_eq!(passed_count(cargo), Some(5));
assert_eq!(
passed_count("===== 1 failed, 12 passed in 0.31s ====="),
Some(12)
);
assert_eq!(passed_count("Tests: 4 passed, 4 total"), Some(4));
assert_eq!(passed_count("ok \texample.com/pkg\t0.01s"), None);
assert_eq!(passed_count(""), None);
}
#[test]
fn the_checkpoint_draw_has_the_logged_chance_and_every_one_always_draws() {
let mut drawn = 0;
for s in 0..400 {
let session = format!("session-{s:04}");
for n in 1..=50u64 {
drawn += usize::from(checkpoint_drawn(&session, n, 7));
assert!(checkpoint_drawn(&session, n, 1));
assert!(checkpoint_drawn(&session, n, 0), "0 is read as always");
}
}
assert!((2650..3070).contains(&drawn), "{drawn} of 20000");
assert_eq!(checkpoint_drawn("abc", 9, 7), checkpoint_drawn("abc", 9, 7));
}
#[test]
fn the_checkpoint_log_records_the_draw_and_never_the_prompt() {
let dir = std::env::temp_dir().join(format!("ana-cp-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let ledger = dir.join("agent.json");
log_checkpoint(&ledger, "sess-1", 3, 7, true, true);
log_checkpoint(&ledger, "sess-1", 4, 7, false, false);
let text = std::fs::read_to_string(dir.join("checkpoints.jsonl")).unwrap();
let rows: Vec<Value> = text
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
assert_eq!(rows.len(), 2);
assert_eq!(rows[0]["prompt"], 3);
assert_eq!(rows[0]["drawn"], true);
assert_eq!(rows[1]["drawn"], false);
assert_eq!(rows[0]["shown"], true);
assert!((rows[0]["p"].as_f64().unwrap() - 1.0 / 7.0).abs() < 1e-12);
let mut keys: Vec<&str> = rows[0]
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
keys.sort_unstable();
assert_eq!(
keys,
["arm", "at", "drawn", "engine", "p", "prompt", "session", "shown", "v"]
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn plain_test_runs_are_graded() {
for cmd in [
"cargo test",
"cargo test --all -- --nocapture",
"cargo +nightly test -p foo",
" PYTHONPATH=. pytest -q ",
"python3 -m pytest tests/",
"npm test",
"npm run test -- --watch=false",
"pnpm test",
"yarn test",
"go test ./...",
"flutter test",
"npx vitest run",
"./gradlew test",
"mvn test",
"cd /work/project && cargo test",
"cd sub && RUST_LOG=debug cargo test 2>&1",
"RUST_BACKTRACE=1 CI=true cargo test --color always",
] {
assert!(test_run(cmd).is_some(), "should be graded: {cmd}");
}
}
#[test]
fn anything_that_can_change_the_shells_status_is_not() {
for cmd in [
"cargo test | tail -3",
"cargo test 2>&1 | tail -3",
"cargo test || true",
"cargo test; echo done",
"cargo test &",
"cargo test && echo ok",
"echo cargo test",
"! cargo test",
"(cargo test)",
"x=$(cargo test)",
"cargo test\nexit 0",
"cd a && cd b && cargo test | cat",
"make && cargo test",
"cd #x && cargo test",
"cd .&exit && cargo test",
"cd a;b && cargo test",
"cd $(pwd) && cargo test",
"cd 'a b' && cargo test",
"cargo test # && false",
"cargo test '--no-run'",
"cargo test \"--no-run\"",
"cargo test --no\\-run",
"PYTEST_ADDOPTS=--co pytest",
"GOFLAGS=-run=^$ go test ./...",
"CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER=true cargo test",
"cargo nextest run",
] {
assert!(test_run(cmd).is_none(), "must not be graded: {cmd}");
}
}
#[test]
fn builds_lints_and_runs_that_test_nothing_are_not_tests() {
for cmd in [
"cargo build",
"cargo clippy --all-targets",
"cargo test --no-run",
"cargo test -- --list",
"pytest --collect-only",
"pytest --help",
"pytest --setup-plan",
"pytest --fixtures",
"go test -list .",
"npm run build",
"go build ./...",
"ls -la",
"git commit -m 'tests'",
"ana run -- cargo test",
"",
] {
assert!(test_run(cmd).is_none(), "must not be graded: {cmd:?}");
}
}
#[test]
fn ana_run_is_recognised_and_left_alone() {
assert!(is_ana_run("ana run abc123 -- cargo test"));
assert!(is_ana_run(
"/home/u/.anamnesis/bin/ana run abc123 -- cargo test"
));
assert!(is_ana_run("ana --data x.json run abc123 -- pytest"));
assert!(is_ana_run("cd /work && ana run abc123 -- cargo test"));
assert!(is_ana_run(
"ana --data x.json --json run abc123 -- cargo test"
));
assert!(!is_ana_run("ana report -- run"));
assert!(!is_ana_run("ana add \"the suite will run\" --prob 0.7"));
assert!(!is_ana_run("ana --json list run"));
assert!(is_ana_run("ana --json --data=x.json run abc -- cargo test"));
assert!(!is_ana_run("cargo test"));
assert!(!is_ana_run("echo ana run"));
assert!(!is_ana_run("ana report"));
}
#[test]
fn a_test_failure_is_only_the_runners_own_failure_code() {
assert_eq!(test_run("cargo test").unwrap().failure_codes(), [101]);
assert_eq!(test_run("pytest").unwrap().failure_codes(), [1]);
}
#[test]
fn cargo_must_say_the_suite_failed_not_merely_that_it_stopped() {
let cargo = Runner::Cargo;
let f = RunFacts::of;
assert!(cargo.confirms_failure(&f(
"Exit code 101\n\ntest result: FAILED. 0 passed; 1 failed"
)));
assert!(
cargo.confirms_failure(&f("Exit code 101\nerror: could not compile `x` (lib test)"))
);
assert!(!cargo.confirms_failure(&f(
"Exit code 101\nerror: manifest path `tiny/Cargo.toml` does not exist"
)));
assert!(!cargo.confirms_failure(&f("Exit code 101\nerror: no such command: `tset`")));
}
#[test]
fn other_runners_must_show_a_failing_suite_and_no_sign_the_run_never_started() {
let other = Runner::Other;
let f = RunFacts::of;
assert!(other.confirms_failure(&f("=== 1 failed, 3 passed in 0.1s ===")));
assert!(other.confirms_failure(&f("--- FAIL: TestX (0.00s)\nFAIL\tpkg\t0.004s")));
assert!(other.confirms_failure(&f("Tests: 2 failed, 4 passed, 6 total")));
assert!(other.confirms_failure(&f(" 2 passing\n 1 failing")));
assert!(!other.confirms_failure(&f("=== 4 passed, 0 failed in 0.1s ===")));
assert!(!other.confirms_failure(&f("Exit code 1")));
assert!(!other.confirms_failure(&f("bash: pytest: command not found")));
assert!(!other.confirms_failure(&f("/usr/bin/python3: No module named pytest")));
assert!(!other.confirms_failure(&f(
"1 failed\nbash: cd: /nonexistent: No such file or directory"
)));
}
#[test]
fn a_pinned_command_is_judged_by_its_own_status_and_the_runners_rules() {
use RunJudgement::*;
let argv = |s: &str| crate::check::split_command(s).unwrap();
let j = |cmd: &str, code: i64, out: &str| judge_run(&argv(cmd), code, &RunFacts::of(out));
assert_eq!(j("make ci", 0, ""), Passed);
assert_eq!(j("make ci", 2, ""), Failed);
assert_eq!(j("./scripts/check.sh", 1, "anything"), Failed);
let ng = |r: RunJudgement| matches!(r, NotGraded(_));
assert!(ng(j(
"python3 -m pytest -q --co",
1,
"/usr/bin/python3: No module named pytest"
)));
assert!(ng(j(
"python3 -m pytest --collect-only",
0,
"collected 4 items"
)));
assert!(ng(j(
"python3 -m unittest",
5,
"Ran 0 tests in 0.000s\n\nNO TESTS RAN"
)));
assert!(ng(j(
"go test ./...",
0,
"? \texample.com/m\t[no test files]"
)));
assert!(ng(j(
"./scripts/missing.sh",
127,
"sh: ./scripts/missing.sh: No such file or directory"
)));
assert_eq!(
j(
"go test ./...",
0,
"? \texample.com/m\t[no test files]\nok \texample.com/m/sub\t0.01s"
),
Passed
);
assert_eq!(
j("python3 -m unittest", 0, "Ran 3 tests in 0.01s\n\nOK"),
Passed
);
assert_eq!(
j(
"python3 -m unittest",
1,
"Ran 3 tests\n\nFAILED (failures=1)"
),
Failed
);
assert_eq!(
j("cargo test", 0, "test result: ok. 2 passed; 0 failed"),
Passed
);
assert!(matches!(
j("cargo test", 0, "test result: ok. 0 passed; 0 failed"),
NotGraded(_)
));
assert!(matches!(j("cargo test", 0, ""), NotGraded(_)));
assert_eq!(
j("cargo test", 101, "test result: FAILED. 0 passed; 1 failed"),
Failed
);
assert!(matches!(
j("cargo test", 101, "error: manifest path does not exist"),
NotGraded(_)
));
assert!(matches!(j("cargo test", 2, "usage error"), NotGraded(_)));
assert_eq!(j("pytest -q", 1, "=== 1 failed in 0.1s ==="), Failed);
assert!(matches!(j("pytest -q", 1, ""), NotGraded(_)));
assert!(matches!(j("pytest -q", 5, "no tests ran"), NotGraded(_)));
assert_eq!(j(r#"pytest -k "not slow""#, 1, "1 failed"), Failed);
}
#[test]
fn the_exit_code_is_read_from_the_error_text() {
assert_eq!(exit_code_in("Exit code 101\n\nrunning 1 test"), Some(101));
assert_eq!(exit_code_in("Exit code 3"), Some(3));
assert_eq!(exit_code_in("Command timed out"), None);
assert_eq!(exit_code_in("exit code 3"), None);
}
#[test]
fn a_cargo_pass_is_the_sum_of_every_binary_and_needs_one_test() {
let n = |t: &str| RunFacts::of(t).cargo_passed;
assert_eq!(
n("running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored\n"),
0
);
assert_eq!(
n("test result: ok. 0 passed; 0 failed; 1 ignored"),
0,
"only an ignored test"
);
assert_eq!(
n("test result: ok. 40 passed; 0 failed\ntest result: ok. 0 passed; 0 failed"),
40,
"empty doc-tests after a real suite"
);
assert_eq!(
n("test result: ok. 2 passed; 0 failed\ntest result: ok. 3 passed; 0 failed"),
5
);
assert_eq!(n("no cargo output at all"), 0);
assert!(!RunFacts::of("test result: ok. 4 passed; 0 failed").cargo_failed);
}
#[test]
fn the_standing_line_is_silent_on_too_little_evidence() {
let d = ReportData::compute(&Ledger::default(), None, 10, today_for_test());
assert!(standing_line(&d).is_none());
}
fn today_for_test() -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 1, 1).unwrap()
}
#[test]
fn claude_and_claude_code_are_one_agent_and_other_clients_are_not() {
let claim = |id: &str, tags: &[&str]| -> Claim {
serde_json::from_value(serde_json::json!({
"id": id, "statement": "s", "created_at": "2024-01-01T00:00:00Z",
"tags": tags, "kind": "binary",
"forecasts": [{"at": "2024-01-01T00:00:00Z", "prob": 0.7}]
}))
.unwrap()
};
let ledger = Ledger {
claims: vec![
claim("a", &["who:claude", "kind:x"]),
claim("b", &["who:claude-code"]),
claim("c", &["who:claude", "who:claude-code"]),
claim("d", &["who:cursor"]),
claim("e", &["kind:x"]),
],
..Default::default()
};
let mine = agent_claims(&ledger);
let ids: Vec<&str> = mine.claims.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, ["a", "b", "c"]);
for c in &mine.claims {
assert_eq!(c.tags.iter().filter(|t| t.starts_with("who:")).count(), 1);
assert!(c.tags.contains(&"who:claude".to_string()));
}
assert!(ledger.claims[1]
.tags
.contains(&"who:claude-code".to_string()));
}
#[test]
fn session_names_become_safe_filenames() {
assert_eq!(sanitize("abc/../x"), "abc----x");
assert!(!sanitize("a/b").contains('/'));
}
}