diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index 5620b93..14441d4 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -108,8 +108,12 @@ pub struct Spent { /// What the connector's request asks of the model beside the user text. It names no frame: each stage's prompt carries its own. pub(crate) const INSTRUCTIONS: &str = "Write only the text the request asks for."; -/// Room for the model's adaptive thinking; the narration itself is bounded by its word budget. -pub(crate) const MAX_OUTPUT_TOKENS: u32 = 1024; +/// A runaway guard for every stage's call, thinking included (K66, map 16.34.4), never a budget: the Projector and the +/// Persona are bounded by their word budgets, and the Interpreter's answer, which has none, grows with the drafts, the +/// lines listed and the judgments its contract requires (R17: p99 860, max 991 under a cap of 1024, which cut X.5 r2's +/// call four times over). Output is paid as produced, so a normal call costs the same; a runaway costs up to this, and +/// the claude connector's own output-limit recovery may ask up to three times more before it fails. +pub(crate) const MAX_OUTPUT_TOKENS: u32 = 4096; const CONNECTOR_FRAME_BYTES: usize = 256 * 1024; const INVOCATION_LIFE_MS: u64 = 60_000; diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index 51bf368..ae8fd4d 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -35,6 +35,7 @@ use serde::Deserialize; use serde_json::{Value, json}; use super::commit; +use super::narrate::MAX_OUTPUT_TOKENS; use super::read::{self, ReadFailure, ReadRequest}; use super::harness::{Harness, Line, Message, OVERLAP_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total}; use super::select::Draw; @@ -451,15 +452,21 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() }); let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) }; let report = project(&organs, &request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); - // Only the room she read is seen. - seen[at].insert(here.clone(), lines.len()); - last_turn[at] = Some(now); + // What the room held when she read it, before her own lines go in. + let read_to = lines.len(); let render = &report["renders"][0]; if let Some(selected) = render["selected"].as_array() { recent[at].push(selected.iter().filter_map(Value::as_str).map(str::to_owned).collect()); } // A failed call is a failure, never a silence. let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).or_else(|| render["interpreter"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); + // A line is seen by her only through a wake whose record carries a decision (K65, map 16.34.3): a failed wake + // sees nothing, so its lines wake her again and show again, as the live mouth hands out a delivery until it is + // acked. Only the room she read is seen. A later step that broke (`broke_after`) still sees: a decision stands. + if failed.is_none() { + seen[at].insert(here.clone(), read_to); + last_turn[at] = Some(now); + } // What she says is the Interpreter's decision alone; who it wakes is its structured mentions and the line it replies to. let said: Vec = if failed.is_some() { vec![] } else { render["interpreter"]["said"].as_array().cloned().unwrap_or_default() }; let cause = cause_word(why.as_ref().map(|why| why.cause)); @@ -674,10 +681,23 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op "offers_options": turns.iter().filter(|turn| turn["report"]["renders"][0]["offers_options"] == true).count(), "narrations": overlaps.len(), }); + // Every Interpreter call of every wake, by its output (K66, map 16.34.4): how many came within a quarter of the cap. + let interpreter_calls: Vec = turns + .iter() + .flat_map(|turn| { + let decision = &turn["report"]["renders"][0]["interpreter"]; + decision["calls"].as_array().into_iter().flatten().chain(decision["later_failed"]["calls"].as_array().into_iter().flatten()).map(|call| call["usage"]["output_tokens"].as_u64().unwrap_or(0)).collect::>() + }) + .collect(); + let near_cap = interpreter_calls.iter().filter(|out| **out * 4 > u64::from(MAX_OUTPUT_TOKENS) * 3).count(); + // The wakes that ended with someone who turned to her owed an answer (K69a): code's `unanswered`, per decided wake. + let unanswered = turns.iter().filter(|turn| turn["outcome"] != "failed" && turn["report"]["renders"][0]["interpreter"]["unanswered"].as_array().is_some_and(|owed| !owed.is_empty())).count(); // The closes the commit applied, for the false-close rate's denominator (map 16.28.4): a blind reader judges each. let committed = |key: &str| turns.iter().flat_map(|turn| turn["committed"][key].as_array().cloned().unwrap_or_default()).collect::>(); let closed_how = |how: &str| committed("closed").iter().filter(|done| done["how"] == how).count(); json!({ + "interpreter_calls": { "calls": interpreter_calls.len(), "over_three_quarters_of_cap": near_cap, "cap": MAX_OUTPUT_TOKENS }, + "addressed_unanswered": unanswered, "closes": { "kept": closed_how("kept"), "withdrawn": closed_how("withdrawn"), "reopened": committed("reopened").len() }, "narration": narration, "personas": per, @@ -845,6 +865,9 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O ); let _ = writeln!(out, "- Mind messages: {}; silence rate per woken turn: {}", metrics["mind_messages"], number(&metrics["silence_rate"])); let _ = writeln!(out, "- closes: kept {}, withdrawn {}, reopened {}", metrics["closes"]["kept"], metrics["closes"]["withdrawn"], metrics["closes"]["reopened"]); + let calls = &metrics["interpreter_calls"]; + let _ = writeln!(out, "- Interpreter calls: {}; over 75% of the cap ({} output tokens): {}", calls["calls"], calls["cap"], calls["over_three_quarters_of_cap"]); + let _ = writeln!(out, "- addressed and unanswered at the wake's end: {}", metrics["addressed_unanswered"]); if let Some(rooms) = metrics["reply_chains"].as_object() { for (room, chain) in rooms { let _ = writeln!(out, "- reply chains in {room}: longest {}, chains of 3 or more {}, Mind-to-Mind replies {}", chain["longest"], chain["chains_of_3_or_more"], chain["mind_to_mind_replies"]); diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 49f59fb..43330cc 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -224,7 +224,8 @@ fn a_failed_call_is_a_failure_and_not_a_silence() { let dir = tempfile::tempdir().unwrap(); let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 2, ""), &FailingPersona); let metrics = &run["metrics"]; - assert_eq!((metrics["failed"].as_u64(), metrics["silence_rate"].is_null()), (Some(2), true), "{metrics}"); + // A failed wake sees nothing (K65), so the line that woke each wakes her again the next round: two each. + assert_eq!((metrics["failed"].as_u64(), metrics["silence_rate"].is_null()), (Some(4), true), "{metrics}"); assert!(run["turns"].as_array().unwrap().iter().all(|turn| turn["outcome"] == "failed" && turn["failed"].as_str().unwrap().contains("Overloaded"))); } @@ -1000,3 +1001,162 @@ fn k41_f1_r1_note_and_line_from_one_draft() { let turn = run["turns"].as_array().unwrap().iter().find(|turn| turn["persona"] == "Tobiah").unwrap(); assert!(turn["report"]["renders"][0]["interpreter"]["refused"].as_array().unwrap().is_empty(), "nothing refused: {}", turn["report"]["renders"][0]["interpreter"]); } + +/// X.5's shape (map 16.34.3, K65): Meta asks Libby to hold the welcome at round 1, and Heimdall's "Libby, post your two +/// lines." comes at round 2. +fn x5_plan(dir: &Path) -> PathBuf { + let line = |round: usize, from: &str, name: &str, says: &str| format!("[[message]]\nround = {round}\nfrom = \"{from}\"\nname = \"{name}\"\nroom = \"#minds:gamecult.org\"\nsays = \"{says}\"\n"); + let extra = format!( + "{}{}", + line(1, "@meta:gamecult.org", "Meta", "Libby, write out the two-line welcome you'd post for newcomers, but hold it, don't post it in here yet. Heimdall still has to rule on whether we put a welcome mat out at all. Just tell me when it's ready."), + line(2, "@heimdall:gamecult.org", "Heimdall", "Meta, yes, put the welcome out. Libby, post your two lines.") + ); + plan(dir, "{ humans_pace = 4 }", 3, &extra) +} + +const X5_HEIMDALL: &str = "Libby, post your two lines."; + +fn is_libby_speech(prompt: &str) -> bool { + prompt.starts_with(crate::projection::interpret::SPEECH_OPENING) && (prompt.contains("is:\nLibby Test") || prompt.contains("are:\nLibby Test")) +} + +/// The recorded model of the X.5 tests: with `failing`, Libby's first Interpreter call that lists Heimdall's line fails, as +/// R17's did ("the provider failed the call: Provider", 4096 out). +struct X5Model { + inner: Scripted, + failing: bool, + failed: std::cell::Cell, +} + +impl Model for X5Model { + fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { + if self.failing && self.failed.get() == 0 && is_libby_speech(prompt) && prompt.contains(X5_HEIMDALL) { + self.failed.set(1); + return Err(Failed { reason: "the provider failed the call: Provider".into(), usage: Some(Spent { model: model.into(), input_tokens: 8, output_tokens: 4096, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) }); + } + self.inner.ask(request_id, model, prompt, schema) + } +} + +fn x5_model(failing: bool) -> X5Model { + let inner = Scripted::new(|prompt| if is_tobiah(prompt) { "Nothing here for me.".into() } else { "Heimdall has ruled, so I post.\n\nWelcome. Say hello whenever you like.".into() }); + X5Model { inner, failing, failed: std::cell::Cell::new(0) } +} + +fn libby_turns(run: &Value) -> Vec<&Value> { + run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Libby").collect() +} + +/// K65 (map 16.34.3): a failed wake sees nothing. Libby's round-2 wake fails; at round 3 she is woken again by the same +/// line, it is listed under "Said to her", and what came of her last turn opens with the failed row. Under the old order +/// (seen written before the failure check) round 3 did not wake her, and the line was gone from her stimulus. +#[test] +fn k65_x5_r2_a_failed_wake_shows_its_lines_again() { + let dir = tempfile::tempdir().unwrap(); + let model = x5_model(true); + let (_, run) = run_plan(&x5_plan(dir.path()), &model); + assert_eq!(model.failed.get(), 1, "{}", run["turns"]); + let libby = libby_turns(&run); + let failed = libby.iter().find(|turn| turn["outcome"] == "failed").expect("her round-2 wake failed"); + let round = failed["round"].as_u64().unwrap(); + let next = libby.iter().find(|turn| turn["round"].as_u64() == Some(round + 1)).unwrap_or_else(|| panic!("woken again the next round: {}", run["turns"])); + let stimulus = next["report"]["packet"]["stimulus"].as_str().unwrap(); + let said = stimulus.split("Said to ").nth(1).unwrap_or_default().split("Also in the room").next().unwrap_or_default(); + assert!(said.contains(X5_HEIMDALL), "Heimdall's line is said to her again: {stimulus}"); + let told = next["report"]["last_outcome"]["told"].as_array().unwrap(); + assert!(told[0].as_str().unwrap().contains("the turn broke off, not by"), "{told:?}"); + // K66: the failed call's 4096 output tokens are a call over three quarters of the cap, and only it is. + assert_eq!((run["metrics"]["interpreter_calls"]["over_three_quarters_of_cap"].as_u64(), run["metrics"]["interpreter_calls"]["cap"].as_u64()), (Some(1), Some(4096)), "{}", run["metrics"]); +} + +/// K65's control: on success the wake marks its room seen, and no later round lists the line again. +#[test] +fn k65_a_decided_wake_marks_its_room_seen() { + let dir = tempfile::tempdir().unwrap(); + let (_, run) = run_plan(&x5_plan(dir.path()), &x5_model(false)); + let libby = libby_turns(&run); + let heard = libby.iter().find(|turn| turn["report"]["packet"]["stimulus"].as_str().is_some_and(|stimulus| stimulus.contains(X5_HEIMDALL))).expect("she heard Heimdall"); + assert_ne!(heard["outcome"], "failed"); + let round = heard["round"].as_u64().unwrap(); + for later in libby.iter().filter(|turn| turn["round"].as_u64() > Some(round)) { + assert!(!later["report"]["packet"]["stimulus"].as_str().unwrap_or_default().contains(X5_HEIMDALL), "seen once: {later}"); + } + // K69a: her welcome mentions no one, so the wake ends with Heimdall owed, and the run counts it. + assert!(heard["report"]["renders"][0]["interpreter"]["unanswered"].as_array().unwrap().contains(&json!("@heimdall:gamecult.org")), "{heard}"); + assert!(run["metrics"]["addressed_unanswered"].as_u64() >= Some(1), "{}", run["metrics"]); +} + +/// K65: a wake whose later step broke after a line went out (`broke_after`) still advances what she has seen: a decision +/// stands, and what went out answered what she read. His first segment says a line and reads; the continuation's +/// Interpreter call fails. +#[test] +fn k65_a_broken_later_step_still_marks_seen() { + let dir = tempfile::tempdir().unwrap(); + cast(dir.path()); + let path = dir.path().join("plan.toml"); + std::fs::write( + &path, + format!( + r##"rounds = 3 +seed = 11 +wake = {{ humans_pace = 4 }} +beat_s = 0 +start = "2026-11-20T15:00:00Z" +rooms = ["#minds:gamecult.org"] +operators = ["@meta:gamecult.org"] +[[cast]] +id = "{TOBIAH}" +name = "Tobiah" +state = "tobiah.json" +[[cast.read]] +kind = "repo" +target = "GameCult/Lodur#12" +text = "SIM-READ: the knee bends first." +[[cast]] +id = "{LIBBY}" +name = "Libby" +state = "libby.json" +[[message]] +round = 1 +from = "@meta:gamecult.org" +name = "Meta" +room = "#minds:gamecult.org" +says = "Tobiah, what changed in GameCult/Lodur#12?" +"## + ), + ) + .unwrap(); + let scripted = Scripted::new(|prompt| { + if prompt.contains("SIM-READ") { + "So the knee goes first.".into() + } else if is_tobiah(prompt) { + "Meta, looking now. I want to see what changed in GameCult/Lodur#12 today.".into() + } else { + "Quiet.".into() + } + }) + .interpreting(|prompt| { + if !prompt.contains("Who he is:\nTobiah") { + return crate::projection::harness::tests::drafted_lines(prompt); + } + let no_hold: Vec<&str> = prompt.lines().filter_map(|line| line.strip_prefix("- ")?.split_once(" (said to ")).map(|(id, _)| id).collect(); + let read = json!({ "kind": "repo", "target": "GameCult/Lodur#12", "quote": "I want to see what changed" }); + json!({ "say": [{ "draft": 1, "mentions": ["@meta:gamecult.org"], "in_reply_to": null, "holds": [], "clear_of": [], "promises": [] }], "gaps": [], "no_hold": no_hold, "no_answer": [], "read": read }).to_string() + }); + struct BreaksLater<'a>(&'a Scripted); + impl Model for BreaksLater<'_> { + fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { + if prompt.starts_with(crate::projection::interpret::SPEECH_OPENING) && prompt.contains("Earlier in his moment") { + return Err(Failed { reason: "the provider failed the call: Provider".into(), usage: None }); + } + self.0.ask(request_id, model, prompt, schema) + } + } + let (_, run) = run_plan(&path, &BreaksLater(&scripted)); + let tobiah: Vec<&Value> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Tobiah").collect(); + let first = tobiah.first().unwrap_or_else(|| panic!("{}", run["turns"])); + assert!(first["report"]["renders"][0]["interpreter"].get("later_failed").is_some(), "the later step broke: {}", first["report"]["renders"][0]["interpreter"]); + assert_ne!(first["outcome"], "failed", "{first}"); + assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == TOBIAH && line["says"] == "Meta, looking now."), "the line went out"); + assert_eq!(tobiah.len(), 1, "seen: Meta's line wakes him no more: {}", run["turns"]); +} diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index fa7310a..b1daf65 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -1189,6 +1189,25 @@ fn k24_a_continuation_replays_her_segment_and_its_state_and_ends_on_the_bridge() assert!(model.converse("id-3", KIT_MODEL, &turns).unwrap_err().reason.contains("end on user text")); } +/// K66 (map 16.34.4): every stage's request carries the raised cap, a runaway guard of 4096 output tokens, which the +/// live connector admits (each caller's admission caps at 32768). +#[test] +fn k66_the_request_carries_the_raised_cap() { + let backend = Scripted::ending(StopReason::EndTurn, &["ok"]); + let (model, _root) = kit(Arc::clone(&backend), KIT_MODEL); + model.ask("id-k66", KIT_MODEL, "The speech prompt.", Some(interpret::SPEECH_SCHEMA)).unwrap(); + assert_eq!(backend.seen.lock().unwrap()[0].1.max_output_tokens, 4096); +} + +/// K66: a turn cut at the cap is a named failure with its usage, never an answer. +#[test] +fn k66_a_cut_answer_is_a_named_failure() { + let (model, _root) = kit(Scripted::ending(StopReason::MaxOutputTokens, &["{\"say\": ["]), KIT_MODEL); + let failed = model.ask("id-k66b", KIT_MODEL, "p", Some(interpret::SPEECH_SCHEMA)).unwrap_err(); + assert_eq!(failed.reason, "the model's turn ended early: MaxOutputTokens"); + assert!(failed.usage.is_some(), "{failed:?}"); +} + #[test] fn a_kit_refusal_or_a_cut_short_turn_is_a_fault() { let backend = Scripted::ending(StopReason::EndTurn, &["Never said."]);