use super::*;
use crate::core::content_source::test_support::rc;
fn sections() -> SectionBytes {
SectionBytes::of(rc())
}
fn sonnet_price() -> Option<(String, f64)> {
Some(("claude-sonnet-4-6".to_string(), 3.0))
}
fn no_roster(_project_dir: &std::path::Path) -> usize {
0
}
fn plausible_prompt() -> String {
"x".repeat(min_plausible_compiled_bytes(sections()).max(1))
}
#[test]
fn no_row_when_the_compiled_prompt_is_not_smaller() {
assert!(
instruction_compression_row("sess-a", 26_617, 30_721, sonnet_price).is_none(),
"a larger compiled prompt must write no row"
);
assert!(
instruction_compression_row("sess-a", 26_617, 26_617, sonnet_price).is_none(),
"an equal compiled prompt must write no row"
);
assert!(
instruction_compression_row("sess-a", 1_003, 1_000, sonnet_price).is_none(),
"a sub-token delta must write no row"
);
}
#[test]
fn a_folded_source_set_produces_a_row() {
let row = instruction_compression_row("sess-a", 60_000, 20_000, sonnet_price).expect("a row");
assert_eq!(row.session_id, "sess-a");
assert_eq!(row.tokens_saved, 10_000);
assert_eq!(row.tokens_before, 15_000);
assert!((row.cost_saved_usd - 0.03).abs() < 1e-9);
assert!(
row.basis.contains("60000") && row.basis.contains("20000"),
"the basis must carry both byte counts: {}",
row.basis
);
}
#[test]
fn instruction_compression_tokens_use_the_shared_divisor() {
let row = instruction_compression_row("sess-a", 8_000, 4_000, sonnet_price).expect("a row");
assert_eq!(row.tokens_saved, (4_000.0 / BYTES_PER_TOKEN) as i64);
assert_eq!(row.tokens_saved, 1_000);
}
#[test]
fn instruction_compression_row_carries_the_named_technique() {
let row = instruction_compression_row("sess-a", 60_000, 20_000, sonnet_price).expect("a row");
assert_eq!(row.technique, TECHNIQUE_INSTRUCTION_COMPRESSION);
assert_eq!(row.technique, "instruction-compression");
}
#[test]
fn instruction_compression_row_names_its_model_source() {
let row = instruction_compression_row("sess-a", 60_000, 20_000, sonnet_price).expect("a row");
assert_eq!(
row.model_source,
crate::core::session_model::MODEL_SOURCE_LAUNCH_CONFIG
);
assert_eq!(row.model_source, "launch-config");
assert_ne!(
row.model_source,
crate::core::session_model::MODEL_SOURCE_CONFIG_FALLBACK,
"a launch-time config read must not be labelled a fallback"
);
}
#[test]
fn no_row_when_the_model_cannot_be_priced() {
assert!(
instruction_compression_row("sess-a", 60_000, 20_000, || None).is_none(),
"an unpriceable model must write no row"
);
assert!(
instruction_compression_row("sess-a", 60_000, 20_000, || Some(("m".into(), 0.0))).is_none(),
"a zero rate must write no row"
);
}
#[test]
fn session_and_root_reads_the_compiled_prompt_path() {
let dest = std::path::Path::new(
"/repos/trusty-tools/.trusty-mpm/sessions/sess-42/INSTRUCTIONS-COMPILED.md",
);
let (session_id, root) = session_and_root(dest).expect("resolved");
assert_eq!(session_id, "sess-42");
assert_eq!(root, std::path::Path::new("/repos/trusty-tools"));
}
#[test]
fn session_and_root_rejects_a_short_path() {
assert!(session_and_root(std::path::Path::new("INSTRUCTIONS-COMPILED.md")).is_none());
assert!(session_and_root(std::path::Path::new("/a/b/INSTRUCTIONS-COMPILED.md")).is_none());
}
#[test]
fn session_and_root_rejects_a_path_that_is_not_under_sessions() {
for not_a_compiled_prompt in [
"/tmp/x/a/b/INSTRUCTIONS-COMPILED.md",
"/repos/t/.trusty-mpm/framework/sess-1/INSTRUCTIONS-COMPILED.md",
"/repos/t/other/sessions/sess-1/INSTRUCTIONS-COMPILED.md",
"/repos/t/.trusty-mpm/sessions/sess-1/last-instructions.md",
] {
assert!(
session_and_root(std::path::Path::new(not_a_compiled_prompt)).is_none(),
"{not_a_compiled_prompt} is not a compiled-prompt path"
);
}
}
#[test]
fn a_malformed_compiled_prompt_path_records_no_row() {
let framework_root = tempfile::tempdir().expect("temp framework root");
let tmp = tempfile::tempdir().expect("temp dir");
let dest = tmp
.path()
.join("a")
.join("b")
.join("INSTRUCTIONS-COMPILED.md");
std::fs::create_dir_all(dest.parent().expect("parent")).expect("fixture dirs");
let plausible = plausible_prompt_above_the_floor();
std::fs::write(&dest, &plausible).expect("fixture");
let ledger = crate::core::savings::savings_log_in(framework_root.path());
record_instruction_compression_to(
framework_root.path(),
sections(),
&dest,
&plausible,
Some("c-7514".to_string()),
no_roster,
sonnet_price,
);
assert!(
!ledger.exists(),
"a destination that is not a compiled prompt must append no row: {}",
std::fs::read_to_string(&ledger).unwrap_or_default()
);
assert!(
!crate::core::savings_sidecar::pending_row_path_in(framework_root.path(), &dest).exists(),
"nor stage one"
);
assert!(
!framework_root
.path()
.join("usage")
.join("no-fold-warned")
.exists(),
"nor leave a no-fold marker behind"
);
}
fn plausible_prompt_above_the_floor() -> String {
"x".repeat(min_plausible_compiled_bytes(sections()) + 137)
}
#[test]
fn folded_source_bytes_counts_the_bundled_sections() {
let dir = tempfile::tempdir().expect("temp dir");
let bundled: usize = crate::core::instruction_pipeline::SECTION_FILES
.iter()
.map(|path| rc().required(path).len())
.sum();
assert!(bundled > 0, "the bundled corpus must not be empty");
assert_eq!(
folded_source_bytes(sections(), dir.path(), 0),
bundled,
"a project with no CLAUDE.md contributes only the bundled sections"
);
}
#[test]
fn folded_source_bytes_adds_an_override_body() {
let dir = tempfile::tempdir().expect("temp dir");
let baseline = folded_source_bytes(sections(), dir.path(), 0);
let body = "Ship it. Skip the ceremony.";
std::fs::write(
dir.path().join("CLAUDE.md"),
format!(
"<!-- TRUSTY-MPM: WORKFLOW START v=1 -->\n{body}\n<!-- TRUSTY-MPM: WORKFLOW END -->\n"
),
)
.expect("write CLAUDE.md");
let with_override = folded_source_bytes(sections(), dir.path(), 0);
assert_eq!(
with_override,
baseline + body.len(),
"the override body must be counted on the source side"
);
}
#[test]
fn resolve_pm_price_agrees_with_the_shared_table() {
if let Some((model, rate)) = resolve_pm_price() {
let table = trusty_common::inference::pricing(&model)
.expect("the resolved model must be one the table knows");
assert_eq!(rate, table.input, "the rate must be the table's input rate");
assert!(rate > 0.0, "a priced model must have a positive input rate");
}
}
fn compiled_prompt_dest(root: &std::path::Path, scope: &str) -> std::path::PathBuf {
let dir = root.join(".trusty-mpm").join("sessions").join(scope);
std::fs::create_dir_all(&dir).expect("session dir");
dir.join("INSTRUCTIONS-COMPILED.md")
}
#[test]
fn the_row_is_keyed_by_the_claude_session_id() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let dest = compiled_prompt_dest(project.path(), "local");
let ledger = crate::core::savings::savings_log_in(framework_root.path());
record_instruction_compression_to(
framework_root.path(),
sections(),
&dest,
&plausible_prompt(),
Some("claude-abc-123".to_string()),
no_roster,
sonnet_price,
);
let written = std::fs::read_to_string(&ledger).expect("the ledger must exist");
assert!(
written.contains("\"session_id\":\"claude-abc-123\""),
"the row must be keyed by the Claude Code session id: {written}"
);
let matched = crate::core::savings::fold_session(&ledger, "claude-abc-123");
assert!(
!matched.is_zero(),
"the statusline fold under the Claude Code id must find the row: {matched:?}"
);
assert!(
crate::core::savings::fold_session(&ledger, "local").is_zero(),
"nothing may be attributed to the compiled-prompt directory name"
);
}
#[test]
fn no_claude_id_stages_the_row_instead_of_writing_an_unfoldable_one() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let dest = compiled_prompt_dest(project.path(), "sess-42");
record_instruction_compression_to(
framework_root.path(),
sections(),
&dest,
&plausible_prompt(),
None,
no_roster,
sonnet_price,
);
let ledger = crate::core::savings::savings_log_in(framework_root.path());
assert!(
!ledger.exists(),
"a row nothing can fold must not reach the ledger"
);
let staged = crate::core::savings_sidecar::pending_row_path_in(framework_root.path(), &dest);
let text = std::fs::read_to_string(&staged).expect("the row must be staged for the hook");
assert!(
text.contains("\"session_id\":\"sess-42\""),
"the staged row keeps the compile-time id until the hook re-keys it: {text}"
);
}
#[test]
fn a_staged_row_becomes_foldable_at_the_first_hook_invocation() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let dest = compiled_prompt_dest(project.path(), "m1");
let ledger = crate::core::savings::savings_log_in(framework_root.path());
record_instruction_compression_to(
framework_root.path(),
sections(),
&dest,
&plausible_prompt(),
None,
no_roster,
sonnet_price,
);
assert!(
crate::core::savings::fold_session(&ledger, "c1").is_zero(),
"before the hook there is nothing for the statusline to fold"
);
for _ in 0..2 {
crate::core::savings_sidecar::emit_staged_row(&ledger, framework_root.path(), &dest, "c1");
}
let folded = crate::core::savings::fold_session(&ledger, "c1");
assert!(
!folded.is_zero(),
"the statusline fold for the launched Claude session must find the row: {folded:?}"
);
assert_eq!(
folded.rows, 1,
"two hook invocations must leave exactly one row for the pair: {folded:?}"
);
assert!(
crate::core::savings::fold_session(&ledger, "m1").is_zero(),
"nothing may stay attributed to the managed session id"
);
}
#[test]
fn a_prompt_that_folds_nothing_warns_once_and_writes_no_row() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let dest = compiled_prompt_dest(project.path(), "m1");
let bulky = "x".repeat(folded_source_bytes(sections(), project.path(), 0) + 1);
record_instruction_compression_to(
framework_root.path(),
sections(),
&dest,
&bulky,
None,
no_roster,
sonnet_price,
);
assert!(
!crate::core::savings::savings_log_in(framework_root.path()).exists(),
"a prompt that folded nothing must write no row"
);
assert!(
!crate::core::savings_sidecar::pending_row_path_in(framework_root.path(), &dest).exists(),
"a prompt that folded nothing must stage nothing either"
);
assert!(
!crate::core::savings_sidecar::log_no_fold_once(
framework_root.path(),
project.path(),
folded_source_bytes(sections(), project.path(), 0),
bulky.len(),
),
"the producer must already have logged for this project and byte pair"
);
}
#[test]
fn rederiving_from_the_compiled_prompt_appends_under_the_session_id() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let dest = compiled_prompt_dest(project.path(), "local");
std::fs::write(&dest, plausible_prompt()).expect("compiled prompt");
let ledger = crate::core::savings::savings_log_in(framework_root.path());
assert!(
rederive_from_compiled_prompt(framework_root.path(), &dest, "c1"),
"the compiled prompt on disk must be enough to produce the row"
);
let folded = crate::core::savings::fold_session(&ledger, "c1");
assert!(
!folded.is_zero(),
"the re-derived row must fold under the Claude session id: {folded:?}"
);
assert!(
!crate::core::savings_sidecar::pending_row_path_in(framework_root.path(), &dest).exists(),
"a re-derivation appends; it must never stage a second copy"
);
}
#[test]
fn rederiving_a_prompt_that_folds_nothing_appends_nothing() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let dest = compiled_prompt_dest(project.path(), "local");
let bulky = "x".repeat(ambient_source_bytes(project.path(), sections()) + 1);
std::fs::write(&dest, &bulky).expect("compiled prompt");
let ledger = crate::core::savings::savings_log_in(framework_root.path());
assert!(
!rederive_from_compiled_prompt(framework_root.path(), &dest, "c1"),
"a prompt that folded nothing must report no row"
);
assert!(crate::core::savings::fold_session(&ledger, "c1").is_zero());
}
#[test]
fn the_row_reports_the_compiled_prompts_own_size() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let dest = compiled_prompt_dest(project.path(), "local");
let staged_bytes = min_plausible_compiled_bytes(sections()) + 137;
std::fs::write(&dest, "x".repeat(staged_bytes)).expect("compiled prompt");
let on_disk = std::fs::metadata(&dest).expect("compiled prompt").len() as usize;
assert_eq!(
on_disk, staged_bytes,
"the fixture must be the size it claims"
);
let ledger = crate::core::savings::savings_log_in(framework_root.path());
assert!(
rederive_from_compiled_prompt(framework_root.path(), &dest, "c1"),
"a plausible compiled prompt must produce a row"
);
let written = std::fs::read_to_string(&ledger).expect("the ledger must exist");
assert!(
written.contains(&format!("compiled {on_disk} B")),
"the row must report the compiled prompt's own size ({on_disk} B): {written}"
);
assert!(
!written.contains("compiled 13 B"),
"the #7491 placeholder measurement must be unreachable: {written}"
);
}
#[test]
fn a_stub_compiled_prompt_writes_no_row() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let dest = compiled_prompt_dest(project.path(), "local");
let ledger = crate::core::savings::savings_log_in(framework_root.path());
std::fs::write(&dest, "placeholder\n\n").expect("compiled prompt");
assert_eq!(
std::fs::metadata(&dest).expect("compiled prompt").len(),
13,
"the fixture reproduces the reported 13-byte compiled row"
);
assert!(
!rederive_from_compiled_prompt(framework_root.path(), &dest, "c1"),
"a stub compiled prompt must report no row"
);
assert!(
!ledger.exists(),
"a stub compiled prompt must not reach the ledger: {}",
std::fs::read_to_string(&ledger).unwrap_or_default()
);
assert!(
!crate::core::savings_sidecar::pending_row_path_in(framework_root.path(), &dest).exists(),
"a stub compiled prompt must not be staged either"
);
let missing = compiled_prompt_dest(project.path(), "gone");
std::fs::remove_file(&missing).ok();
assert!(
!rederive_from_compiled_prompt(framework_root.path(), &missing, "c2"),
"a missing compiled prompt must report no row"
);
assert!(!ledger.exists(), "a missing file must write nothing");
}
#[test]
fn claude_code_session_id_names_the_harness_variable() {
assert_eq!(
crate::core::savings::CLAUDE_CODE_SESSION_ID_ENV,
"CLAUDE_CODE_SESSION_ID"
);
}
fn deploy_agents(dir: &std::path::Path, count: usize) {
std::fs::create_dir_all(dir).expect("agent tier");
for index in 0..count {
std::fs::write(
dir.join(format!("fixture-agent-{index}.md")),
format!(
"---\nname: fixture-agent-{index}\nrole: engineer\nmodel: sonnet\n---\n\nBody.\n"
),
)
.expect("agent file");
}
}
fn no_override_composition(project: &std::path::Path) -> (String, usize) {
let tier = project.join(".claude").join("agents");
deploy_agents(&tier, 40);
let dirs = vec![tier.clone()];
let delivered = crate::core::delegation_authority::roster_section_from_tiers(&dirs, &dirs)
.expect("a deployed tier renders a roster");
let read = crate::core::delegation_authority::roster_section_from_dirs(&dirs)
.expect("the undeduped roster renders too");
let (prompt, _) =
crate::core::instruction_overrides::resolve_pm_prompt_with_roster(rc(), project, || {
Some(delivered.clone())
});
(prompt, read.len())
}
#[test]
fn a_no_override_project_folds_below_its_authored_sources() {
let project = tempfile::tempdir().expect("temp project");
let (prompt, roster_read) = no_override_composition(project.path());
let sources = folded_source_bytes(sections(), project.path(), roster_read);
let compiled = prompt.len();
assert!(
compiled < sources,
"the no-override fold must remove bytes: sources {sources} B, compiled \
{compiled} B"
);
}
#[test]
fn the_no_override_fold_clears_the_prose_floor() {
let project = tempfile::tempdir().expect("temp project");
let (prompt, roster_read) = no_override_composition(project.path());
let sources = folded_source_bytes(sections(), project.path(), roster_read);
let saved = sources.saturating_sub(prompt.len());
let prose_floor: usize = crate::core::instruction_pipeline::SECTION_FILES
.iter()
.map(|path| rc().required(path))
.map(|body| body.len() - crate::core::instruction_fold::fold_delivered_prompt(body).len())
.sum();
assert!(prose_floor > 0, "the prose fold must recover something");
assert!(
saved >= prose_floor,
"the fold saved {saved} B, below the {prose_floor} B the prose fold alone \
recovers from the bundled sections"
);
}
#[test]
fn the_no_override_row_basis_carries_the_measured_bytes() {
let project = tempfile::tempdir().expect("temp project");
let framework_root = tempfile::tempdir().expect("temp framework root");
let (prompt, roster_read) = no_override_composition(project.path());
let dest = compiled_prompt_dest(project.path(), "local");
let ledger = crate::core::savings::savings_log_in(framework_root.path());
record_instruction_compression_to(
framework_root.path(),
sections(),
&dest,
&prompt,
Some("claude-7616".to_string()),
move |_| roster_read,
sonnet_price,
);
let written = std::fs::read_to_string(&ledger).expect("a row must be written");
let sources = folded_source_bytes(sections(), project.path(), roster_read);
assert!(
written.contains(&format!(
"sources {sources} B - compiled {} B",
prompt.len()
)),
"the basis must carry the measured counts, not a placeholder: {written}"
);
assert!(
written.contains("claude-7616"),
"the row must be keyed by the Claude session id: {written}"
);
assert!(
!written.contains("\"session_id\":\"local\""),
"a row keyed by the compiled-prompt directory is the #7209 defect: {written}"
);
}
#[test]
fn roster_source_bytes_are_zero_without_a_roster() {
assert_eq!(
roster_source_bytes_from(&[]),
0,
"no tier at all folds no roster"
);
let empty_tier = tempfile::tempdir().expect("temp tier");
assert_eq!(
roster_source_bytes_from(&[empty_tier.path().to_path_buf()]),
0,
"a tier that exists but deploys no agent folds no roster"
);
let absent = empty_tier.path().join("never-created");
assert_eq!(
roster_source_bytes_from(&[absent]),
0,
"an absent tier is normal, not a fold"
);
let deployed = tempfile::tempdir().expect("temp tier");
deploy_agents(deployed.path(), 3);
assert!(
roster_source_bytes_from(&[deployed.path().to_path_buf()]) > 0,
"a tier holding agents must contribute source bytes"
);
}
#[test]
fn the_roster_dedup_counts_as_folded_source() {
let dir = tempfile::tempdir().expect("temp dir");
let baseline = folded_source_bytes(sections(), dir.path(), 0);
assert_eq!(
folded_source_bytes(sections(), dir.path(), 1_234),
baseline + 1_234,
"the roster the composer read must land on the source side"
);
}
#[test]
fn the_fold_measurement_is_none_before_any_session_compiles() {
let project = tempfile::tempdir().expect("temp project");
assert!(measure_project_fold(project.path(), sections()).is_none());
}
#[test]
fn the_fold_measurement_reads_the_newest_compiled_prompt() {
let project = tempfile::tempdir().expect("temp project");
let dest = compiled_prompt_dest(project.path(), "local");
std::fs::write(&dest, "x".repeat(4_096)).expect("compiled prompt");
let (sources, compiled) =
measure_project_fold(project.path(), sections()).expect("a measurement");
assert_eq!(compiled, 4_096);
assert!(
sources >= min_plausible_compiled_bytes(sections()),
"the source side must carry the bundled corpus"
);
}
#[test]
fn n_composes_under_one_session_id_append_exactly_one_row() {
let tmp = tempfile::tempdir().expect("temp dir");
let root = tmp.path().join("framework");
let project = tmp.path().join("project");
let dest = crate::core::instruction_pipeline::compiled_prompt_path(&project, "local");
std::fs::create_dir_all(dest.parent().expect("session dir")).expect("session dir");
let ledger = savings_log_in(&root);
let prompt = "x".repeat(min_plausible_compiled_bytes(sections()).max(1));
for _ in 0..26 {
record_instruction_compression_to(
&root,
sections(),
&dest,
&prompt,
Some("claude-7658".to_string()),
no_roster,
sonnet_price,
);
}
let text = std::fs::read_to_string(&ledger).expect("the first compose must write a ledger");
assert_eq!(
text.lines().filter(|line| !line.trim().is_empty()).count(),
1,
"26 composes of one unchanged prompt must leave one row, got:\n{text}"
);
}