diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 07e9463..f41c9de 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -42,7 +42,7 @@ use serde_json::{Value, json}; use super::Affordance; use super::commit::{Evidence, How, Proposal}; -use super::read::{Asked, QUOTE_MIN_WORDS, resolve}; +use super::read::{Asked, QUOTE_MIN_WORDS, SPAN_MIN_WORDS, resolve}; use super::narrate::{Model, heard_overlap, lived_stream, words}; use super::select::{Forms, Packet, capitalized, spoken, turn_words, voiced}; use super::tuning::Tuning; @@ -712,14 +712,20 @@ fn reading(raw: &Value, packet: &Packet, prose: &str, found: &Drafts, wake: Wake return Err("no_read_here"); } let asked: Asked = serde_json::from_value(raw.clone()).map_err(|_| "not_the_contract")?; - let quote = asked.quote.trim(); - let located = (words(quote) >= QUOTE_MIN_WORDS) - .then(|| found.thought(prose).into_iter().filter(|(_, end)| *end > wake.from).find_map(|(start, end)| { + // The reach is located in her thought in this segment: the Interpreter's quote, or failing that the longest run of at + // least `SPAN_MIN_WORDS` of its words found there (Soul's R5: a short or loose quote is the Interpreter's fault, not + // hers). When nothing of it is found, the read is refused, reported, and never told to her. + let quote: Vec<&str> = asked.quote.split_whitespace().collect(); + let locate = |text: &str| { + found.thought(prose).into_iter().filter(|(_, end)| *end > wake.from).find_map(|(start, end)| { let start = start.max(wake.from); - SourceSpan::locate(&prose[start..end], quote).map(|span| prose[start + span.start_byte()..start + span.end_byte()].to_owned()) - })) - .flatten() - .ok_or("quote_not_in_her_thought")?; + SourceSpan::locate(&prose[start..end], text).map(|span| prose[start + span.start_byte()..start + span.end_byte()].to_owned()) + }) + }; + let whole = (quote.len() >= QUOTE_MIN_WORDS).then(|| locate("e.join(" "))).flatten(); + let located = whole + .or_else(|| (SPAN_MIN_WORDS..=quote.len()).rev().find_map(|size| quote.windows(size).find_map(|span| locate(&span.join(" "))))) + .ok_or("quote_not_located")?; // In front of her is her prose and what she was sent, never what she read: a read cannot chain from a fetched page // (Soul's p1b), so no page can steer her to the next. let reached: Vec = packet.bodies.iter().cloned().chain(std::iter::once(packet.heard.clone())).collect(); diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index badbbf9..7ce1503 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -785,7 +785,7 @@ fn k24_a_read_is_what_her_thought_reaches_for_and_nothing_a_model_made_up() { let invented = asked(&reading, prose, json!({ "kind": "web", "target": "http://evil.example/x", "quote": "I want to see what Nibu actually changed" })); assert_eq!((invented["read"].clone(), invented["read_refused"][0]["why"].as_str()), (Value::Null, Some("web_address_not_in_front_of_her")), "{invented}"); let unquoted = asked(&reading, prose, json!({ "kind": "domain", "target": "d1", "quote": "she should read the repo" })); - assert_eq!(unquoted["read_refused"][0]["why"], "quote_not_in_her_thought"); + assert_eq!(unquoted["read_refused"][0]["why"], "quote_not_located"); let not_ours = asked(&reading, prose, json!({ "kind": "repo", "target": "Elsewhere/Lodur", "quote": "I want to see what Nibu actually changed" })); assert_eq!(not_ours["read_refused"][0]["why"], "not_a_gamecult_repo"); let cannot = asked(&packet(), prose, json!({ "kind": "domain", "target": "d1", "quote": "I want to see what Nibu actually changed" })); @@ -842,3 +842,23 @@ fn k24_a_read_never_chains_from_what_she_read() { let decision = decide_in(&model, "test", &reading, "The room is warm.", &prose, &Tuning::default(), wake); assert_eq!((decision["read"].clone(), decision["read_refused"][0]["why"].as_str()), (Value::Null, Some("web_address_not_in_front_of_her")), "{decision}"); } + +/// Soul's R5: a loose quote is located from a run of at least three of its words in her segment; a quote with nothing of +/// it there, and a malformed target (a digest id inside a repo target), are refused and never told to her as hers. +#[test] +fn r5_a_loose_quote_is_located_and_an_interpreter_fault_is_never_hers() { + let prose = "I want to see what Nibu actually changed in the knee. And GameCult/Bifrost too."; + let reading = reading_packet(); + let loose = asked(&reading, prose, json!({ "kind": "domain", "target": "d1", "quote": "she wants to see what Nibu actually changed today" })); + assert_eq!(loose["read"]["quote"], "to see what Nibu actually changed", "the longest run found: {loose}"); + let short = asked(&reading, prose, json!({ "kind": "domain", "target": "d1", "quote": "the knee" })); + assert_eq!(short["read_refused"][0]["why"], "quote_not_located", "{short}"); + for (kind, target) in [("repo", "GameCult/Bifrost#d3"), ("repo", "d3"), ("domain", "GameCult/Bifrost")] { + let malformed = asked(&reading, prose, json!({ "kind": kind, "target": target, "quote": "I want to see what Nibu actually changed" })); + assert_eq!(malformed["read_refused"][0]["why"], "malformed_target", "{target}: {malformed}"); + } + let mut decision = short.clone(); + decision["read_refused"].as_array_mut().unwrap().push(json!({ "read": {}, "why": "malformed_target" })); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap(); + assert!(outcome.lines(packet().forms).is_empty() && outcome.omitted.len() == 2, "reported, never told: {:?}", outcome.omitted); +} diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index c21c425..d3b89c6 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -242,7 +242,8 @@ pub(crate) fn outcome_of(record: &Value) -> Option { } for refused in decision["read_refused"].as_array().into_iter().flatten() { match serde_json::from_value::(refused["why"].clone()) { - Ok(why) => outcome.parts.push(Part::ReadRefused { what: words(&refused["what"]).filter(|_| why.cap()), why }), + Ok(why) if why.told() => outcome.parts.push(Part::ReadRefused { what: words(&refused["what"]).filter(|_| why.cap()), why }), + Ok(_) => outcome.omitted.push(format!("a read refused for the Interpreter's fault, not hers: {refused}")), Err(_) => outcome.omitted.push(format!("a refused read she cannot be told truly: {refused}")), } } diff --git a/crates/mind-body/src/projection/read.rs b/crates/mind-body/src/projection/read.rs index 9756b1a..67b6c13 100644 --- a/crates/mind-body/src/projection/read.rs +++ b/crates/mind-body/src/projection/read.rs @@ -29,6 +29,8 @@ use crate::queue::{any_of, of_kind}; /// The fewest words of her thought a read must quote: fewer say nothing of what she reached for. pub(crate) const QUOTE_MIN_WORDS: usize = 4; +/// The fewest words of a run of the quote that locate her reach when the whole quote is not found. +pub(crate) const SPAN_MIN_WORDS: usize = 3; /// The most bytes a fetched body may be before it is refused as too large, before any clipping. const BODY_MAX_BYTES: usize = 1024 * 1024; /// How many hits a recall over her mind returns, and how many rulings a campaign read shows. @@ -122,6 +124,8 @@ pub(crate) enum ReadRefusal { NoReadHere, NotTheContract, QuoteNotInHerThought, + QuoteNotLocated, + MalformedTarget, NoSuchDomainLine, NoRecallWords, NotAGamecultRepo, @@ -132,6 +136,13 @@ pub(crate) enum ReadRefusal { } impl ReadRefusal { + /// Whether she is told of it: a cap, a turn that cannot read, an address not in front of her, a repo outside + /// GameCult. A refusal that is the Interpreter's fault (a quote it could not locate, a malformed or unknown target, an + /// answer off the contract) is reported and never told to her as hers (Soul's R5). + pub(crate) fn told(self) -> bool { + matches!(self, Self::ReadsPerWake | Self::WakeReadBytes | Self::ProseWords | Self::NoReadHere | Self::WebAddressNotInFrontOfHer | Self::NotAGamecultRepo) + } + /// Whether a cap refused it: then the read was resolved, and what it was can be told. pub(crate) fn cap(self) -> bool { matches!(self, Self::ReadsPerWake | Self::WakeReadBytes | Self::ProseWords) @@ -142,7 +153,8 @@ impl ReadRefusal { match self { Self::NoReadHere => "that turn could not read".to_owned(), Self::NotTheContract => "the read could not be named".to_owned(), - Self::QuoteNotInHerThought => format!("nothing in {poss} thought reached for it"), + Self::QuoteNotInHerThought | Self::QuoteNotLocated => format!("nothing in {poss} thought reached for it"), + Self::MalformedTarget => "the read could not be named".to_owned(), Self::NoSuchDomainLine => format!("it is no line of what moved in {poss} domain"), Self::NoRecallWords => "there was nothing to recall by".to_owned(), Self::NotAGamecultRepo => "it is not a public GameCult repo".to_owned(), @@ -183,13 +195,19 @@ fn repo_target(target: &str) -> Option<&str> { pub(crate) fn resolve(asked: &Asked, packet: &Packet, prose: &str, reached: &[String]) -> Result { let target = asked.target.trim(); match asked.kind { + Kind::Domain if !digest_id(target) => Err("malformed_target"), Kind::Domain => packet.domain.iter().find(|line| line.id == target).map(|line| match &line.about { About::Repo(repo) => ReadRequest::Repo(repo.clone()), About::Campaign(slug) => ReadRequest::Campaign(slug.clone()), }).ok_or("no_such_domain_line"), Kind::Mind if !target.is_empty() && target.len() <= 200 => Ok(ReadRequest::Mind(target.to_owned())), Kind::Mind => Err("no_recall_words"), - Kind::Repo => repo_target(target).map(|target| ReadRequest::Repo(target.to_owned())).ok_or("not_a_gamecult_repo"), + // A digest id resolves only as a domain item, never inside a repo target (`GameCult/Bifrost#d3`, Soul's R5). + Kind::Repo => match repo_target(target) { + Some(target) => Ok(ReadRequest::Repo(target.to_owned())), + None if target.starts_with("GameCult/") || digest_id(target) => Err("malformed_target"), + None => Err("not_a_gamecult_repo"), + }, Kind::Web => { let url = (target.starts_with("http://") || target.starts_with("https://")) && !target.contains(char::is_whitespace); let reached_for = prose.contains(target) || reached.iter().any(|text| text.contains(target)); @@ -198,6 +216,11 @@ pub(crate) fn resolve(asked: &Asked, packet: &Packet, prose: &str, reached: &[St } } +/// Whether `target` is a digest id: `d` and a number. +fn digest_id(target: &str) -> bool { + target.strip_prefix('d').is_some_and(|number| !number.is_empty() && number.chars().all(|c| c.is_ascii_digit())) +} + /// `text` held to `max` bytes on a character boundary, with a counted mark of what was cut. pub(crate) fn clipped(text: &str, max: usize) -> String { if text.len() <= max {