diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 3d638c4..ce65cf5 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -22,15 +22,17 @@ //! mention or a reply target only for someone this packet showed her (`Packet::people`). She speaks only in the turn's //! room. Whether a line tells what she knows privately is a reading of its meaning, so it is the Interpreter's //! judgement over the private items the packet lists to it (`Packet::private`), never a word match here. Every refusal -//! and drop is reported. Nothing here posts: the commit (C3c) will. +//! and drop is reported. Every gap is typed (`GapKind`) and its quote located in her prose (`gap`). The prompt tells the +//! Interpreter what she can do this turn (`select::turn_words`), so a reach past it is a `missing_affordance` gap, not a +//! line that pretends. Nothing here posts: the commit (C3c) will. use ghostlight_persona_projection::SourceSpan; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use unicode_segmentation::UnicodeSegmentation; use super::narrate::{Model, heard_overlap, lived_stream}; -use super::select::Packet; +use super::select::{Packet, capitalized, turn_words}; use super::tuning::Tuning; /// The most lines she says in one turn. @@ -43,14 +45,68 @@ const ECHO_OVERLAP: f64 = 0.8; /// What to say, where, to whom, and the gaps: Huginn's chat Interpreter, beside nothing of Ghostlight's but its span rule. const SPEECH_PROMPT: &str = "You decide what one person says aloud in a chat room this turn, from her own prose. You never write her words: you cite them. -Below are who she is, the room and who is in it, what reached her, her lived moment, and her prose. Decide which words of her prose she chooses to say aloud now, in this room. A line is speech only when her prose shows her choosing to say it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that she says nothing, is not speech. Words she recalls or quotes from someone else are never her speech. +Below are who she is, what she can do here, the room and who is in it, what reached her, her lived moment, and her prose. Decide which words of her prose she chooses to say aloud now, in this room. A line is speech only when her prose shows her choosing to say it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that she says nothing, is not speech. Words she recalls or quotes from someone else are never her speech. She speaks only in this room. What she knows privately is listed below as private: she says none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a line fits who is listening is yours to judge. Answer with one JSON object and nothing else: -{\"say\": [{\"spans\": [\"\"], \"mentions\": [\"\"], \"reply_to\": \"\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere\", \"quote\": \"\", \"detail\": \"\"}]} +{\"say\": [{\"spans\": [\"\"], \"mentions\": [\"\"], \"reply_to\": \"\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere | missing_affordance\", \"quote\": \"\", \"detail\": \"\"}]} -A line is whole sentences of her prose, the words she would type and nothing she only describes: each span is one sentence or several, from its first character to its last, and the spans of one line are consecutive sentences. A quotation that stands as sentences of its own may be cited sentence by sentence; words quoted inside a sentence of narration are cited only with that whole sentence, and then only if that sentence is what she says. She never says half a sentence; if only part of a sentence is speech, she says nothing of it. At most two lines. Record a gap instead of guessing: conditional when she might say something but has not chosen to, addressee when she means to say it but whom to is unclear, elsewhere when she means it for another room or another time. An empty say list is the usual answer in a busy room."; +A line is whole sentences of her prose, the words she would type and nothing she only describes: each span is one sentence or several, from its first character to its last, and the spans of one line are consecutive sentences. A quotation that stands as sentences of its own may be cited sentence by sentence; words quoted inside a sentence of narration are cited only with that whole sentence, and then only if that sentence is what she says. She never says half a sentence; if only part of a sentence is speech, she says nothing of it. At most two lines. Record a gap instead of guessing: conditional when she might say something but has not chosen to, addressee when she means to say it but whom to is unclear, elsewhere when she means it for another room or another time, missing_affordance when she reaches for something her body cannot do this turn (what she can do here is listed below). An empty say list is the usual answer in a busy room."; + +/// What a gap is (map 16.16): words she meant and did not say now, and why. Typed by code from the model's `kind`; a kind +/// the contract does not name is kept as `Unresolved` and reported, never dropped. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum GapKind { + /// She might say it, and has not chosen to. + Conditional, + /// She means to say it, and whom to is unclear. + Addressee, + /// She means it for another room or another time. + Elsewhere, + /// She reaches for something her body cannot do this turn: a tool request in waiting (section 4.2). + MissingAffordance, + Unresolved, +} + +impl GapKind { + fn of(kind: &str) -> Self { + match kind.trim() { + "conditional" => Self::Conditional, + "addressee" => Self::Addressee, + "elsewhere" => Self::Elsewhere, + "missing_affordance" => Self::MissingAffordance, + _ => Self::Unresolved, + } + } +} + +/// One gap as the report keeps it: its typed kind (with what the model declared when that is no kind), her words, and +/// whether they were located in her prose by `SourceSpan::locate`, as a speech span is. A located quote is her prose's own +/// words, verbatim, with their bytes; an unlocated one is the model's, marked so, and is never shown to her (K9). The +/// model's `detail` is kept for the trace and is never what she is told. +fn gap(prose: &str, raw: &Value) -> Value { + let kind = GapKind::of(raw.get("kind").and_then(Value::as_str).unwrap_or_default()); + let quote = raw.get("quote").and_then(Value::as_str).unwrap_or_default().trim(); + let mut gap = json!({ "kind": kind, "detail": raw.get("detail").cloned().unwrap_or(Value::Null) }); + if kind == GapKind::Unresolved { + gap["declared"] = raw.get("kind").cloned().unwrap_or_else(|| raw.clone()); + } + match (!quote.is_empty()).then(|| SourceSpan::locate(prose, quote)).flatten() { + Some(found) => { + gap["quote"] = json!(found.verbatim()); + gap["located"] = json!(true); + gap["start_byte"] = json!(found.start_byte()); + gap["end_byte"] = json!(found.end_byte()); + } + None => { + gap["quote"] = json!(quote); + gap["located"] = json!(false); + } + } + gap +} #[derive(Debug, Deserialize)] struct Answer { @@ -83,8 +139,9 @@ pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str) -> St private.push_str("- none\n"); } format!( - "{SPEECH_PROMPT}\n\nWho she is:\n{}\n\nThe room: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat she knows privately, none of it to be said here:\n{private}\nWhat reached her:\n{}\n\nHer lived moment:\n{}\n\nHer prose:\n{prose}", + "{SPEECH_PROMPT}\n\nWho she is:\n{}\n\nWhat she can do here:\n{}.\n\nThe room: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat she knows privately, none of it to be said here:\n{private}\nWhat reached her:\n{}\n\nHer lived moment:\n{}\n\nHer prose:\n{prose}", packet.name, + capitalized(&turn_words(&packet.affordances, packet.forms)), packet.room.as_deref().unwrap_or("none"), packet.room_kind.words(), packet.stimulus, @@ -266,8 +323,9 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra let Some(parsed) = json_of(&answer.text) else { return json!({ "failed": "the answer is not the speech contract's JSON", "raw": answer.text, "usage": answer.usage }); }; + let gaps: Vec = parsed.gaps.iter().map(|raw| gap(prose, raw)).collect(); let Some(room) = packet.room.clone() else { - return json!({ "said": [], "refused": [{ "why": "the turn has no room to speak in" }], "gaps": parsed.gaps, "usage": answer.usage }); + return json!({ "said": [], "refused": [{ "why": "the turn has no room to speak in" }], "gaps": gaps, "usage": answer.usage }); }; let shown = |id: &str| packet.people.iter().any(|(_, person)| person == id); let mut said: Vec = Vec::new(); @@ -301,7 +359,7 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra }; said.push(json!({ "room": room, "text": text, "mentions": mentions, "reply_to": reply_to, "rests_on": spans, "dropped": { "mentions": unknown, "reply_to": unknown_reply } })); } - json!({ "room": room, "room_kind": packet.room_kind, "said": said, "refused": refused, "gaps": parsed.gaps, "usage": answer.usage }) + json!({ "room": room, "room_kind": packet.room_kind, "said": said, "refused": refused, "gaps": gaps, "usage": answer.usage }) } #[cfg(test)] diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 28f13e3..46f92de 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -341,3 +341,51 @@ fn the_prompt_is_hugins_chat_prompt_with_the_room_its_kind_and_who_is_in_it() { assert!(prompt.contains(rule), "{rule}"); } } + +/// The gaps of a decision whose answer says nothing and records `gaps`. +fn gaps_of(packet: &Packet, prose: &str, gaps: serde_json::Value) -> Vec { + let reply = json!({ "say": [], "gaps": gaps }).to_string(); + let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone()); + decide(&model, "test", packet, "The room is warm.", prose, &Tuning::default())["gaps"].as_array().unwrap().clone() +} + +#[test] +fn a_reach_for_what_her_body_cannot_do_is_a_missing_affordance_gap_in_her_own_words() { + // Recorded model: her prose reaches for a sound's shape; this turn has no way to render one. + let prose = "Kiko's sound is still going round. I want to see the shape of that. Maybe later."; + let gaps = gaps_of(&packet(), prose, json!([{ "kind": "missing_affordance", "quote": "I want to see the shape of that.", "detail": "she cannot render a spectrogram in a chat turn" }])); + assert_eq!(gaps.len(), 1, "{gaps:?}"); + let gap = &gaps[0]; + assert_eq!((gap["kind"].as_str(), gap["quote"].as_str(), gap["located"].as_bool()), (Some("missing_affordance"), Some("I want to see the shape of that."), Some(true)), "{gap}"); + let (start, end) = (gap["start_byte"].as_u64().unwrap() as usize, gap["end_byte"].as_u64().unwrap() as usize); + assert_eq!(&prose[start..end], "I want to see the shape of that.", "her words are located in her prose, verbatim"); +} + +#[test] +fn an_unknown_gap_kind_is_kept_as_unresolved_and_an_unlocated_quote_is_marked() { + let prose = "I could tell Nibu. Not yet."; + let gaps = gaps_of(&packet(), prose, json!([ + { "kind": "regret", "quote": "Not yet." }, + { "kind": "conditional", "quote": "I will tell Nibu tomorrow." }, + "a gap that is not an object", + ])); + assert_eq!(gaps.len(), 3, "no gap is dropped: {gaps:?}"); + assert_eq!((gaps[0]["kind"].as_str(), gaps[0]["declared"].as_str(), gaps[0]["located"].as_bool()), (Some("unresolved"), Some("regret"), Some(true)), "{}", gaps[0]); + assert_eq!((gaps[1]["kind"].as_str(), gaps[1]["located"].as_bool()), (Some("conditional"), Some(false)), "words not in her prose are never located: {}", gaps[1]); + assert_eq!((gaps[2]["kind"].as_str(), gaps[2]["declared"].as_str(), gaps[2]["located"].as_bool()), (Some("unresolved"), Some("a gap that is not an object"), Some(false)), "{}", gaps[2]); + // A turn with no room still types its gaps. + let mut roomless = packet(); + roomless.room = None; + assert_eq!(gaps_of(&roomless, prose, json!([{ "kind": "elsewhere", "quote": "I could tell Nibu." }]))[0]["kind"], "elsewhere"); +} + +#[test] +fn the_interpreter_is_told_what_she_can_do_here_from_the_packets_affordances() { + // Heimdall's packet: the turn line is in his pronouns. + let prompt = speech_prompt(&packet(), "x", "y"); + assert!(prompt.contains("What she can do here:\nThis turn the room reaches him as typed lines, and he can answer in the turn's room by typing lines of his own; nothing he does here builds, changes or ships anything.\n\nThe room:"), "{prompt}"); + assert!(prompt.contains("missing_affordance when she reaches for something her body cannot do this turn"), "{prompt}"); + let mut listening = packet(); + listening.affordances = vec![Affordance::Perceive]; + assert!(speech_prompt(&listening, "x", "y").contains("What she can do here:\nThis turn the room reaches him as typed lines; nothing"), "derived from the affordances, not a constant"); +} diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 01cc94c..53c0cc4 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -1252,7 +1252,7 @@ fn minutes(now: DateTime, at_ms: u64) -> i64 { // Her body. /// `word` with its first letter upper-cased. -fn capitalized(word: &str) -> String { +pub(crate) fn capitalized(word: &str) -> String { let mut chars = word.chars(); chars.next().map_or_else(String::new, |first| format!("{}{}", first.to_uppercase(), chars.as_str())) } diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 38b6dec..333a561 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -265,6 +265,7 @@ mind_body::projection::harness: pub use super :: simulate :: simulate ; mind_body::projection::harness: struct Fixture # [derive (Clone , Debug)] pub-fields[her: String, names: Vec < String >, kind: TurnKind, now: DateTime < Utc >, here: Option < String >, operators: Vec < String >, minds: Vec < String >, last_heard: Vec < (String , u64) >] mind_body::projection::harness: struct Harness< 'a > pub-fields[instance: String, persona: Option < & 'a dyn PersonaSource >, model: Option < & 'a dyn Model >, tuning: PathBuf] mind_body::projection::harness: struct Message # [derive (Clone , Debug , Deserialize)] pub-fields[from: String, name: String, room: String, ago: Option < String >, round: Option < usize >, says: String, new: bool, tag: bool, mentions: Vec < String >, dm: bool, to: Option < String >, follow_up: bool, reply_to: Option < usize >] +mind_body::projection::interpret: impl GapKind mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Result < String > mind_body::projection::narrate: impl Failed mind_body::projection::narrate: impl KitModel