use super::*;
use std::sync::{Arc, Mutex};
fn staged_row(session_id: &str) -> SavingsRow {
SavingsRow {
ts: "2026-09-09T00:00:00Z".to_string(),
session_id: session_id.to_string(),
technique: crate::core::savings::TECHNIQUE_INSTRUCTION_COMPRESSION.to_string(),
tokens_saved: 600,
tokens_before: 6_800,
cost_saved_usd: 0.0018,
basis: "hand-built".to_string(),
model_source: crate::core::session_model::MODEL_SOURCE_LAUNCH_CONFIG.to_string(),
}
}
fn rows_in(ledger: &Path) -> usize {
std::fs::read_to_string(ledger)
.map(|text| text.lines().filter(|line| !line.trim().is_empty()).count())
.unwrap_or(0)
}
#[test]
fn a_staged_row_emits_once_under_the_claude_session_id() {
let root = tempfile::tempdir().expect("temp root");
let compiled = root
.path()
.join("project/.trusty-mpm/sessions/m1/INSTRUCTIONS-COMPILED.md");
let ledger = root.path().join("ledger.jsonl");
stage_row(root.path(), &compiled, &staged_row("m1"));
assert!(
pending_row_path_in(root.path(), &compiled).exists(),
"the compiling process must leave a staged row behind"
);
assert!(
emit_staged_row(&ledger, root.path(), &compiled, "c1"),
"the first hook invocation must append the staged row"
);
assert!(
!crate::core::savings::fold_session(&ledger, "c1").is_zero(),
"the statusline fold under the Claude session id must find the row"
);
assert!(
crate::core::savings::fold_session(&ledger, "m1").is_zero(),
"nothing may stay attributed to the compile-time id"
);
assert!(
!emit_staged_row(&ledger, root.path(), &compiled, "c1"),
"a second hook invocation must append nothing"
);
assert_eq!(
rows_in(&ledger),
1,
"the staged row must reach the ledger exactly once"
);
}
#[test]
fn emitting_without_a_staged_row_writes_nothing() {
let root = tempfile::tempdir().expect("temp root");
let compiled = root
.path()
.join("project/.trusty-mpm/sessions/m1/INSTRUCTIONS-COMPILED.md");
let ledger = root.path().join("ledger.jsonl");
assert!(
!emit_staged_row(&ledger, root.path(), &compiled, "c1"),
"with nothing staged the hook must report no append"
);
assert!(
!ledger.exists(),
"with nothing staged the hook must not create the ledger"
);
}
#[test]
fn emitting_without_a_session_id_leaves_the_row_staged() {
let root = tempfile::tempdir().expect("temp root");
let compiled = root
.path()
.join("project/.trusty-mpm/sessions/m1/INSTRUCTIONS-COMPILED.md");
let ledger = root.path().join("ledger.jsonl");
stage_row(root.path(), &compiled, &staged_row("m1"));
assert!(!emit_staged_row(&ledger, root.path(), &compiled, " "));
assert!(
pending_row_path_in(root.path(), &compiled).exists(),
"a blank session id must leave the staged row for the next hook"
);
assert!(emit_staged_row(&ledger, root.path(), &compiled, "c1"));
assert_eq!(rows_in(&ledger), 1);
}
#[test]
fn a_failed_append_leaves_the_row_staged_for_the_next_hook() {
let root = tempfile::tempdir().expect("temp root");
let compiled = root
.path()
.join("project/.trusty-mpm/sessions/m1/INSTRUCTIONS-COMPILED.md");
let blocker = root.path().join("blocker");
std::fs::write(&blocker, b"a regular file, not a directory").expect("write blocker");
let unwritable = blocker.join("ledger.jsonl");
stage_row(root.path(), &compiled, &staged_row("m1"));
assert!(
!emit_staged_row(&unwritable, root.path(), &compiled, "c1"),
"an append that fails must report no append"
);
assert!(
pending_row_path_in(root.path(), &compiled).exists(),
"a failed append must return the row to its staging path for the next hook"
);
let ledger = root.path().join("ledger.jsonl");
assert!(
emit_staged_row(&ledger, root.path(), &compiled, "c1"),
"the retry against a writable ledger must append the recovered row"
);
assert_eq!(
rows_in(&ledger),
1,
"the recovered row must reach the ledger exactly once"
);
assert!(
!crate::core::savings::fold_session(&ledger, "c1").is_zero(),
"the recovered row must fold under the Claude session id"
);
}
#[test]
fn two_racing_claims_append_exactly_one_row() {
let root = tempfile::tempdir().expect("temp root");
let compiled = root
.path()
.join("project/.trusty-mpm/sessions/m1/INSTRUCTIONS-COMPILED.md");
let ledger = root.path().join("ledger.jsonl");
stage_row(root.path(), &compiled, &staged_row("m1"));
let racers: Vec<_> = (0..2)
.map(|_| {
let ledger = ledger.clone();
let root = root.path().to_path_buf();
let compiled = compiled.clone();
std::thread::spawn(move || emit_staged_row(&ledger, &root, &compiled, "c1"))
})
.collect();
let appended = racers
.into_iter()
.map(|racer| racer.join().expect("racer thread"))
.filter(|appended| *appended)
.count();
assert_eq!(appended, 1, "exactly one racer may claim the staged row");
assert_eq!(
rows_in(&ledger),
1,
"two racing hooks must leave exactly one row"
);
}
#[test]
fn two_compiled_prompts_stage_to_different_files() {
let root = tempfile::tempdir().expect("temp root");
let left = root
.path()
.join("alpha/.trusty-mpm/sessions/local/INSTRUCTIONS-COMPILED.md");
let right = root
.path()
.join("beta/.trusty-mpm/sessions/local/INSTRUCTIONS-COMPILED.md");
assert_ne!(
pending_row_path_in(root.path(), &left),
pending_row_path_in(root.path(), &right),
"two projects on the `local` scope must not share a staging file"
);
}
#[test]
fn a_staged_row_remembers_its_compiled_prompt() {
let root = tempfile::tempdir().expect("temp root");
let compiled = root
.path()
.join("project/.trusty-mpm/sessions/m1/INSTRUCTIONS-COMPILED.md");
stage_row(root.path(), &compiled, &staged_row("m1"));
let text = std::fs::read_to_string(pending_row_path_in(root.path(), &compiled))
.expect("the staged file must be readable");
let parsed: serde_json::Value =
serde_json::from_str(&text).expect("the staged file must be one JSON object");
assert_eq!(
parsed.get("compiled_prompt").and_then(|v| v.as_str()),
Some(compiled.to_string_lossy().as_ref()),
"the staged row must name the compiled prompt it measures: {text}"
);
let row: SavingsRow =
serde_json::from_str(&text).expect("a staged file must still read back as a bare row");
assert_eq!(row.tokens_saved, 600, "the measurement must survive intact");
}
#[test]
fn the_no_fold_note_fires_once_per_project() {
let root = tempfile::tempdir().expect("temp root");
let project = root.path().join("project");
assert!(
log_no_fold_once(root.path(), &project, 26_741, 29_074),
"the first decline must log"
);
assert!(
!log_no_fold_once(root.path(), &project, 26_741, 29_074),
"a second compile with the same figures must stay quiet"
);
}
#[test]
fn the_no_fold_note_fires_again_when_the_byte_pair_moves() {
let root = tempfile::tempdir().expect("temp root");
let project = root.path().join("project");
assert!(log_no_fold_once(root.path(), &project, 26_741, 29_074));
assert!(
log_no_fold_once(root.path(), &project, 26_741, 28_000),
"a changed byte pair must log again"
);
}
#[derive(Clone, Default)]
struct CaptureWriter(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for CaptureWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().expect("capture lock").extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CaptureWriter {
type Writer = CaptureWriter;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
#[test]
fn the_no_fold_note_is_emitted_at_debug_level() {
let root = tempfile::tempdir().expect("temp root");
let project = root.path().join("project");
let at_warn = CaptureWriter::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(at_warn.clone())
.with_max_level(tracing::Level::WARN)
.with_ansi(false)
.finish();
tracing::subscriber::with_default(subscriber, || {
log_no_fold_once(root.path(), &project, 26_741, 29_074);
});
let warned = String::from_utf8(at_warn.0.lock().expect("capture lock").clone())
.expect("the captured log must be utf-8");
assert!(
warned.is_empty(),
"the decline must not reach an operator's WARN stream: {warned}"
);
let at_debug = CaptureWriter::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(at_debug.clone())
.with_max_level(tracing::Level::DEBUG)
.with_ansi(false)
.finish();
tracing::subscriber::with_default(subscriber, || {
log_no_fold_once(root.path(), &project, 26_741, 28_000);
log_no_fold_once(root.path(), &project, 26_741, 28_000);
});
let logged = String::from_utf8(at_debug.0.lock().expect("capture lock").clone())
.expect("the captured log must be utf-8");
assert_eq!(
logged
.matches("not smaller than the instruction sources")
.count(),
1,
"two compiles must produce exactly one line: {logged}"
);
assert!(
logged.contains("26741") && logged.contains("28000"),
"the line must name both byte counts: {logged}"
);
}
#[test]
fn the_no_fold_note_names_neither_the_segment_nor_an_override() {
let root = tempfile::tempdir().expect("temp root");
let project = root.path().join("project");
let capture = CaptureWriter::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(capture.clone())
.with_max_level(tracing::Level::DEBUG)
.with_ansi(false)
.finish();
tracing::subscriber::with_default(subscriber, || {
log_no_fold_once(root.path(), &project, 26_741, 29_074);
});
let logged = String::from_utf8(capture.0.lock().expect("capture lock").clone())
.expect("the captured log must be utf-8");
for banned in [
"\u{1f4b8}",
"statusline segment",
"CLAUDE.md",
"override",
"divert",
] {
assert!(
!logged.contains(banned),
"the line must state only the measurement, but says {banned:?}: {logged}"
);
}
assert!(
logged.contains("no instruction-fold savings row is written"),
"the line must still say what it declined to write: {logged}"
);
}