diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 835290b..4f6daec 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -370,6 +370,35 @@ pub(crate) enum MemoryRefusal { MemoryUnlisted, } +impl MemoryRefusal { + /// Whether the Interpreter can mend it by saying the note again (`decide_in`): its wording, not its count. + fn retryable(self) -> bool { + matches!(self, Self::MemoryLong | Self::Echo) + } + + /// The reason in plain words, as the Interpreter is told it when a note goes back to it once. + fn why(self) -> String { + match self { + Self::MemoryEmpty => "it said nothing".to_owned(), + Self::MemoryLong => format!("it is over {MEMORY_BYTES} bytes; keep it shorter"), + Self::Echo => format!("it repeats someone's words from what reached the person or what they read, {ECHO_MIN_WORDS} words or more in a row; no one's line is kept as a memory, so say it in words of its own"), + Self::OverMemories => "one answer keeps at most four notes".to_owned(), + Self::MemoryUnlisted => "it names no memory listed".to_owned(), + } + } +} + +/// What a note is measured against (`quotes`): the bodies she was shown and read, less her own drafts of this wake. A +/// heard line that quotes her draft back, or a read that holds it, is her words coming back, so a note may carry them +/// (R19, Libby's draft lost); the rest of the line, and every other line, still counts. +fn without_drafts(bodies: &[String], found: &Drafts) -> Vec { + bodies + .iter() + .map(|body| found.drafts.iter().filter(|draft| !draft.text.trim().is_empty()).fold(body.clone(), |text, draft| text.replace(draft.text.as_str(), " "))) + .filter(|body| !body.trim().is_empty()) + .collect() +} + /// Where in her wake a decision falls (map 16.22.3): what was decided earlier this wake (none for her first segment), /// where her new segment begins in her prose, what she has read so far this wake, and her earlier segments with their /// bridges, as the Interpreter is shown them. Drafts are numbered across the wake, and each decision decides every draft @@ -727,32 +756,68 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na // What she remembers of this moment, and which of her listed memories it settles (map 16.35.4): proposals the commit // applies (`commit::apply`), each held to code's structural checks. A memory carries no one's line: one that echoes // what she was shown or read, or quotes a run of it, is refused, so no heard words reach the Projector by way of her - // state (I16.7). + // state (I16.7). Her own drafts are hers: words of them that a heard line or a read quotes back are not what it + // measures a note against (`without_drafts`). A note refused for its wording (`MemoryRefusal::retryable`) goes back to + // the Interpreter once, with code's plain reason, and the second answer is held to the same checks and stands. let mut proposals: Vec = Vec::new(); let mut memory_refused: Vec = Vec::new(); let mut about_dropped: Vec = Vec::new(); let mut remembered = 0usize; - for proposed in parsed.remember { - let text = proposed.text.trim(); - let reason = if text.is_empty() { - Some(MemoryRefusal::MemoryEmpty) - } else if text.len() > MEMORY_BYTES { - Some(MemoryRefusal::MemoryLong) - } else if quotes(text, &bodies) { - Some(MemoryRefusal::Echo) - } else if remembered >= MEMORIES_MAX { - Some(MemoryRefusal::OverMemories) - } else { - None - }; - if let Some(reason) = reason { - memory_refused.push(json!({ "act": "remember", "text": text, "reason": reason })); - continue; + let note_bodies = without_drafts(&bodies, &found); + let mut batch = parsed.remember; + let mut retried = false; + loop { + let mut again: Vec<(String, MemoryRefusal)> = Vec::new(); + for proposed in batch { + let text = proposed.text.trim(); + let reason = if text.is_empty() { + Some(MemoryRefusal::MemoryEmpty) + } else if text.len() > MEMORY_BYTES { + Some(MemoryRefusal::MemoryLong) + } else if quotes(text, ¬e_bodies) { + Some(MemoryRefusal::Echo) + } else if remembered >= MEMORIES_MAX { + Some(MemoryRefusal::OverMemories) + } else { + None + }; + if let Some(reason) = reason { + if reason.retryable() && !retried { + again.push((text.to_owned(), reason)); + } else { + memory_refused.push(json!({ "act": "remember", "text": text, "reason": reason })); + } + continue; + } + remembered += 1; + let (about, unknown): (Vec, Vec) = proposed.about.into_iter().partition(|id| shown(id)); + about_dropped.extend(unknown); + proposals.push(json!({ "kind": "remember", "text": text, "about": about, "importance": proposed.importance.clamp(0.0, 1.0), "private": proposed.private, "room": room })); + } + if again.is_empty() { + break; + } + let refused_notes: String = again.iter().map(|(text, reason)| format!("- \"{text}\": {}\n", reason.why())).collect(); + let asking = format!("{prompt}\n\nSome notes in an earlier answer to this were refused:\n{refused_notes}Answer the speech contract again. Only `remember` is read this time: say each refused note you still want kept in words of its own, or leave it out. Everything else in your earlier answer is settled."); + let request_id = format!("{segment_id}:{attempt}"); + let (usage, second) = match model.ask(&request_id, &tuning.interpreter.model, &asking, Some(SPEECH_SCHEMA)) { + Ok(answer) => (answer.usage, serde_json::from_str::(&answer.text).ok().map(|answer| answer.remember)), + Err(failed) => (failed.usage, None), + }; + decision["calls"].as_array_mut().into_iter().for_each(|calls| calls.push(json!({ "usage": usage, "retry": false, "memory_retry": true }))); + let first_refusals = again.iter().map(|(text, reason)| json!({ "text": text, "reason": reason })).collect::>(); + match second { + Some(second) => { + decision["memory_retried"] = json!(first_refusals); + batch = second; + retried = true; + } + // No second answer: the first refusals stand. + None => { + memory_refused.extend(again.iter().map(|(text, reason)| json!({ "act": "remember", "text": text, "reason": reason }))); + break; + } } - remembered += 1; - let (about, unknown): (Vec, Vec) = proposed.about.into_iter().partition(|id| shown(id)); - about_dropped.extend(unknown); - proposals.push(json!({ "kind": "remember", "text": text, "about": about, "importance": proposed.importance.clamp(0.0, 1.0), "private": proposed.private, "room": room })); } let mut settled: Vec<&str> = Vec::new(); for id in &parsed.resolve { diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 4a922eb..e4aaa53 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -2055,3 +2055,64 @@ fn t6_notes_past_the_guard_stop_and_the_ones_about_who_is_here_come_first() { assert!(packet.sections.notes <= 600, "{:?}", packet.sections); } } + +/// The decision when the recorded Interpreter answers `first`, and `second` to the prompt that sends refused notes back; +/// with how many times it was sent back. +fn answered_twice(packet: &Packet, prose: &str, first: Value, second: Value) -> (Value, usize) { + let sent_back = std::rc::Rc::new(std::cell::Cell::new(0usize)); + let counted = sent_back.clone(); + let (first, second) = (first.to_string(), second.to_string()); + let model = Scripted::new(|_| String::new()).interpreting(move |prompt| { + if prompt.contains("notes in an earlier answer to this were refused") { + counted.set(counted.get() + 1); + second.clone() + } else { + first.clone() + } + }); + let decision = decide(&model, "test", packet, "The room is warm.", prose, &Tuning::default()); + (decision, sent_back.get()) +} + +/// R19 (retry, once): a note refused as an echo goes back to the Interpreter once with the plain reason, and a rephrasing is +/// kept; a second refusal stands as it is reported today, and the note is not sent back a second time. +#[test] +fn r19_a_refused_note_is_sent_back_once() { + let packet = libby_packet(&[(META, "Meta", X1_META_R1, true)]); + let rephrased = "Meta asked Libby to hold the welcome lines and say when they are ready."; + let (decision, sent_back) = answered_twice(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": [note(X1_META_R1, &[META])] }), json!({ "say": [], "gaps": [], "remember": [note(rephrased, &[META])] })); + assert_eq!(sent_back, 1, "{decision}"); + assert_eq!((decision["state"][0]["text"].as_str(), decision.get("memory_refused"), decision["memory_retried"][0]["reason"].as_str()), (Some(rephrased), None, Some("echo")), "{decision}"); + assert_eq!(decision["calls"].as_array().map(Vec::len), Some(2), "{decision}"); + + let (stuck, sent_back) = answered_twice(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": [note(X1_META_R1, &[META])] }), json!({ "say": [], "gaps": [], "remember": [note(X1_META_R1, &[META])] })); + assert_eq!((sent_back, stuck["state"].clone(), stuck["memory_refused"][0]["reason"].as_str()), (1, json!([]), Some("echo")), "{stuck}"); + + let long = "Meta asked about welcome lines. ".repeat(30); + let (shortened, sent_back) = answered_twice(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": [note(&long, &[META])] }), json!({ "say": [], "gaps": [], "remember": [note(X5_NOTE, &[META])] })); + assert_eq!((sent_back, shortened["state"][0]["text"].as_str(), shortened["memory_retried"][0]["reason"].as_str()), (1, Some(X5_NOTE), Some("memory_long")), "{shortened}"); + + // A note refused only for being past the count is not sent back: rephrasing does not make room. + let five: Vec = (1..=5).map(|n| note(&format!("Libby noticed thing number {n} about the welcome."), &[META])).collect(); + let (counted, sent_back) = answered_twice(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": five }), json!({ "say": [], "gaps": [] })); + assert_eq!((sent_back, counted["memory_refused"][0]["reason"].as_str()), (0, Some("over_memories")), "{counted}"); +} + +/// R19 (her own draft): a heard line that quotes her draft back does not make a note carrying that draft an echo, while the +/// rest of that line, and any other line, still does. +#[test] +fn r19_a_note_may_carry_her_own_draft_text() { + let draft = "Welcome. Say hello whenever you like, nobody here needs you to have something to fix first."; + let heard = format!("Libby, I have your lines here: {draft} Tell Meta when you have changed the second one."); + let packet = libby_packet(&[(HER, "Heimdall", &heard, true)]); + let prose = format!("Here is the draft. {draft}"); + let carrying = format!("Libby wrote this welcome and is holding it: {draft}"); + let decision = answered(&packet, &prose, json!({ "say": [], "gaps": [], "remember": [note(&carrying, &[HER])] })); + assert_eq!((decision["state"][0]["text"].as_str(), decision.get("memory_refused")), (Some(carrying.as_str()), None), "{decision}"); + // Without the draft in her wake the same note is her copy of a heard line. + let undrafted = answered(&packet, "Here is the draft.", json!({ "say": [], "gaps": [], "remember": [note(&carrying, &[HER])] })); + assert_eq!(undrafted["memory_refused"][0]["reason"].as_str(), Some("echo"), "{undrafted}"); + // The words around her draft are Heimdall's, and still refused. + let theirs = answered(&packet, &prose, json!({ "say": [], "gaps": [], "remember": [note("Heimdall said: Tell Meta when you have changed the second one, Libby, he asked.", &[HER])] })); + assert_eq!(theirs["memory_refused"][0]["reason"].as_str(), Some("echo"), "{theirs}"); +}