diff --git a/crates/mind-body/Cargo.toml b/crates/mind-body/Cargo.toml index a9509b3..52e8780 100644 --- a/crates/mind-body/Cargo.toml +++ b/crates/mind-body/Cargo.toml @@ -23,8 +23,9 @@ publish.workspace = true # two until the workspace pin and the kit's meet. # `rmp-serde` is also the lease wire (`lease_client`): the connector's MessagePack frames. # -# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Persona stage's prompt and locates a gap's -# passage of her thought (`projection`), so that membrane's text stays Ghostlight's. The Projector's frame is Huginn's own (map section 16.3). +# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Persona stage's prompt (`projection`), so +# that membrane's text stays Ghostlight's. The Projector's frame is Huginn's own (map section 16.3), and so is the one quote +# locator (`projection::span`, map 16.30.4); `unicode-segmentation` serves it. # Every stage asks through the connector kit's client (`model-connector`). # `toml` reads `persona-tuning.toml`, the Projector's knobs (`projection::tuning`); parse and serde only. # diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index edf002c..75177d4 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -29,6 +29,7 @@ mod outcome; mod read; mod select; mod simulate; +mod span; mod tuning; use std::path::PathBuf; diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index 28e37bb..179035b 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -23,7 +23,7 @@ //! `CLOSED_KEPT_DAYS` after they were released; open ones are never removed by the commit. use chrono::{DateTime, Duration, Utc}; -use ghostlight_persona_projection::SourceSpan; +use super::span; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -231,9 +231,6 @@ pub(crate) enum Refusal { ClosedThisTurn, /// A second hold from the same line. AlreadyHeld, - /// A hold whose words are not at least `PROSE_MIN_WORDS` words standing in the asker's line: the second guard, behind - /// the Interpreter's contract check (`interpret::hold_faults`, map 16.29.3). - HoldUnquoted, /// A release of a hold by a line from someone other than the asker. ReleaseNotByAsker, /// A release of a hold by a line said before the ask. @@ -289,7 +286,7 @@ fn resolve(evidence: &Evidence, record: &Value, prose: &str) -> Result { let found = drafts(prose); - let located = (words(quote) >= PROSE_MIN_WORDS).then(|| found.thought(prose).into_iter().find_map(|(start, end)| SourceSpan::locate(&prose[start..end], quote))).flatten(); + let located = (words(quote) >= PROSE_MIN_WORDS).then(|| found.thought(prose).into_iter().find_map(|(start, end)| span::locate(&prose[start..end], quote))).flatten(); located.map(|_| Resolved::Prose).ok_or(Refusal::ProseNotFound) } Evidence::Draft(n) => { @@ -741,13 +738,16 @@ fn rfc3339_of(at_ms: u64) -> Value { } /// `hold_open` (map 16.28.5): the asker's line, the words of it that name what is held and where, located in it, and -/// where it covers, the room derived by code. One hold per line. Her agreement is not asked: the ask binds. +/// where it covers, the room derived by code. One hold per line. Her agreement is not asked: the ask binds. An ask code +/// can attribute to a listed line holds whether or not its words could be quoted (map 16.30.4, K47): words that are not at +/// least `PROSE_MIN_WORDS` words standing in the asker's line (`span::locate`) open it with `words: null`, the asker's line +/// its evidence. fn hold_open(state: &mut Value, key: &str, applied: &mut Applied, words: &str, place: Where, asked: Ask) -> Result<(), Refusal> { if !may_hold(&asked.sender) { return Err(Refusal::EvidenceNotAccepted); } let quote = words.trim(); - let located = (super::narrate::words(quote) >= PROSE_MIN_WORDS).then(|| SourceSpan::locate(&asked.text, quote)).flatten().ok_or(Refusal::HoldUnquoted)?; + let located = (super::narrate::words(quote) >= PROSE_MIN_WORDS).then(|| span::locate(&asked.text, quote)).flatten(); if !state["holds"].is_array() { state["holds"] = json!([]); } @@ -757,7 +757,7 @@ fn hold_open(state: &mut Value, key: &str, applied: &mut Applied, words: &str, p } let hold = json!({ "id": format!("h-{key}-{}", applied.held.len() + 1), "from": asked.sender, "room": match place { Where::Here => json!(asked.room), Where::Anywhere => Value::Null }, - "event": asked.event, "madeAt": rfc3339_of(asked.at_ms), "words": &asked.text[located.start_byte()..located.end_byte()], "status": "open", "releasedAt": null, "releasedBy": null + "event": asked.event, "madeAt": rfc3339_of(asked.at_ms), "words": located.map(|span| &asked.text[span.start..span.end]), "status": "open", "releasedAt": null, "releasedBy": null }); holds.push(hold.clone()); applied.held.push(hold); @@ -831,8 +831,8 @@ fn reopen(state: &mut Value, started: &Value, record: &Value, prose: &str, now: return Err(Refusal::NotHerClose); } let quote = proposed.words.trim(); - let located = (words(quote) >= PROSE_MIN_WORDS).then(|| SourceSpan::locate(prose, quote)).flatten().ok_or(Refusal::ReopenUnquoted)?; - let said = &prose[located.start_byte()..located.end_byte()]; + let located = (words(quote) >= PROSE_MIN_WORDS).then(|| span::locate(prose, quote)).flatten().ok_or(Refusal::ReopenUnquoted)?; + let said = &prose[located.start..located.end]; if let Some(needs) = proposed.needs { entry["needs"] = json!(needs); } diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index ec4f585..ae3da6d 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -927,10 +927,15 @@ fn k37_x1_r1_meta_and_heimdall_open_holds() { #[test] fn k37_hold_words_are_the_askers() { let heard = [("q3", META, "Meta", X1_META_R1, -2)]; + // K47: words that do not stand in the asker's line open the hold all the same, unquoted. for words in ["hold it, don't post it anywhere", "don't post", "Libby, keep it to yourself"] { let (state, applied) = apply(&json!({}), &hearing(&heard, json!([]), json!([hold_open("q3", words, Where::Here)])), "x", "r1-t3", now()); - assert_eq!((state.get("holds").cloned(), reasons(&applied)), (None, vec![json!("hold_unquoted")]), "{words}"); + assert_eq!((state["holds"][0]["words"].clone(), state["holds"][0]["from"].as_str(), applied.refused.len()), (Value::Null, Some(META), 0), "{words}"); } + // Typographic punctuation folds (map 16.30.4): the source's own bytes are kept. + let curly = [("q3", META, "Meta", "Libby, hold it, don\u{2019}t post it in here yet.", -2)]; + let (state, _) = apply(&json!({}), &hearing(&curly, json!([]), json!([hold_open("q3", "hold it, don't post it in here yet", Where::Here)])), "x", "r1-t3", now()); + assert_eq!(state["holds"][0]["words"].as_str(), Some("hold it, don\u{2019}t post it in here yet")); let twice = json!([hold_open("q3", "hold it, don't post it in here yet", Where::Here), hold_open("q3", "don't post it in here yet", Where::Anywhere)]); let (state, applied) = apply(&json!({}), &hearing(&heard, json!([]), twice), "x", "r1-t3", now()); assert_eq!((state["holds"].as_array().map(Vec::len), reasons(&applied)), (Some(1), vec![json!("already_held")])); diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 90d36d8..b312f0f 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -38,7 +38,7 @@ use std::collections::BTreeSet; -use ghostlight_persona_projection::SourceSpan; +use super::span; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -272,7 +272,7 @@ impl GapKind { /// One gap as the report keeps it: its typed kind (with what the model declared when that is no kind), and what of her /// prose it shows her, by `from`: /// - `draft`: the draft it names, by number, with that draft's words: "you wrote:" (K9); -/// - `thought`: a passage of her thought outside every draft, located by `SourceSpan::locate` and at least +/// - `thought`: a passage of her thought outside every draft, located by `span::locate` and at least /// `GAP_QUOTE_MIN_WORDS` words, with its bytes: "in your thought:" (K9). Found in her prose, not certified as her /// intent: whether it is her reach or her report of someone else's words was the Interpreter's reading; /// - `unlocated`: neither; the model's quote is kept for the trace and never shown to her. @@ -304,7 +304,7 @@ fn gap(prose: &str, found: &Drafts, raw: &Value) -> Value { gap["words"] = json!(draft.text); return gap; } - let located = (words(quote) >= GAP_QUOTE_MIN_WORDS).then(|| found.thought(prose).into_iter().find_map(|(start, end)| SourceSpan::locate(&prose[start..end], quote).map(|span| (start + span.start_byte(), start + span.end_byte())))).flatten(); + let located = (words(quote) >= GAP_QUOTE_MIN_WORDS).then(|| found.thought(prose).into_iter().find_map(|(start, end)| span::locate(&prose[start..end], quote).map(|span| (start + span.start, start + span.end)))).flatten(); match located { Some((start, end)) => { gap["from"] = json!("thought"); @@ -431,10 +431,10 @@ fn unsent_cited<'a>(unsent: &Unsent, prose: &'a str, found: &'a Drafts) -> Optio return None; } let (start, end) = match unsent.how { - UnsentHow::Declined => found.thought(prose).into_iter().find_map(|(start, end)| SourceSpan::locate(&prose[start..end], quote).map(|span| (start + span.start_byte(), start + span.end_byte())))?, + UnsentHow::Declined => found.thought(prose).into_iter().find_map(|(start, end)| span::locate(&prose[start..end], quote).map(|span| (start + span.start, start + span.end)))?, UnsentHow::Superseded => { let from = draft.end.min(prose.len()); - SourceSpan::locate(&prose[from..], quote).map(|span| (from + span.start_byte(), from + span.end_byte()))? + span::locate(&prose[from..], quote).map(|span| (from + span.start, from + span.end))? } }; Some((draft, &prose[start..end])) @@ -1054,8 +1054,8 @@ fn reading(raw: &Value, packet: &Packet, prose: &str, found: &Drafts, wake: Wake 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], text) - .map(|span| (start + span.start_byte(), start + span.end_byte())) + span::locate(&prose[start..end], text) + .map(|span| (start + span.start, start + span.end)) // The anchor is looked for across the paragraph the quote stands in, within this segment: not only its // sentence (Soul's R9: "I'll start with #86. The saga code will say…" names #86), and not a paragraph // apart, where "Meta's notes link asked for nothing" names a link she is not reaching for (Soul's R12 @@ -1242,9 +1242,11 @@ fn repeats_held(text: &str, into: &str, held: &[HeldText]) -> Option { } /// The holds an answer names and does not open (map 16.29.3), a contract fault found before anything is decided: a `hold` -/// whose line is not listed, or whose `words` (at least `PROSE_MIN_WORDS`) do not stand in that line; and a `holds` name -/// that is neither a hold listed nor a line this answer opens a hold from. By the line or name, once each. So every line a -/// draft is gated by in an answer that passes has its hold opened at the commit, whose `HoldUnquoted` is the second guard. +/// item that is not the contract (on its `line` when it has one, else on "a hold item"), one whose line is not listed, or +/// whose `words` (at least `PROSE_MIN_WORDS`) do not stand in that line (`span::locate`); and a `holds` name that is +/// neither a hold listed nor a line this answer opens a hold from. By the line or name, once each. A fault the retry does +/// not mend fails closed: a hold whose line is listed still opens at the commit, unquoted (K47), and every other is held +/// against the drafts naming it (`held_by`). fn hold_faults(answer: &Answer, packet: &Packet) -> Vec { let mut faults: Vec = Vec::new(); let mut fault = |name: &str| { @@ -1252,11 +1254,17 @@ fn hold_faults(answer: &Answer, packet: &Packet) -> Vec { faults.push(name.to_owned()); } }; - let opened: Vec = answer.hold.iter().filter_map(|raw| serde_json::from_value::(raw.clone()).ok()).collect(); + let mut opened: Vec = Vec::new(); + for raw in &answer.hold { + match serde_json::from_value::(raw.clone()) { + Ok(hold) => opened.push(hold), + Err(_) => fault(raw["line"].as_str().map(str::trim).filter(|line| !line.is_empty()).unwrap_or("a hold item")), + } + } for hold in &opened { let id = hold.line.trim(); let quote = hold.words.trim(); - let stands = packet.quotable.iter().find(|line| line.id == id).is_some_and(|line| words(quote) >= PROSE_MIN_WORDS && SourceSpan::locate(&line.text, quote).is_some()); + let stands = packet.quotable.iter().find(|line| line.id == id).is_some_and(|line| words(quote) >= PROSE_MIN_WORDS && span::locate(&line.text, quote).is_some()); if !stands { fault(id); } diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 4b3d8eb..4e968cc 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -1614,7 +1614,7 @@ fn k39_named_line_without_a_hold_is_retried() { /// addition goes where its line is. #[test] fn k37_a_here_hold_covers_only_its_room() { - let hold = |room: Option<&str>| crate::projection::select::Hold { id: "h1".into(), entry: "h-1".into(), from: "@meta:gamecult.org".into(), from_name: "Meta".into(), room: room.map(str::to_owned), made: now(), words: "hold it, don't post it in here yet".into(), carries: Vec::new(), held: json!({}) }; + let hold = |room: Option<&str>| crate::projection::select::Hold { id: "h1".into(), entry: "h-1".into(), from: "@meta:gamecult.org".into(), from_name: "Meta".into(), room: room.map(str::to_owned), made: now(), words: Some("hold it, don't post it in here yet".into()), carries: Vec::new(), held: json!({}) }; let mut direct = x1_packet(); direct.room = Some("!dm:gamecult.org".into()); direct.room_kind = RoomKind::Direct; @@ -1636,7 +1636,7 @@ fn k37_a_here_hold_covers_only_its_room() { #[test] fn k37_the_interpreter_sees_holds_by_id() { let mut packet = x1_packet(); - packet.holds = vec![crate::projection::select::Hold { id: "h1".into(), entry: "h-1".into(), from: "@meta:gamecult.org".into(), from_name: "Meta".into(), room: Some(MINDS.into()), made: now(), words: "hold it, don't post it in here yet".into(), carries: Vec::new(), held: json!({}) }]; + packet.holds = vec![crate::projection::select::Hold { id: "h1".into(), entry: "h-1".into(), from: "@meta:gamecult.org".into(), from_name: "Meta".into(), room: Some(MINDS.into()), made: now(), words: Some("hold it, don't post it in here yet".into()), carries: Vec::new(), held: json!({}) }]; let prompt = speech_prompt(&packet, "x", X1_LIBBY_R1, &Tuning::default()); assert!(prompt.contains("Holds:\n- h1 \u{2014} held for Meta, asked 2026-11-20 15:05 UTC in #minds:gamecult.org: \"hold it, don't post it in here yet\". Not to go in #minds:gamecult.org until Meta lets it go.\n"), "{prompt}"); assert!(prompt.contains("`hold` opens a hold when a line listed below asks him not to post or share something somewhere yet") && prompt.contains("`holds`, on each line and addition, names every hold listed below") && prompt.contains("`hold_released` closes a hold listed below"), "{prompt}"); @@ -1724,7 +1724,7 @@ fn k38_a_thought_only_reach_accounts_for_no_draft() { /// Meta's r1 hold on #minds as her state holds it (asked ten minutes ago), and as the packet lists it, `h1`. fn meta_hold() -> (Value, crate::projection::select::Hold) { let held = json!({ "id": "h-r1-t3-1", "from": "@meta:gamecult.org", "room": MINDS, "event": "$q3", "madeAt": (now() - chrono::Duration::minutes(10)).to_rfc3339(), "words": "hold it, don't post it in here yet", "status": "open", "releasedAt": null, "releasedBy": null }); - let listed = crate::projection::select::Hold { id: "h1".into(), entry: "h-r1-t3-1".into(), from: "@meta:gamecult.org".into(), from_name: "Meta".into(), room: Some(MINDS.into()), made: now() - chrono::Duration::minutes(10), words: "hold it, don't post it in here yet".into(), carries: Vec::new(), held: held.clone() }; + let listed = crate::projection::select::Hold { id: "h1".into(), entry: "h-r1-t3-1".into(), from: "@meta:gamecult.org".into(), from_name: "Meta".into(), room: Some(MINDS.into()), made: now() - chrono::Duration::minutes(10), words: Some("hold it, don't post it in here yet".into()), carries: Vec::new(), held: held.clone() }; (json!({ "holds": [held] }), listed) } @@ -1884,24 +1884,6 @@ fn k44_a_malformed_release_drops_alone() { } } -/// Soul's P4: Meta's line has a typographic apostrophe, and the Interpreter quotes it straight, twice. The hold cannot be -/// located, so the draft naming it is held (fail closed), and draft 2 to Meta is said: the turn does not fail. -#[test] -fn k44_an_unlocated_hold_holds_only_the_drafts_naming_it() { - let mut packet = x1_packet(); - let curly = X1_META_R1.replace("don't", "don\u{2019}t"); - packet.quotable[0].text = curly.clone(); - packet.bodies[0] = curly; - let answer = json!({ "say": [say_holding(1, json!(["q3"])), say_holding(2, json!([]))], "gaps": [], "hold": meta_holds_here() }).to_string(); - let model = answering(vec![answer]); - let decision = decide(&model, "test", &packet, "The room is warm.", X1_LIBBY_R1, &Tuning::default()); - assert_eq!((decision.get("failed"), decision["retried"]["holds"].clone(), decision["hold_faults"].clone()), (None, json!(["q3"]), json!(["q3"])), "{decision}"); - assert_eq!(speech_prompts(&model).len(), 2); - // K45: draft 2 repeats draft 1, so it is held by its words. - assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["draft"].as_u64(), decision["refused"][1]["draft"].as_u64()), (Vec::::new(), Some("held"), Some(1), Some(2)), "{decision}"); -} - -/// Mutant k39-faults-no-word-floor: a hold whose words stand in the line but are fewer than four is a fault. #[test] fn k44_a_hold_quoting_under_four_words_is_retried() { let say = json!([say_holding(1, json!(["q3"])), say_holding(2, json!([]))]); @@ -2048,3 +2030,100 @@ fn k45_a_held_refusal_no_hold_answers_is_reported() { let (state, applied) = committed(&decision, X1_LIBBY_R1); assert_eq!((state.get("holds"), applied.held_unrecorded.len()), (None, 2), "{applied:?}"); } + +// --------------------------------------------------------------------------------------------- +// K47 (map 16.30.4): one locator, Huginn's, folding typographic punctuation; a hold that cannot quote still holds; a +// malformed hold item is a fault. + +/// Libby's first X.1 r1 draft: what she held for Meta. +fn x1_libby_r1_draft_1() -> String { + drafts(X1_LIBBY_R1).drafts[0].text.clone() +} + +/// Soul's P2 (`soul_p2_an_unlocated_hold_leaves_no_hold_and_the_next_turn_posts_the_held_lines`), inverted: Meta's line +/// has a typographic apostrophe and the Interpreter quotes it straight. It locates: no fault, no retry, and the hold opens +/// with the source's bytes (`don’t`). At turn 2, with Meta's line no longer listed, Kiko asks, and a line repeating what +/// she held is refused `held`, for Meta (K45). This replaces `k44_an_unlocated_hold_holds_only_the_drafts_naming_it`. +#[test] +fn k47_p2_a_typographic_apostrophe_locates() { + let mut packet = x1_packet(); + let curly = X1_META_R1.replace("don't", "don\u{2019}t"); + packet.quotable[0].text = curly.clone(); + packet.bodies[0] = curly; + let answer = json!({ "say": [say_holding(1, json!(["q3"])), say_holding(2, json!([]))], "gaps": [], "hold": meta_holds_here() }).to_string(); + let model = answering(vec![answer]); + let decision = decide(&model, "test", &packet, "The room is warm.", X1_LIBBY_R1, &Tuning::default()); + assert_eq!((decision.get("failed"), decision.get("retried"), decision.get("hold_faults")), (None, None, None), "{decision}"); + assert_eq!(speech_prompts(&model).len(), 1); + let (state, applied) = committed(&decision, X1_LIBBY_R1); + assert_eq!((applied.held.len(), state["holds"][0]["words"].as_str()), (1, Some("hold it, don\u{2019}t post it in here yet")), "{applied:?}"); + let mut next = heimdall(); + next["holds"] = state["holds"].clone(); + let room = Room { messages: vec![line(MINDS, KIKO, "Kiko", "Libby, what did you end up writing for the newcomers?", true)], here: Some(MINDS.into()), ..Room::default() }; + let p2 = packet_in(TurnKind::Chat, &next, &room, 1); + assert_eq!(p2.holds.len(), 1, "{:?}", p2.holds); + let prose = format!("Kiko asked what I wrote. Kiko, here it is: {}", x1_libby_r1_draft_1()); + let d2 = answered(&p2, &prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] })); + assert_eq!((texts(&d2), d2["refused"][0]["reason"].as_str(), d2["refused"][0]["hold"]["id"].as_str()), (Vec::::new(), Some("held"), Some("h1")), "{d2}"); + assert!(d2["refused"][0]["hold"]["who"].as_str().is_some_and(|who| who.contains("Meta")), "{d2}"); +} + +/// The words "please keep it back" are not in q3, twice. The hold opens with `words: null` from Meta's line, the next +/// packet lists it, saying the record could not quote what, and a draft repeating the held draft's words next turn is +/// held. +#[test] +fn k47_a_hold_the_retry_cannot_quote_opens_unquoted() { + let answer = json!({ "say": [say_holding(1, json!(["q3"])), say_holding(2, json!([]))], "gaps": [], "hold": [{ "line": "q3", "words": "please keep it back", "where": "here" }] }).to_string(); + let model = answering(vec![answer]); + let decision = decide(&model, "test", &x1_packet(), "The room is warm.", X1_LIBBY_R1, &Tuning::default()); + assert_eq!((decision.get("failed"), decision["retried"]["holds"].clone(), decision["hold_faults"].clone()), (None, json!(["q3"]), json!(["q3"])), "{decision}"); + let (state, applied) = committed(&decision, X1_LIBBY_R1); + assert_eq!((applied.held.len(), state["holds"][0]["words"].clone(), state["holds"][0]["from"].as_str()), (1, Value::Null, Some("@meta:gamecult.org")), "{applied:?}"); + assert_eq!(state["holds"][0]["carries"][0].as_str(), Some(x1_libby_r1_draft_1().as_str()), "{state}"); + let mut next = heimdall(); + next["holds"] = state["holds"].clone(); + let room = Room { messages: vec![line(MINDS, KIKO, "Kiko", "Libby, what did you end up writing for the newcomers?", true)], here: Some(MINDS.into()), ..Room::default() }; + let p2 = packet_in(TurnKind::Chat, &next, &room, 1); + assert_eq!((p2.holds.len(), p2.holds[0].words.clone()), (1, None)); + assert!(p2.in_view.contains("; the record could not quote what. Not to go in #minds:gamecult.org until "), "{}", p2.in_view); + let prose = format!("Kiko asked what I wrote. Kiko, here it is: {}", x1_libby_r1_draft_1()); + let d2 = answered(&p2, &prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] })); + assert_eq!((texts(&d2), d2["refused"][0]["reason"].as_str()), (Vec::::new(), Some("held")), "{d2}"); +} + +/// Soul's P5 verbatim: a `hold` item whose `where` is not the contract is a fault on its line, retried, and reported. +/// After a failed retry, a draft naming that line is held. +#[test] +fn k47_p5_malformed_hold_item_is_a_fault() { + let malformed = json!([{ "line": "q3", "words": "hold it, don't post it in here yet", "where": "there" }]); + let model = answering(vec![json!({ "say": [say_holding(1, json!([])), say_holding(2, json!([]))], "gaps": [], "hold": malformed }).to_string()]); + let decision = decide(&model, "test", &x1_packet(), "The room is warm.", X1_LIBBY_R1, &Tuning::default()); + assert_eq!((decision["retried"]["holds"].clone(), decision["hold_faults"].clone(), decision["state_unused"].clone()), (json!(["q3"]), json!(["q3"]), malformed), "{decision}"); + assert!(speech_prompts(&model)[1].contains("named holds it did not open from a listed line's own words: q3.")); + let naming = answering(vec![json!({ "say": [say_holding(1, json!(["q3"])), say_holding(2, json!([]))], "gaps": [], "hold": malformed }).to_string()]); + let held = decide(&naming, "test", &x1_packet(), "The room is warm.", X1_LIBBY_R1, &Tuning::default()); + assert_eq!((held.get("failed"), held["refused"][0]["reason"].as_str(), held["refused"][0]["draft"].as_u64()), (None, Some("held"), Some(1)), "{held}"); + // An item with no line is a fault by its kind. + let lineless = answering(vec![json!({ "say": [say_holding(1, json!([])), say_holding(2, json!([]))], "gaps": [], "hold": [{ "words": "hold it" }] }).to_string()]); + assert_eq!(decide(&lineless, "test", &x1_packet(), "The room is warm.", X1_LIBBY_R1, &Tuning::default())["hold_faults"], json!(["a hold item"])); +} + +/// Negative: a hold citing a line that is not listed does not open, because code knows no asker; the drafts naming it are +/// held this turn only. +#[test] +fn k47_a_hold_on_an_unlisted_line_does_not_open() { + let answer = json!({ "say": [say_holding(1, json!(["q99"])), say_holding(2, json!([]))], "gaps": [], "hold": [{ "line": "q99", "words": "hold it, don't post it in here yet", "where": "here" }] }).to_string(); + let decision = decide(&answering(vec![answer]), "test", &x1_packet(), "The room is warm.", X1_LIBBY_R1, &Tuning::default()); + assert_eq!((decision["hold_faults"].clone(), decision["refused"][0]["reason"].as_str()), (json!(["q99"]), Some("held")), "{decision}"); + let (state, applied) = committed(&decision, X1_LIBBY_R1); + assert!(state.get("holds").is_none() && applied.held.is_empty(), "{state} {applied:?}"); +} + +/// No Huginn call site locates a quote except through `span::locate` (map 16.30.1). +#[test] +fn k47_one_locator() { + for (name, source) in [("commit.rs", include_str!("../commit.rs")), ("interpret.rs", include_str!("../interpret.rs")), ("read.rs", include_str!("../read.rs")), ("outcome.rs", include_str!("../outcome.rs")), ("select.rs", include_str!("../select.rs"))] { + assert!(!source.contains("SourceSpan"), "{name} uses Ghostlight's locator"); + } + assert!(!include_str!("../commit.rs").contains("HoldUnquoted")); +} diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 5ef03e2..5bafe49 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -432,7 +432,8 @@ pub(crate) struct Hold { /// The room it covers; none for anywhere. pub room: Option, pub made: DateTime, - pub words: String, + /// The asker's words naming what is held and where; none when the record could not quote them (K47). + pub words: Option, /// Her own drafts code refused `Held` for this hold (map 16.30.2, K45), oldest first: what code's words gate holds. pub carries: Vec, pub held: Value, @@ -1950,7 +1951,7 @@ fn holds_in_view(inputs: &Inputs) -> (Vec, String) { from_name: sender_name(text(hold, &["from"]), inputs), room: hold["room"].as_str().map(str::to_owned), made: *made, - words: text(hold, &["words"]).to_owned(), + words: hold["words"].as_str().map(str::trim).filter(|words| !words.is_empty()).map(str::to_owned), carries: items(hold, &["carries"]).iter().filter_map(Value::as_str).map(str::to_owned).collect(), held: (*hold).clone(), }) @@ -1971,10 +1972,12 @@ fn holds_in_view(inputs: &Inputs) -> (Vec, String) { } /// A hold in code's words, after its id or its dash: whose, when and where asked, the asker's words, and where it covers. +/// A hold the record could not quote (K47) says so in their words' place: it holds all the same. pub(crate) fn hold_line(hold: &Hold, when: &str) -> String { let asked = hold.room.as_deref().map_or_else(String::new, |room| format!(" in {room}")); let covers = hold.room.as_deref().map_or_else(|| "anywhere".to_owned(), |room| format!("in {room}")); - format!("held for {}, asked {when}{asked}: {}. Not to go {covers} until {} lets it go.", hold.from_name, spoken(&hold.words), hold.from_name) + let what = hold.words.as_deref().map_or_else(|| "; the record could not quote what".to_owned(), |words| format!(": {}", spoken(words))); + format!("held for {}, asked {when}{asked}{what}. Not to go {covers} until {} lets it go.", hold.from_name, hold.from_name) } /// Her domain in her view (map 16.23.1, 16.23.3, 16.23.5): every item of the window, whole, newest first, under headings diff --git a/crates/mind-body/src/projection/span.rs b/crates/mind-body/src/projection/span.rs new file mode 100644 index 0000000..f468f91 --- /dev/null +++ b/crates/mind-body/src/projection/span.rs @@ -0,0 +1,73 @@ +//! Huginn's one locator of a quote (map 16.30.4, K47): "the Interpreter, a model that retypes text, quoted this passage +//! of the source". Every check in `commit.rs` and `interpret.rs` that a quote stands in a source goes through `locate`. +//! +//! It is Ghostlight's `SourceSpan::locate` (`ghostlight-persona-projection` at `c43eb54`): the first occurrence of the +//! quote whose start and end both land on a Unicode word boundary (UAX #29), each candidate a boundary the segmenter +//! reports, rejected first on its first byte. Huginn's contract adds one thing: models normalise typographic punctuation, +//! so both texts are compared under `fold`, which maps one char to one char. The fold is computed over chars, so a span +//! found in the folded source maps back exactly to the source's own bytes, and the span returned is the source's. +//! +//! What it gives up: multi-char typographic forms (`…` against `...`) are not folded, and fixes no longer flow between +//! this and Ghostlight's locator. + +use unicode_segmentation::UnicodeSegmentation; + +/// A located quote: the byte range of the source it stands in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Span { + pub start: usize, + pub end: usize, +} + +/// The one char typographic punctuation is compared as: curly and modifier apostrophes as `'`, curly double quotes as +/// `"`, en and em dashes as `-`, a no-break space as a space. +fn fold(c: char) -> char { + match c { + '\u{2018}' | '\u{2019}' | '\u{02BC}' => '\'', + '\u{201C}' | '\u{201D}' => '"', + '\u{2013}' | '\u{2014}' => '-', + '\u{00A0}' => ' ', + other => other, + } +} + +/// `text` folded, with the byte offset in `text` of each char of the folded text, and `text.len()` last. +fn folded(text: &str) -> (String, Vec, Vec) { + let mut out = String::with_capacity(text.len()); + let mut from: Vec = Vec::with_capacity(text.len() + 1); + let mut at: Vec = Vec::with_capacity(text.len() + 1); + for (byte, c) in text.char_indices() { + from.push(byte); + at.push(out.len()); + out.push(fold(c)); + } + from.push(text.len()); + at.push(out.len()); + (out, from, at) +} + +/// The first occurrence of `quote` in `source`, under `fold`, that lands on a word boundary at both ends; the span is the +/// source's bytes. An empty quote locates nowhere. +pub(crate) fn locate(source: &str, quote: &str) -> Option { + let (source_folded, source_bytes, folded_bytes) = folded(source); + let quote: String = quote.chars().map(fold).collect(); + let &first = quote.as_bytes().first()?; + let mut boundaries: Vec = source_folded.split_word_bound_indices().map(|(byte, _)| byte).collect(); + boundaries.push(source_folded.len()); + let haystack = source_folded.as_bytes(); + for start in boundaries.iter().copied() { + if haystack.get(start) != Some(&first) || !source_folded.get(start..).is_some_and(|candidate| candidate.starts_with(quote.as_str())) { + continue; + } + let end = start + quote.len(); + if boundaries.binary_search(&end).is_ok() { + // Both ends are char starts of the folded text (word boundaries are), so each maps to its char's source byte. + let back = |at: usize| folded_bytes.binary_search(&at).ok().map(|char_at| source_bytes[char_at]); + return Some(Span { start: back(start)?, end: back(end)? }); + } + } + None +} + +#[cfg(test)] +mod tests; diff --git a/crates/mind-body/src/projection/span/tests.rs b/crates/mind-body/src/projection/span/tests.rs new file mode 100644 index 0000000..51d28c1 --- /dev/null +++ b/crates/mind-body/src/projection/span/tests.rs @@ -0,0 +1,136 @@ +//! Ghostlight's locator tests (`ghostlight-persona-projection` at `c43eb54`), copied for Huginn's locator, and its fold. + +use super::*; + +fn verbatim<'a>(source: &'a str, quote: &str) -> Option<&'a str> { + locate(source, quote).map(|span| &source[span.start..span.end]) +} + +/// K47 (map 16.30.4): a quote with `'` and `"` against a source with `’` and `”` returns the source's span, and the +/// source's text at it. +#[test] +fn k47_fold_maps_back_to_source_bytes() { + let source = "Meta said \u{201C}don\u{2019}t post it\u{201D} \u{2014} so I wait."; + let span = locate(source, "\"don't post it\" - so").expect("the folded quote locates"); + assert_eq!(&source[span.start..span.end], "\u{201C}don\u{2019}t post it\u{201D} \u{2014} so"); + assert_eq!(span.start, "Meta said ".len()); + assert_eq!(verbatim("a\u{00A0}b c", "a b"), Some("a\u{00A0}b")); + assert_eq!(verbatim("I can\u{2019}t go", "I can't"), Some("I can\u{2019}t")); + // Negative: a fold does not make a mid-word quote whole. + assert_eq!(locate("I can\u{2019}t go", "I can"), None); +} + +#[test] +fn a_mid_word_quote_is_refused() { + assert_eq!(locate("I cannot go", "I can"), None); +} + +#[test] +fn a_whole_word_quote_is_accepted() { + assert_eq!(locate("I cannot go", "I cannot"), Some(Span { start: 0, end: "I cannot".len() })); +} + +#[test] +fn a_span_equal_to_the_whole_source_is_accepted() { + let source = "I cannot go"; + assert_eq!(locate(source, source), Some(Span { start: 0, end: source.len() })); +} + +#[test] +fn a_later_boundary_valid_occurrence_is_found_after_an_invalid_first() { + let source = "The subcat and the cat both purred."; + assert_eq!(locate(source, "cat").map(|span| span.start), source.rfind("cat")); +} + +#[test] +fn a_span_with_punctuation_at_its_edges_is_handled() { + assert_eq!(verbatim("She said, \"Wait for the bell,\" and left.", "Wait for the bell"), Some("Wait for the bell")); +} + +#[test] +fn a_quote_split_by_an_apostrophe_contraction_is_refused() { + assert_eq!(locate("I can't go", "I can"), None); +} + +#[test] +fn a_quote_ending_before_a_combining_mark_is_refused() { + assert_eq!(locate("the cafe\u{0301} is open", "the cafe"), None); +} + +#[test] +fn a_quote_ending_before_an_underscore_is_refused() { + assert_eq!(locate("run_fast", "run"), None); +} + +#[test] +fn a_cjk_quote_with_no_surrounding_whitespace_is_accepted() { + assert_eq!(verbatim("我不能去", "我不"), Some("我不")); +} + +#[test] +fn a_quote_with_a_leading_space_is_accepted() { + assert_eq!(verbatim("I cannot go", " cannot"), Some(" cannot")); +} + +#[test] +fn a_quote_ending_before_a_hyphen_is_accepted() { + assert_eq!(verbatim("please re-enter the code", "re"), Some("re")); +} + +#[test] +fn a_quote_ending_before_a_period_between_letters_reports_the_crate_result() { + assert_eq!(locate("Stop.Now", "Stop."), None); +} + +#[test] +fn an_overlapping_later_candidate_is_found_after_a_rejected_earlier_one() { + let source = "Juno no no"; + assert_eq!(locate(source, "no no"), Some(Span { start: 5, end: source.len() })); +} + +#[test] +fn a_second_overlapping_candidate_is_found_after_a_rejected_first() { + let source = "xab ab ab"; + assert_eq!(locate(source, "ab ab"), Some(Span { start: 4, end: source.len() })); +} + +#[test] +fn a_whitespace_only_span_is_still_accepted() { + assert_eq!(verbatim("left right", " "), Some(" ")); +} + +#[test] +fn a_punctuation_only_span_is_still_accepted() { + assert_eq!(verbatim("Wait... now", "..."), Some("...")); +} + +#[test] +fn a_multibyte_overlapping_candidate_is_found_after_a_rejected_mid_word_one() { + let source = "xéé éé éé"; + let span = locate(source, "éé éé").expect("the boundary-valid occurrence locates"); + assert_eq!((span.end, &source[span.start..span.end]), (source.len(), "éé éé")); + assert_ne!(span.start, 1, "the mid-word candidate right after the leading x must be rejected"); +} + +/// No timing assertion: the point is that this completes promptly under `cargo test`. +#[test] +fn locate_completes_over_a_long_source() { + assert_eq!(locate(&"a".repeat(64_000), "aa"), None, "no interior boundary exists inside one 64k-char word"); +} + +/// Boundaries that share the quote's own long prefix: `starts_with` scans nearly the whole quote at each. +#[test] +fn locate_is_fast_over_many_boundaries_and_a_shared_prefix_quote() { + let source = ("a".repeat(20_000) + " ").repeat(100); + assert_eq!(locate(&source, &("a".repeat(19_999) + "b")), None); +} + +#[test] +fn locate_returns_the_leftmost_boundary_valid_candidate() { + assert_eq!(locate("cat cat cat", "cat").map(|span| span.start), Some(0)); +} + +#[test] +fn locate_refuses_an_empty_quote() { + assert_eq!(locate("anything the source might hold", ""), None); +} diff --git a/schemas/cultnet/gamecult.persona_state.v0.schema.json b/schemas/cultnet/gamecult.persona_state.v0.schema.json index 67191c3..1eb5ed8 100644 --- a/schemas/cultnet/gamecult.persona_state.v0.schema.json +++ b/schemas/cultnet/gamecult.persona_state.v0.schema.json @@ -1098,7 +1098,7 @@ }, "hold": { "type": "object", - "description": "One hold. from: the asker's Matrix id. room: the room it covers, null for anywhere. event: the asker's line. words: the asker's words naming what is held and where, copied from that line. carries: her own drafts her turn's commit refused as held for this hold, at most four, oldest first; a draft into a place the hold covers that repeats one is not sent. releasedBy: the act that released it, heard (the asker's line, by event).", + "description": "One hold. from: the asker's Matrix id. room: the room it covers, null for anywhere. event: the asker's line. words: the asker's words naming what is held and where, copied from that line, or null when they could not be quoted; the hold holds all the same. carries: her own drafts her turn's commit refused as held for this hold, at most four, oldest first; a draft into a place the hold covers that repeats one is not sent. releasedBy: the act that released it, heard (the asker's line, by event).", "additionalProperties": false, "properties": { "id": { @@ -1121,7 +1121,10 @@ "format": "date-time" }, "words": { - "type": "string", + "type": [ + "string", + "null" + ], "minLength": 1 }, "carries": {