diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index c9182c5..e09480d 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -48,7 +48,7 @@ pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use select::TurnKind; pub use tuning::{TUNING_FILE, TUNING_ROOT}; -use narrate::{cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words}; +use narrate::{cap_prose, cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words}; use select::{History, Inputs, Packet, People, Replied, Room, RoomLine, select, turn_room}; /// The agent name on the connector's request ids. @@ -414,10 +414,13 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni return render; } }; - let mut prose = cap_words(&first.answer.text, tuning.persona.words); + // Never cut inside a draft (Soul's R5): a draft the cap cut off is told to her as unfinished, cut by the cap. + let capped = cap_prose(&first.answer.text, tuning.persona.words); + let mut prose = capped.text; + let mut cut_drafts: Vec = capped.cut_draft.into_iter().collect(); // Each continuation's call, its usage under `usage` so the report's totals count it (Soul: 72 of 76 calls counted). let mut continuations: Vec = Vec::new(); - render["persona"] = json!({ "words": words(&prose), "cut_at_budget": words(&first.answer.text) > tuning.persona.words, "usage": first.answer.usage, "prose": prose }); + render["persona"] = json!({ "words": words(&prose), "cut_at_budget": capped.cut, "usage": first.answer.usage, "prose": prose }); if through != Through::Interpreter { return render; } @@ -427,8 +430,6 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni let mut decision = interpret::decide(model, &request_id(instance, "interpreter", tag, packet.seed), packet, &narration, &prose, tuning); let mut reads: Vec = Vec::new(); let mut ended = None; - // Whether the newest segment was cut at her word budget: then a draft it left unfinished is code's cut, not hers. - let mut cut = false; while let (Some(reading), Some(read)) = (reading, decision.get("read").filter(|read| !read.is_null()).cloned()) { // Caps (map 16.22.3): reads a wake, bytes a wake, and her prose across segments at most twice her word budget. A // read is performed only when the reply after it can have her whole word budget inside that, so the overall cap @@ -471,9 +472,10 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni break; } }; - let segment = cap_words(&continued.answer.text, tuning.persona.words); - cut = words(&continued.answer.text) > tuning.persona.words; - continuations.push(json!({ "usage": continued.answer.usage, "words": words(&segment), "cut_at_budget": cut })); + let capped = cap_prose(&continued.answer.text, tuning.persona.words); + let segment = capped.text; + cut_drafts.extend(capped.cut_draft); + continuations.push(json!({ "usage": continued.answer.usage, "words": words(&segment), "cut_at_budget": capped.cut })); turns.push(Turn::Assistant { text: segment.clone(), states: continued.states }); before = format!("{before}{}\n\n{bridge}\n\n", &prose[from..]); prose = format!("{prose}\n\n{segment}"); @@ -485,21 +487,14 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni // applies (Soul p5); the failure, with what it cost, is recorded beside it. if next.get("failed").is_some() { decision["later_failed"] = json!({ "segment": reads.len() + 1, "failed": next["failed"], "raw": next.get("raw"), "usage": next["usage"] }); - cut = false; break; } decision = next; } - // A draft the word budget cut off after a read is code's cut, not a promise of hers that failed: it is reported, and - // she is not told of it as unfinished, nor of an unwritten gap in that segment. - if cut && !reads.is_empty() && decision.get("unfinished").is_some() { - decision["unfinished_cut_by_cap"] = decision["unfinished"].take(); - decision.as_object_mut().map(|map| map.remove("unfinished")); - for gap in decision["gaps"].as_array_mut().into_iter().flatten() { - if gap["kind"] == "unwritten" && gap["start_byte"].as_u64().is_some_and(|at| at as usize >= from) { - gap["from"] = json!("cut_by_cap"); - } - } + // A draft the cap cut off before it closed: never in her stream, and told to her as unfinished, cut by the cap. + if let Some(last) = cut_drafts.last().filter(|_| decision.get("failed").is_none()) { + decision["unfinished"] = json!(last); + decision["cut_by_cap"] = json!(cut_drafts); } if let Some(cap) = ended { decision["read_ended"] = json!(cap); diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index 8b359a0..6d4757d 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -484,9 +484,10 @@ fn k24_a_failed_later_call_keeps_what_was_already_decided() { } /// Soul at F.1 r9: the reply after a read gets her whole word budget, so a read is performed only when that fits the -/// wake's cap; and a draft the budget cuts off after a read is code's cut, not an unfinished line of hers. +/// wake's cap. A draft that runs past even the ceiling, or never closes, is cut before it opens (Soul's R5): the reply +/// after the read starts outside it, and she is told it was cut unfinished. #[test] -fn k24_the_reply_after_a_read_gets_her_whole_budget_and_a_cut_draft_is_not_hers() { +fn k24_the_reply_after_a_read_gets_her_whole_budget_and_a_runaway_draft_is_cut_before_it_opens() { let fixture = reading_room("quiet-beat.toml"); let words = crate::projection::tuning::Tuning::default().persona.words; let model = Scripted::new(|prompt| { @@ -504,10 +505,11 @@ fn k24_the_reply_after_a_read_gets_her_whole_budget_and_a_cut_draft_is_not_hers( let persona = &report["renders"][0]["persona"]; let decision = &report["renders"][0]["interpreter"]; assert_eq!(decision["reads"][0]["ok"], true, "a first segment at her whole budget still leaves the reply its own: {decision}"); - assert_eq!(persona["words"].as_u64(), Some(2 * words as u64), "her first segment and the whole reply after the read: {persona}"); - assert!(decision.get("unfinished").is_none() && decision["unfinished_cut_by_cap"].as_str().is_some_and(|text| text.starts_with("Deru, I opened it")), "{decision}"); + assert_eq!(persona["words"].as_u64(), Some(words as u64), "her first segment whole; the runaway draft is not in her stream: {persona}"); + assert!(!persona["prose"].as_str().unwrap().contains(""), "no unclosed draft in her stream: {persona}"); + assert!(decision["unfinished"].as_str().is_some_and(|text| text.starts_with("Deru, I opened it")) && decision["cut_by_cap"].is_array(), "{decision}"); let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); - assert!(!told.iter().any(|line| line.contains("finished writing")), "{told:?}"); + assert!(told.iter().any(|line| line.contains("finished writing")), "she is told: {told:?}"); } /// Soul at F.1 (72 calls reported, 76 made): every call of a reading wake is in the usage totals, the continuations and @@ -545,3 +547,24 @@ reads_per_wake = 1 assert!(told.contains(&"- He reached for GameCult/Lodur#12 on the forge and it was not read: he has read as much as one turn reads.".to_owned()), "{told:?}"); assert!(told.contains(&"- He reached for something to read and it was not read: the address was not in front of him.".to_owned()) && !told.join("\n").contains("made.up"), "a model's target is never told: {told:?}"); } + +/// Soul's R5, Nibu r1: a list answer of about 180 words is posted whole: the cap runs on to the draft's closing mark, +/// within twice her budget; past that ceiling the draft is dropped cleanly and told as cut unfinished. +#[test] +fn r5_the_cap_never_cuts_inside_a_draft() { + let words = crate::projection::tuning::Tuning::default().persona.words; + let list: String = (1..=60).map(|n| format!("item{n} is fine; ")).collect(); + let answer = format!("Meta asked for the list, so here it is. {}Meta, the list: {list}that is all. Done.", "thinking ".repeat(20)); + let capped = crate::projection::narrate::cap_prose(&answer, words); + assert!(capped.text.ends_with("that is all.") && capped.cut_draft.is_none(), "the draft whole: {}", capped.text); + let runaway = format!("Lead-in words here. Meta, {}", "word ".repeat(2 * words + 10)); + let cut = crate::projection::narrate::cap_prose(&format!("{runaway}"), words); + assert_eq!((cut.text.as_str(), cut.cut_draft.as_deref().is_some_and(|draft| draft.starts_with("Meta, word"))), ("Lead-in words here.", true), "{cut:?}"); + // Through the turn: the list is said whole. + let fixture = room("operator-warm.toml"); + let reply = answer.clone(); + let model = Scripted::new(move |_| reply.clone()); + let report = wake_of(&fixture, &model); + let said = report["renders"][0]["interpreter"]["said"][0]["text"].as_str().unwrap_or_default().to_owned(); + assert!(said.starts_with("Meta, the list:") && said.ends_with("that is all."), "{}", report["renders"][0]["interpreter"]); +} diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index 05ae9b5..91d85b9 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -386,6 +386,33 @@ pub(crate) fn cap_words(text: &str, max: usize) -> String { } } +/// Her prose held to her word budget without ever ending inside a draft (map 16.19.1; Soul's R5): a cut never leaves an +/// unclosed `` in her stream, so a continuation never runs on inside one. When the budget falls inside a draft, +/// the prose runs on to that draft's closing mark, up to a hard ceiling of twice the budget; past the ceiling, or with no +/// closing mark, it is cut before the draft opens, and the draft's words so far are `cut_draft`: unfinished, cut by the +/// cap, which she is told. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Capped { + pub text: String, + /// Whether the budget cut anything. + pub cut: bool, + pub cut_draft: Option, +} + +pub(crate) fn cap_prose(text: &str, max: usize) -> Capped { + let text = text.trim(); + let capped = cap_words(text, max); + let cut = capped.len() < text.len(); + let open = capped.rfind(DRAFT_OPEN).filter(|open| !capped[*open..].contains(DRAFT_CLOSE)); + let Some(open) = open else { return Capped { text: capped, cut, cut_draft: None } }; + let close = text[open..].find(DRAFT_CLOSE).map(|at| open + at + DRAFT_CLOSE.len()); + if let Some(close) = close.filter(|close| words(&text[..*close]) <= max.saturating_mul(2)) { + return Capped { text: text[..close].to_owned(), cut: close < text.len(), cut_draft: None }; + } + let partial = capped[open + DRAFT_OPEN.len()..].trim(); + Capped { text: text[..open].trim_end().to_owned(), cut: true, cut_draft: (!partial.is_empty()).then(|| partial.to_owned()) } +} + /// The byte just past the last sentence end in `text`: a `.`, `!`, `?` or `…` with any closing quotes or brackets after /// it, followed by whitespace or the end of the text; or a `。`, `!` or `?`, which ends a sentence where it stands. fn last_sentence_end(text: &str) -> Option {