Persona T7 fix: a note is exempt only for a line she already posted, whole words and at least ECHO_MIN_WORDS; the retry is tested, records why it failed, and reads at most one note per note sent back (Soul s1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-27 20:04:39 +01:00
commit a907e7ffdf
2 changed files with 168 additions and 30 deletions

View file

@ -44,7 +44,7 @@ use serde_json::{Value, json};
use super::Affordance;
use super::read::{self, Asked, Kind, QUOTE_MIN_WORDS, ReadRequest, SPAN_MIN_WORDS};
use super::narrate::{Model, heard_overlap, lived_stream, words};
use super::select::{Forms, Packet, capitalized, named_pronouns, spoken, turn_words, voiced};
use super::select::{Amendable, Forms, Packet, capitalized, named_pronouns, spoken, turn_words, voiced};
use super::tuning::Tuning;
/// The most lines she says in one turn.
@ -386,14 +386,33 @@ fn memory_why(refusal: MemoryRefusal) -> String {
}
}
/// 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<String> {
/// What a note is measured against (`quotes`): the bodies she was shown and read, less her own posted lines that come back
/// in them, whole and at word boundaries (`span::tokens`), and only a line of at least `ECHO_MIN_WORDS` words, as a shorter
/// run is no quotation. A line of hers already posted came before this wake, so a heard line or a read that holds it is her
/// own words coming back and a note may carry them. Her drafts of this wake are not here: everything she heard came before
/// them, so a draft that matches a heard line copied it, and a note carrying it would carry that line (Soul's s1).
fn without_own_lines(bodies: &[String], own: &[Amendable]) -> Vec<String> {
let lines: Vec<Vec<String>> = own.iter().map(|line| span::tokens(&line.text).collect::<Vec<_>>()).filter(|words| words.len() >= ECHO_MIN_WORDS).collect();
if lines.is_empty() {
return bodies.to_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())
.map(|body| {
let words: Vec<String> = span::tokens(body).collect();
let (mut kept, mut at) = (Vec::new(), 0);
while at < words.len() {
match lines.iter().find(|line| words[at..].starts_with(line)) {
Some(line) => at += line.len(),
None => {
kept.push(words[at].as_str());
at += 1;
}
}
}
kept.join(" ")
})
.filter(|body| !body.is_empty())
.collect()
}
@ -754,18 +773,20 @@ 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). 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 (`retryable`) goes back to
// state (I16.7). Her own posted lines are hers: a heard line or a read that quotes one back is not what it
// measures a note against (`without_own_lines`). A note refused for its wording (`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<Value> = Vec::new();
let mut memory_refused: Vec<Value> = Vec::new();
let mut about_dropped: Vec<String> = Vec::new();
let mut remembered = 0usize;
let note_bodies = without_drafts(&bodies, &found);
let note_bodies = without_own_lines(&bodies, &packet.amendable);
let mut batch = parsed.remember;
let mut retried = false;
// What the first pass settled without sending back: a second answer that says it again is the model restating its answer, not a rephrasing.
let mut settled_texts: Vec<String> = Vec::new();
// The second answer is read for at most as many notes as were sent back: a restatement of the whole list, reworded, is not a rephrasing.
let mut room_left = 0usize;
loop {
let mut again: Vec<(String, MemoryRefusal)> = Vec::new();
for proposed in batch {
@ -773,6 +794,12 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na
if retried && settled_texts.iter().any(|seen| seen == text) {
continue;
}
if retried {
if room_left == 0 {
continue;
}
room_left -= 1;
}
let reason = if text.is_empty() {
Some(MemoryRefusal::MemoryEmpty)
} else if text.len() > MEMORY_BYTES {
@ -805,15 +832,19 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na
let refused_notes: String = again.iter().map(|(text, reason)| format!("- \"{text}\": {}\n", memory_why(*reason))).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>(&answer.text).ok().map(|answer| answer.remember)),
Err(failed) => (failed.usage, None),
let (usage, second, failed) = match model.ask(&request_id, &tuning.interpreter.model, &asking, Some(SPEECH_SCHEMA)) {
Ok(answer) => (answer.usage, serde_json::from_str::<Answer>(&answer.text).ok().map(|answer| answer.remember), None),
Err(failed) => (failed.usage, None, Some(failed.reason)),
};
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::<Vec<_>>();
let mut call = json!({ "usage": usage, "retry": false, "memory_retry": true });
if let Some(reason) = failed {
call["failed"] = json!(reason);
}
decision["calls"].as_array_mut().into_iter().for_each(|calls| calls.push(call));
decision["memory_retried"] = json!(again.iter().map(|(text, reason)| json!({ "text": text, "reason": reason })).collect::<Vec<_>>());
match second {
Some(second) => {
decision["memory_retried"] = json!(first_refusals);
room_left = again.len();
batch = second;
retried = true;
}

View file

@ -2098,21 +2098,128 @@ fn r19_a_refused_note_is_sent_back_once() {
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.
/// The Interpreter double of the retry tests: `first` to the speech prompt, `second` to the one that sends refused notes back,
/// every prompt kept in order, every request id kept by `Replaying`, which refuses a reused id with other bytes as the
/// connector does.
fn retry_run(packet: &Packet, prose: &str, first: Value, second: Value) -> (Value, Vec<String>, Vec<String>) {
let prompts = std::rc::Rc::new(std::cell::RefCell::new(Vec::<String>::new()));
let kept = prompts.clone();
let (first, second) = (first.to_string(), second.to_string());
let scripted = Scripted::new(|_| String::new()).interpreting(move |prompt| {
kept.borrow_mut().push(prompt.to_owned());
if prompt.contains("notes in an earlier answer to this were refused") { second.clone() } else { first.clone() }
});
let replaying = crate::projection::harness::tests::Replaying::over(&scripted);
let decision = decide(&replaying, "test", packet, "The room is warm.", prose, &Tuning::default());
let ids = replaying.ids.borrow().clone();
let prompts = prompts.borrow().clone();
(decision, ids, prompts)
}
/// Soul s1 (retry-contract-untested; mutants m01 reused id, m08 flag, m09 plain reason): the retry asks under its own id (K58),
/// is flagged in the calls, and tells the Interpreter the refused note and why in plain words.
#[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.");
fn r19_the_retry_has_its_own_id_its_flag_and_the_plain_reason() {
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, ids, prompts) = retry_run(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": [note(X1_META_R1, &[META])] }), json!({ "say": [], "gaps": [], "remember": [note(rephrased, &[META])] }));
assert_eq!(ids, vec!["test:0".to_owned(), "test:1".to_owned()], "{decision}");
assert_eq!(decision["state"][0]["text"].as_str(), Some(rephrased), "a reused id would be refused as ReplayConflict: {decision}");
assert_eq!(decision["calls"][1]["memory_retry"], json!(true), "{decision}");
assert_eq!(decision["calls"][0].get("memory_retry"), None, "{decision}");
let sent_back = &prompts[1];
assert!(sent_back.contains(&format!("\"{X1_META_R1}\"")) && sent_back.contains("words or more in a row") && sent_back.contains("words of its own"), "{sent_back}");
let long = "Meta asked about welcome lines. ".repeat(30);
let (_, _, prompts) = retry_run(&packet, X5_LIBBY_R1, json!({ "say": [], "gaps": [], "remember": [note(&long, &[META])] }), json!({ "say": [], "gaps": [] }));
assert!(prompts[1].contains("bytes; keep it shorter"), "{}", prompts[1]);
}
/// A model that fails the retry call, as the connector reports a turn cut short.
struct FailsTheRetry(Scripted);
impl Model for FailsTheRetry {
fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> Result<crate::projection::Answer, crate::projection::Failed> {
if prompt.contains("notes in an earlier answer to this were refused") {
return Err(crate::projection::Failed { reason: "the model's turn ended early: MaxOutputTokens".into(), usage: None });
}
self.0.ask(request_id, model, prompt, schema)
}
}
/// Soul s1 (m05): a failed retry leaves the first refusals standing, and its call says why it failed (K66).
#[test]
fn r19_a_failed_retry_keeps_the_first_refusals_and_says_why() {
let packet = libby_packet(&[(META, "Meta", X1_META_R1, true)]);
let reply = json!({ "say": [], "gaps": [], "remember": [note(X1_META_R1, &[META])] }).to_string();
let model = FailsTheRetry(Scripted::new(|_| String::new()).interpreting(move |_| reply.clone()));
let decision = decide(&model, "test", &packet, "The room is warm.", X5_LIBBY_R1, &Tuning::default());
assert_eq!((decision["state"].clone(), decision["memory_refused"][0]["reason"].as_str()), (json!([]), Some("echo")), "{decision}");
assert_eq!((decision["calls"][1]["memory_retry"].clone(), decision["calls"][1]["failed"].as_str()), (json!(true), Some("the model's turn ended early: MaxOutputTokens")), "{decision}");
assert_eq!(decision["memory_retried"][0]["reason"].as_str(), Some("echo"), "{decision}");
}
/// Soul s1 (retry-keeps-reworded-dupes): a second answer that restates the accepted notes in new words is not read past
/// the number of notes sent back, so one fact does not become two memories.
#[test]
fn r19_a_retry_that_restates_accepted_notes_keeps_one_per_note_sent_back() {
let packet = libby_packet(&[(META, "Meta", X1_META_R1, true)]);
let accepted = "Libby told Meta she would hold the welcome lines until Heimdall rules.";
let rephrased = "Meta asked Libby to hold the welcome lines and say when they are ready.";
let (decision, _, _) = retry_run(
&packet,
X5_LIBBY_R1,
json!({ "say": [], "gaps": [], "remember": [note(X1_META_R1, &[META]), note(accepted, &[META])] }),
json!({ "say": [], "gaps": [], "remember": [note(rephrased, &[META]), note("Libby promised Meta to wait for Heimdall's ruling on the welcome lines.", &[META]), note(accepted, &[META])] }),
);
let texts: Vec<&str> = decision["state"].as_array().unwrap().iter().filter_map(|one| one["text"].as_str()).collect();
assert_eq!(texts, vec![accepted, rephrased], "{decision}");
}
/// A posted line of hers, listed as she may add to it, in `packet`.
fn with_own_line(mut packet: Packet, text: &str) -> Packet {
packet.amendable.push(Amendable { id: "a1".into(), event: "$own".into(), room: MINDS.into(), text: text.into() });
packet
}
/// R19 and Soul s1 (her own words): a heard line or a read that quotes a line she already posted does not make a note
/// carrying that line an echo, while the rest of the heard line, and any other line, still does.
#[test]
fn r19_a_note_may_carry_a_line_she_posted() {
let own = "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: {own} Tell Meta when the second line changes please.");
let packet = libby_packet(&[(HER, "Heimdall", &heard, true)]);
let prose = format!("Here is the draft. <typed>{draft}</typed>");
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])] }));
let carrying = format!("Libby posted this welcome: {own}");
let answer = |packet: &Packet, text: &str| answered(packet, "Here it is.", json!({ "say": [], "gaps": [], "remember": [note(text, &[HER])] }));
let kept = answer(&with_own_line(packet.clone(), own), &carrying);
assert_eq!((kept["state"][0]["text"].as_str(), kept.get("memory_refused")), (Some(carrying.as_str()), None), "{kept}");
assert_eq!(answer(&packet, &carrying)["memory_refused"][0]["reason"].as_str(), Some("echo"), "she did not post it, so it is heard words");
let theirs = answer(&with_own_line(packet, own), "Heimdall said: tell meta when the second line changes please, Libby.");
assert_eq!(theirs["memory_refused"][0]["reason"].as_str(), Some("echo"), "{theirs}");
}
/// Soul s1 (short-draft-strips-bodies): a posted line shorter than `ECHO_MIN_WORDS` words exempts nothing, and what is
/// exempt is a run of whole words, never letters inside a word.
#[test]
fn r19_a_short_line_of_hers_exempts_nothing_and_never_cuts_inside_a_word() {
let heard = "Heimdall: one two ok three four five six seven eight and a look at the token.";
let packet = libby_packet(&[(HER, "Heimdall", heard, true)]);
let copied = "Heimdall said one two ok three four five six seven eight to her.";
for short in ["ok", "ok three four five six seven"] {
let decision = answered(&with_own_line(packet.clone(), short), "Noted.", json!({ "say": [], "gaps": [], "remember": [note(copied, &[HER])] }));
assert_eq!(decision["memory_refused"][0]["reason"].as_str(), Some("echo"), "{short}: {decision}");
}
let bodies = vec!["a look at the token and a book".to_owned()];
let own = [Amendable { id: "a1".into(), event: "$own".into(), room: MINDS.into(), text: "ok to look at".into() }];
assert_eq!(without_own_lines(&bodies, &own), bodies);
}
/// Soul s1 (draft-copy-launders-heard-line): a draft of this wake that copies a heard line does not let a note carry that
/// line: only a line she posted before is exempt, never a draft written after what she heard.
#[test]
fn r19_a_draft_that_copies_a_heard_line_does_not_launder_it_into_a_note() {
let packet = libby_packet(&[(META, "Meta", X1_META_R1, true)]);
let prose = format!("Here it is. <typed>{X1_META_R1}</typed>");
let decision = answered(&packet, &prose, json!({ "say": [], "gaps": [], "remember": [note(&format!("Meta said: {X1_META_R1}"), &[META])] }));
assert_eq!((decision["state"].clone(), decision["memory_refused"][0]["reason"].as_str()), (json!([]), Some("echo")), "{decision}");
}