diff --git a/crates/mind-body/fixtures/harness/golden-chorus.txt b/crates/mind-body/fixtures/harness/golden-chorus.txt index 18400b9..fb0cd06 100644 --- a/crates/mind-body/fixtures/harness/golden-chorus.txt +++ b/crates/mind-body/fixtures/harness/golden-chorus.txt @@ -1,6 +1,6 @@ -responder 3: Meta, who runs the place asked the room a question, and "weksa"; "heimdall" answered it. Meta, who runs the place last spoke a few minutes ago. The last 2 lines are the Minds' alone. -responder 4: Meta, who runs the place asked the room a question, and "weksa"; "heimdall"; Kiko answered it. Meta, who runs the place last spoke a few minutes ago. The last 3 lines are the Minds' alone. -responder 5: Meta, who runs the place asked the room a question, and "weksa"; "heimdall"; Kiko; "libby" answered it. Meta, who runs the place last spoke a few minutes ago. The last 4 lines are the Minds' alone. -responder 6: Meta, who runs the place asked the room a question, and "weksa"; "heimdall"; Kiko; "libby"; "void" answered it. Meta, who runs the place last spoke a few minutes ago. The last 5 lines are the Minds' alone. -responder 7: Meta, who runs the place asked the room a question, and "weksa"; "heimdall"; Kiko; "libby"; "void"; "nibu" answered it. Meta, who runs the place last spoke a few minutes ago. The last 6 lines are the Minds' alone. -responder 8: Meta, who runs the place asked the room a question, and "weksa"; "heimdall"; Kiko; "libby"; "void"; "nibu"; "aqua" answered it. Meta, who runs the place last spoke a few minutes ago. The last 7 lines are the Minds' alone. +responder 3: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 2 lines are the Minds' alone. +responder 4: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko answered it. Meta, who runs the place last spoke a few minutes ago. The last 3 lines are the Minds' alone. +responder 5: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 4 lines are the Minds' alone. +responder 6: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 5 lines are the Minds' alone. +responder 7: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know; "nibu", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 6 lines are the Minds' alone. +responder 8: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know; "nibu", someone he does not know; "aqua", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 7 lines a… diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index 97d26b7..a114896 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -35,12 +35,11 @@ use super::read::{ReadRequest, answers, repo_name}; pub(crate) const CLOSED_KEPT_DAYS: i64 = 7; /// How many reaffirmations, and how many reopenings, an entry keeps: the newest. const REAFFIRMED_KEPT: usize = 3; -/// The most bytes of her own drafts one hold carries, all of them together (map 16.31.3, K51): about 8 drafts at -/// `CARRY_BYTES`. Past it nothing new is carried and `carries_full` is reported: the oldest stay, since the text written -/// right after the ask is the likeliest held thing. +/// The most bytes of her own drafts one hold carries, all of them together (map 16.31.3, K51). Each draft is carried +/// whole (K56): a clipped draft's tail would be no held text. Past it nothing new is carried and `carries_full` is +/// reported: the oldest stay, since the text written right after the ask is the likeliest held thing. A draft longer +/// than this alone, the first a hold carries, is carried clipped to it, and reported too. const CARRIES_BYTES: usize = 9600; -/// The most bytes of one held draft a hold carries (K45). -const CARRY_BYTES: usize = 1200; /// The fewest words a passage of her prose cited as evidence may be (section 4.1's `source_quote`). pub(crate) const PROSE_MIN_WORDS: usize = 4; @@ -420,17 +419,34 @@ pub(crate) fn apply(state: &Value, record: &Value, prose: &str, key: &str, now: applied.refused.push(json!({ "proposal": raw, "reason": reason })); } } + rehold(&mut state, &applied); carry_held(&mut state, record, &mut applied); block_on_failed_reads(&mut state, record, &mut applied); receive_reads(&mut state, record, key, now, &mut applied); (state, applied) } +/// A hold this apply opened starts with what a hold it released had carried, when both are the same asker's over the same +/// place (K56): an asker who lets a hold go and asks again in one wake asks for the same thing, and the texts held under +/// the first are held under the second. The released hold keeps its own carries until it is pruned. +fn rehold(state: &mut Value, applied: &Applied) { + for opened in &applied.held { + let Some(released) = applied.unheld.iter().find(|released| released["from"] == opened["from"] && released["room"] == opened["room"]) else { + continue; + }; + let carried: Vec = released["carries"].as_array().cloned().unwrap_or_default(); + if let Some(hold) = state.get_mut("holds").and_then(Value::as_array_mut).into_iter().flatten().find(|hold| hold["id"] == opened["id"]) { + hold["carries"] = json!(carried); + } + } +} + /// Each entry of the decision's `carry` (map 16.31.3, K51), written to its hold after the holds this apply opened: every /// draft she did not send while the hold was open, and nothing else decides it. The hold's handle is a hold listed to the -/// Interpreter (`h1`), or the line an open hold opened from (`q3`). Each text is held to `CARRY_BYTES`, a duplicate is -/// skipped, and past `CARRIES_BYTES` for the hold nothing new is carried and the entry is reported in `carries_full`. A -/// handle no open hold answers carries nothing, and is reported. The decision proposes and the commit writes. +/// Interpreter (`h1`), or the line an open hold opened from (`q3`). Each text is carried whole, a duplicate (the same +/// text under `span::fold`) is skipped, and past `CARRIES_BYTES` for the hold nothing new is carried and the entry is +/// reported in `carries_full`. A handle no open hold answers carries nothing, and is reported. The decision proposes and +/// the commit writes. fn carry_held(state: &mut Value, record: &Value, applied: &mut Applied) { let decision = &record["interpreter"]; for entry in decision["carry"].as_array().into_iter().flatten() { @@ -447,20 +463,22 @@ fn carry_held(state: &mut Value, record: &Value, applied: &mut Applied) { applied.held_unrecorded.push(entry.clone()); continue; }; - let text = super::select::clip(text, CARRY_BYTES); if !hold["carries"].is_array() { hold["carries"] = json!([]); } let carries = hold["carries"].as_array_mut().expect("carries is an array"); - if carries.iter().any(|carried| carried.as_str() == Some(text.as_str())) { + if carries.iter().filter_map(Value::as_str).any(|carried| span::fold_text(carried) == span::fold_text(text)) { continue; } let used: usize = carries.iter().filter_map(Value::as_str).map(str::len).sum(); - if used + text.len() > CARRIES_BYTES { - applied.carries_full.push(entry.clone()); - } else { + if used + text.len() <= CARRIES_BYTES { carries.push(json!(text)); + continue; } + if carries.is_empty() { + carries.push(json!(super::select::clip(text, CARRIES_BYTES))); + } + applied.carries_full.push(entry.clone()); } } diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index 57f623a..59194ba 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -1064,7 +1064,7 @@ fn k51_carry_reads_the_decision_carry_and_nothing_else() { let carry = |hold: &str, text: &str| json!({ "hold": hold, "text": text }); let mut record = hearing(&[], listed, json!([])); record["interpreter"]["carry"] = json!([carry("h1", "One."), carry("h1", "Two."), carry("h1", "One."), carry("h9", "Lost.")]); - record["interpreter"]["refused"] = json!([{ "act": "say", "draft": 1, "reason": "held", "text": "Refused only.", "hold": { "who": "Meta", "id": "h2" } }]); + record["interpreter"]["refused"] = json!([{ "act": "say", "draft": 1, "reason": "held", "text": "Refused only.", "holds": [{ "who": "Meta", "id": "h2" }] }]); let (after, applied) = apply(&state, &record, "x", "r1-t4", now()); assert_eq!((after["holds"][0]["carries"].clone(), after["holds"][1].get("carries"), applied.held_unrecorded.clone(), applied.carries_full.len()), (json!(["One.", "Two."]), None, vec![carry("h9", "Lost.")], 0), "{after}"); } diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 3936b06..b6134fb 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -174,9 +174,11 @@ pub(crate) enum Refusal { NoRoom, /// The number names no draft she set down: the Interpreter's error, nothing of hers. NoDraft, - /// The draft was already said or added this turn: a draft goes out once, in one place (a note to Self aside). + /// The draft is in an earlier line or addition of this answer: a draft goes out once, in one place (a note to Self + /// aside). Settled before the words gate (K56), so it holds whatever became of the earlier one. Used, - /// The same words already went out this turn, from another draft: said once (map 16.20.7). + /// The same words, as `span::fold` reads them, are in an earlier line of this answer, from another draft: said once + /// (map 16.20.7). Settled before the words gate, as `Used` is. Duplicate, /// Mostly the words she had just heard. Echo, @@ -186,7 +188,7 @@ pub(crate) enum Refusal { NotAmendable, /// A line replying to no line listed as one she may reply to (map 16.20.8 (D), K20). NotQuotable, - /// A second amendment in one turn. + /// A second amendment in one answer: settled before the words gate, as `Used` is. SecondAmend, /// A second note to Self in one turn. SecondNote, @@ -301,7 +303,7 @@ fn gap(prose: &str, found: &Drafts, raw: &Value) -> Value { let names_a_draft = !matches!(kind, GapKind::Unwritten | GapKind::Unresolved); let quote = raw.get("quote").and_then(Value::as_str).unwrap_or_default().trim(); // A reach that quotes a draft by its words, with no number, is about that draft: a promise in it (map 16.20.6). - let quoted_draft = || (kind == GapKind::MissingAffordance && words(quote) >= GAP_QUOTE_MIN_WORDS).then(|| found.drafts.iter().find(|draft| draft.text.contains(quote))).flatten(); + let quoted_draft = || (kind == GapKind::MissingAffordance && words(quote) >= GAP_QUOTE_MIN_WORDS).then(|| found.drafts.iter().find(|draft| span::fold_text(&draft.text).contains(&span::fold_text(quote)))).flatten(); if let Some(draft) = raw.get("draft").and_then(Value::as_i64).and_then(|n| found.numbered(n)).filter(|_| names_a_draft).or_else(quoted_draft) { gap["from"] = json!("draft"); gap["draft"] = json!(draft.n); @@ -847,9 +849,8 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na let mut refusals: Vec = Vec::new(); // A draft is its number (map 16.20.7): a draft is said or added once, and is used only when its act succeeds, so a // refused act leaves it free. A note to Self may be a draft that was also said or added (map 16.29.8). The same words - // go out once: a said draft whose words already went out is `Duplicate`, and only speech is held to that. `went` holds + // go out once: a line whose words are another line's is `Duplicate`, and only speech is held to that. `went` holds // the drafts that went somewhere; `said_drafts` the ones said. - let mut used: Vec = Vec::new(); let mut went: Vec<&Draft> = Vec::new(); let mut said_drafts: Vec = Vec::new(); let mut unused: Vec = Vec::new(); @@ -863,11 +864,76 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na .filter_map(|raw| serde_json::from_value::(raw.clone()).ok()) .filter_map(|hold| packet.quotable.iter().find(|line| line.id == hold.line.trim()).map(|line| (line.id.clone(), (hold.place == Where::Here).then(|| line.room.clone())))) .collect(); - // Code's words gate (map 16.31.3, K51), before the act loops: the drafts that carry a held text into a room its hold - // covers, measured over everything this answer sends there. Naming a hold adds to it and never clears it. - let gated = held_gate(&parsed, packet, &opening, &found); - let gate = |into: &str, draft: &Draft| gated.get(&(into.to_owned(), draft.n)).cloned(); - for line in parsed.say { + // The refusals that do not depend on the words gate (map 16.31.3, K56), settled first, in the answer's order. `Used`, + // `Duplicate` and `SecondAmend` count the lines before it that no such refusal took: a draft is in at most one line or + // addition, the same words in at most one line, and at most one addition is made. A line any of them refuses does not + // go out, so the gate counts it unsent. + let mut taken: Vec = Vec::new(); + let mut taken_words: Vec = Vec::new(); + let mut gate_lines: Vec = Vec::new(); + let mut say_first: Vec> = Vec::new(); + for line in &parsed.say { + let Some(draft) = line.draft.and_then(|n| found.numbered(n)) else { + say_first.push(Some(Refusal::NoDraft)); + continue; + }; + let cited = line.in_reply_to.as_deref().map(str::trim).filter(|id| !id.is_empty()); + let reason = if room.is_none() { + Some(Refusal::NoRoom) + } else if taken.contains(&draft.n) { + Some(Refusal::Used) + } else if taken_words.contains(&span::fold_text(&draft.text)) { + Some(Refusal::Duplicate) + } else if cited.is_some_and(|id| !packet.quotable.iter().any(|quotable| quotable.id == id)) { + Some(Refusal::NotQuotable) + } else if echo(&draft.text, &bodies) { + Some(Refusal::Echo) + } else { + None + }; + if reason.is_none() { + taken.push(draft.n); + taken_words.push(span::fold_text(&draft.text)); + } + if let Some(into) = room.clone() { + gate_lines.push(GateLine { into, draft, named: &line.holds, say: true, candidate: reason.is_none() }); + } + say_first.push(reason); + } + let mut amending = false; + let mut amend_first: Vec> = Vec::new(); + for proposed in &parsed.amend { + let Some(draft) = proposed.draft.and_then(|n| found.numbered(n)) else { + amend_first.push(Some(Refusal::NoDraft)); + continue; + }; + let target = proposed.target.as_deref().and_then(|id| packet.amendable.iter().find(|line| line.id == id.trim())); + let reason = if taken.contains(&draft.n) { + Some(Refusal::Used) + } else if echo(&draft.text, &bodies) { + Some(Refusal::Echo) + } else if amending { + Some(Refusal::SecondAmend) + } else if target.is_none() { + Some(Refusal::NotAmendable) + } else { + None + }; + if reason.is_none() { + taken.push(draft.n); + amending = true; + } + // An addition goes where its line is. + if let Some(into) = target.map(|line| line.room.clone()).or_else(|| room.clone()) { + gate_lines.push(GateLine { into, draft, named: &proposed.holds, say: false, candidate: reason.is_none() }); + } + amend_first.push(reason); + } + // Code's words gate (map 16.31.3, K51, K56), over the lines no earlier refusal took: the lines held, with every hold + // that holds each, and the lines past `MAX_LINES`. Naming a hold adds to it and never clears it. + let gate = held_gate(&gate_lines, packet, &opening, &found); + let gated = |into: Option<&str>, draft: &Draft| into.and_then(|into| gate.held.get(&(into.to_owned(), draft.n))).cloned(); + for (line, first) in parsed.say.into_iter().zip(say_first) { let Some(draft) = line.draft.and_then(|n| found.numbered(n)) else { refusals.push(refused(Act::Say, None, line.draft, Refusal::NoDraft)); continue; @@ -876,34 +942,17 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na // reply to a line she was not shown, nor as no reply when she meant one. let cited = line.in_reply_to.as_deref().map(str::trim).filter(|id| !id.is_empty()); let target = cited.and_then(|id| packet.quotable.iter().find(|quotable| quotable.id == id)); - let hold = room.as_deref().and_then(|into| gate(into, draft)); - let reason = if room.is_none() { - Some(Refusal::NoRoom) - } else if used.contains(&draft.n) { - Some(Refusal::Used) - } else if said.iter().any(|line| line["text"] == draft.text.as_str()) { - Some(Refusal::Duplicate) - } else if cited.is_some() && target.is_none() { - Some(Refusal::NotQuotable) - } else if echo(&draft.text, &bodies) { - Some(Refusal::Echo) - } else if hold.is_some() { - Some(Refusal::Held) - } else if said.len() >= MAX_LINES { - Some(Refusal::OverLines) - } else { - None - }; + let holds = gated(room.as_deref(), draft); + let reason = first.or_else(|| holds.as_ref().map(|_| Refusal::Held)).or_else(|| gate.over.contains(&draft.n).then_some(Refusal::OverLines)); if let Some(reason) = reason { let mut refusal = refused(Act::Say, Some(draft), None, reason); - if reason == Refusal::Held { - refusal["hold"] = hold.unwrap_or_default(); + if let (Refusal::Held, Some(holds)) = (reason, holds) { + refusal["holds"] = json!(holds); } refusals.push(refusal); continue; } let (mentions, unknown): (Vec, Vec) = line.mentions.into_iter().partition(|id| shown(id)); - used.push(draft.n); said_drafts.push(draft.n); went.push(draft); said.push(json!({ "room": room, "text": draft.text, "mentions": mentions, "in_reply_to": target.map(|line| json!({ "id": line.id, "event": line.event, "who": line.who, "text": line.text })), "rests_on": { "draft": draft.n, "start_byte": draft.start, "end_byte": draft.end }, "dropped": { "mentions": unknown } })); @@ -913,37 +962,25 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na // nothing here can rewrite the line (map 16.17). let mut amended: Vec = Vec::new(); let mut amended_drafts: Vec = Vec::new(); - for proposed in parsed.amend { + for (proposed, first) in parsed.amend.into_iter().zip(amend_first) { let Some(draft) = proposed.draft.and_then(|n| found.numbered(n)) else { refusals.push(refused(Act::Amend, None, proposed.draft, Refusal::NoDraft)); continue; }; let target = proposed.target.as_deref().and_then(|id| packet.amendable.iter().find(|line| line.id == id.trim())); - // An addition goes where its line is. - let hold = target.map(|line| line.room.as_str()).or(room.as_deref()).and_then(|into| gate(into, draft)); - let reason = if used.contains(&draft.n) { - Some(Refusal::Used) - } else if echo(&draft.text, &bodies) { - Some(Refusal::Echo) - } else if hold.is_some() { - Some(Refusal::Held) - } else if !amended.is_empty() { - Some(Refusal::SecondAmend) - } else { - None - }; - match (reason, target) { + let holds = gated(target.map(|line| line.room.as_str()).or(room.as_deref()), draft); + match (first.or_else(|| holds.as_ref().map(|_| Refusal::Held)), target) { (None, Some(line)) => { - used.push(draft.n); - went.push(draft); + went.push(draft); amended_drafts.push(draft.n); amended.push(json!({ "target": line.id, "event": line.event, "room": line.room, "original": line.text, "added": draft.text, "draft": draft.n })); promised(&mut decision, Promising { unused: &mut unused, proposals: &mut proposals, to_dropped: &mut to_dropped, packet, prose }, draft, &proposed.promises, &shown); } (reason, _) => { - let mut refusal = refused(Act::Amend, Some(draft), None, reason.unwrap_or(Refusal::NotAmendable)); - if let (Some(Refusal::Held), Some(hold)) = (reason, &hold) { - refusal["hold"] = hold.clone(); + let reason = reason.unwrap_or(Refusal::NotAmendable); + let mut refusal = refused(Act::Amend, Some(draft), None, reason); + if let (Refusal::Held, Some(holds)) = (reason, holds) { + refusal["holds"] = json!(holds); } refusals.push(refusal); } @@ -986,7 +1023,7 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na for gap in decision["gaps"].as_array_mut().into_iter().flatten() { let promise = gap["kind"] == json!(GapKind::MissingAffordance) && gap["from"] == "draft" && gap["draft"].as_u64().is_some_and(|n| said_drafts.iter().chain(&amended_drafts).any(|said| *said as u64 == n)); let named = !promise && gap["draft"].as_u64().is_some_and(|n| went.iter().any(|draft| draft.n as u64 == n)) && gap["from"] == "draft"; - let quoted = gap["from"] == "unlocated" && gap["quote"].as_str().is_some_and(|quote| !quote.is_empty() && went.iter().any(|draft| draft.text.contains(quote))); + let quoted = gap["from"] == "unlocated" && gap["quote"].as_str().is_some_and(|quote| !quote.is_empty() && went.iter().any(|draft| span::fold_text(&draft.text).contains(&span::fold_text(quote)))); if named || quoted { gap["from"] = json!("acted"); } @@ -1273,13 +1310,13 @@ fn hold_named(id: &str, packet: &Packet, opening: &[(String, Option)]) - Named { hold: json!({ "who": line.map(|line| line.who.as_str()), "by_id": line.map(|line| line.sender.as_str()), "id": id }), covers: opens.and_then(|(_, covers)| covers.clone()), made: line.filter(|_| opens.is_some()).map(|line| line.at_ms) } } -/// The hold a draft going into `into` names that holds it (map 16.28.5): each id it names resolves to a hold -/// (`hold_named`), and the first that covers `into` (anywhere, or that room) holds it. Code owns where. The asker's words -/// stay in her view and the Interpreter's list, never in a refusal her outcome is told from (map 16.29.3). Naming is an +/// The holds a draft going into `into` names that hold it (map 16.28.5): each id it names resolves to a hold +/// (`hold_named`), and each that covers `into` (anywhere, or that room) holds it. Code owns where. The asker's words stay +/// in her view and the Interpreter's list, never in a refusal her outcome is told from (map 16.29.3). Naming is an /// addition to code's words gate (`held_gate`, K51): a paraphrase only the Interpreter can recognise is held by naming, /// and naming never clears a draft the words gate holds. -fn held_by(named: &[String], into: &str, packet: &Packet, opening: &[(String, Option)]) -> Option { - named.iter().map(|id| hold_named(id.trim(), packet, opening)).find(|named| named.covers.as_deref().is_none_or(|room| room == into)) +fn held_by(named: &[String], into: &str, packet: &Packet, opening: &[(String, Option)]) -> Vec { + named.iter().map(|id| hold_named(id.trim(), packet, opening)).filter(|named| named.covers.as_deref().is_none_or(|room| room == into)).collect() } /// Whether two texts are the same words, as `span::tokens` reads them. @@ -1287,84 +1324,134 @@ fn same_words(a: &str, b: &str) -> bool { span::tokens(a).eq(span::tokens(b)) } -/// A text the words gate measures against (K51): its words, its hold as a refusal names it, and when that hold was made. -struct HeldText { - text: String, +/// A line or an addition of this answer as the words gate reads it (K56): the room it goes into, its draft, the holds it +/// names, whether it is a line (only lines count toward `MAX_LINES`), and whether it is a candidate, one no refusal that +/// does not depend on the gate took. +struct GateLine<'a> { + into: String, + draft: &'a Draft, + named: &'a [String], + say: bool, + candidate: bool, +} + +/// A hold as a held text answers to it (K56): how a refusal names it, and when it was made. +#[derive(Clone)] +struct Asker { hold: Value, made: Option, } -/// Code's words gate (map 16.31.3, K51): the drafts of this answer that carry a held text into a room its hold covers, -/// each with its hold, by the room it goes into and its number. For each room R a say or an amendment goes into: +/// A text the words gate measures against (K51): its words, and every hold it is held for. +struct HeldText { + text: String, + askers: Vec, +} + +/// What code's words gate decided (K56): each line held, by the room it goes into and its number, with every hold that +/// holds it; and the lines past `MAX_LINES`, by number. +struct Gate { + held: BTreeMap<(String, usize), Vec>, + over: BTreeSet, +} + +/// Adds `askers` to the holds `key` is held for, each once: whether anything was added. +fn hold_for(held: &mut BTreeMap<(String, usize), Vec>, key: (String, usize), askers: &[Asker]) -> bool { + let holds = held.entry(key).or_default(); + let before = holds.len(); + for asker in askers { + if !holds.contains(&asker.hold) { + holds.push(asker.hold.clone()); + } + } + holds.len() > before +} + +/// Code's words gate (map 16.31.3, K51, K56): the candidate lines that carry a held text into a room its hold covers, +/// each with every hold that holds it, and the candidate lines past `MAX_LINES`. A draft is unsent when it does not go +/// out: no candidate, past `MAX_LINES`, or held. For each room R a candidate goes into: /// - its held texts H(R) are the texts each open hold covering R carries; when any hold open or opening covers R, every -/// draft of the wake the answer puts in neither `say` nor `amend`; and each draft whose named `holds` hold it there; -/// - what enters R, U(R), is every such line, with her listed lines in R (`amendable`) posted after the held text's hold; -/// - a held text h enters R when a line equals it, when it has at least `ECHO_MIN_WORDS` words and `ECHO_OVERLAP` of its -/// trigrams are in U(R) joined, or when a line of at least `ECHO_MIN_WORDS` words has `ECHO_OVERLAP` of its trigrams in -/// h, all over `span::tokens`. Then every line into R that equals h or shares a trigram with it is held under h's hold -/// and joins H(R), and the gate runs on until nothing changes: it ends, since each held text is measured once and each -/// new one holds one more line. +/// unsent draft of the wake that is no candidate into R, under every hold open or opening that covers R; and each +/// draft of a line into R that names holds covering R (`held_by`), whatever its fate; +/// - what enters R, U(R), is every candidate into R, with her listed lines in R (`amendable`) posted after the held +/// text's hold; +/// - a held text h enters R when a candidate equals it, when it has at least `ECHO_MIN_WORDS` words and `ECHO_OVERLAP` +/// of its trigrams are in U(R) joined, or when a candidate of at least `ECHO_MIN_WORDS` words has `ECHO_OVERLAP` of its +/// trigrams in h, all over `span::tokens`. Then every candidate into R that equals h or shares a trigram with it is held +/// under h's holds, and its text joins H(R) under the holds it is held for. +/// +/// The candidates not held then go out in order, `MAX_LINES` lines at most, and every line past them is cut. A cut line +/// is unsent, so the gate runs again over it, until no line is newly held or cut: it ends, since nothing held or cut is +/// ever let go, and there are finitely many lines and holds. A cut line stays cut when a later round holds a line before +/// it: the line held repeats a cut one, which would otherwise go out. /// /// Her listed lines are never held: they are already out, and only count toward the measure. What it cannot reach, by /// construction: a paraphrase (only naming holds it), a first instance, a held text under `ECHO_MIN_WORDS` split across /// lines, and a split across more than two wakes. -fn held_gate(answer: &Answer, packet: &Packet, opening: &[(String, Option)], found: &Drafts) -> BTreeMap<(String, usize), Value> { - let numbered = |n: Option| n.and_then(|n| found.numbered(n)); - let says = answer.say.iter().filter_map(|line| Some((packet.room.clone()?, numbered(line.draft)?, &line.holds))); - let amends = answer.amend.iter().filter_map(|amend| { - let target = amend.target.as_deref().and_then(|id| packet.amendable.iter().find(|line| line.id == id.trim())); - Some((target.map(|line| line.room.clone()).or_else(|| packet.room.clone())?, numbered(amend.draft)?, &amend.holds)) - }); - let mut lines: Vec<(String, &Draft, &Vec)> = Vec::new(); - for (into, draft, named) in says.chain(amends) { - if !lines.iter().any(|(room, known, _)| *room == into && known.n == draft.n) { - lines.push((into, draft, named)); - } - } - let sent: BTreeSet = answer.say.iter().map(|line| line.draft).chain(answer.amend.iter().map(|amend| amend.draft)).flatten().filter_map(|n| usize::try_from(n).ok()).collect(); - let unsent: Vec<&Draft> = found.drafts.iter().filter(|draft| !sent.contains(&draft.n)).collect(); +fn held_gate(lines: &[GateLine], packet: &Packet, opening: &[(String, Option)], found: &Drafts) -> Gate { let long = |text: &str| span::tokens(text).count() >= ECHO_MIN_WORDS; - let mut gated: BTreeMap<(String, usize), Value> = BTreeMap::new(); - let rooms: BTreeSet = lines.iter().map(|(room, _, _)| room.clone()).collect(); - for room in rooms { - let covers = |covers: &Option| covers.as_deref().is_none_or(|covered| covered == room); - let into: Vec<(&Draft, &Vec)> = lines.iter().filter(|(line_room, _, _)| *line_room == room).map(|(_, draft, named)| (*draft, *named)).collect(); - let mut held: Vec = Vec::new(); - for hold in packet.holds.iter().filter(|hold| covers(&hold.room)) { - let named = hold_named(&hold.id, packet, opening); - held.extend(hold.carries.iter().map(|text| HeldText { text: text.clone(), hold: named.hold.clone(), made: named.made })); - } - let first = packet.holds.iter().filter(|hold| covers(&hold.room)).map(|hold| hold.id.as_str()).chain(opening.iter().filter(|(_, covered)| covers(covered)).map(|(line, _)| line.as_str())).next(); - if let Some(first) = first.map(|id| hold_named(id, packet, opening)) { - held.extend(unsent.iter().map(|draft| HeldText { text: draft.text.clone(), hold: first.hold.clone(), made: first.made })); - } - for (draft, named) in &into { - if let Some(named) = held_by(named, &room, packet, opening) { - held.push(HeldText { text: draft.text.clone(), hold: named.hold, made: named.made }); + let rooms: BTreeSet<&str> = lines.iter().filter(|line| line.candidate).map(|line| line.into.as_str()).collect(); + let mut gate = Gate { held: BTreeMap::new(), over: BTreeSet::new() }; + loop { + let live = |line: &GateLine| line.candidate && !gate.over.contains(&line.draft.n); + let out: BTreeSet = lines.iter().filter(|line| live(line) && !gate.held.contains_key(&(line.into.clone(), line.draft.n))).map(|line| line.draft.n).collect(); + let mut held = gate.held.clone(); + for &room in &rooms { + let covers = |covers: &Option| covers.as_deref().is_none_or(|covered| covered == room); + let into: Vec<&Draft> = lines.iter().filter(|line| line.into == room && live(line)).map(|line| line.draft).collect(); + let covering: Vec = packet.holds.iter().filter(|hold| covers(&hold.room)).map(|hold| hold.id.as_str()).chain(opening.iter().filter(|(_, covered)| covers(covered)).map(|(line, _)| line.as_str())).fold(Vec::new(), |mut ids: Vec<&str>, id| { + if !ids.contains(&id) { + ids.push(id); + } + ids + }).into_iter().map(|id| hold_named(id, packet, opening)).map(|named| Asker { hold: named.hold, made: named.made }).collect(); + let mut texts: Vec = Vec::new(); + for hold in packet.holds.iter().filter(|hold| covers(&hold.room)) { + let named = hold_named(&hold.id, packet, opening); + texts.extend(hold.carries.iter().map(|text| HeldText { text: text.clone(), askers: vec![Asker { hold: named.hold.clone(), made: named.made }] })); } - } - let sent_here: Vec<&str> = into.iter().map(|(draft, _)| draft.text.as_str()).collect(); - let mut at = 0; - while let Some(h) = held.get(at) { - let listed = packet.amendable.iter().filter(|line| line.room == room && h.made.is_none_or(|made| line.at_ms.is_none_or(|posted| posted > made))).map(|line| line.text.as_str()); - // Her listed lines first, then this answer's: the order they reach the room. - let union = listed.chain(sent_here.iter().copied()).collect::>().join("\n"); - let enters = into.iter().any(|(draft, _)| same_words(&draft.text, &h.text) || (long(&draft.text) && heard_overlap(&draft.text, &h.text) >= ECHO_OVERLAP)) || (long(&h.text) && heard_overlap(&h.text, &union) >= ECHO_OVERLAP); - let mut caught: Vec = Vec::new(); - if enters { - for (draft, _) in &into { - if !gated.contains_key(&(room.clone(), draft.n)) && (same_words(&draft.text, &h.text) || heard_overlap(&draft.text, &h.text) > 0.0) { - gated.insert((room.clone(), draft.n), h.hold.clone()); - caught.push(HeldText { text: draft.text.clone(), hold: h.hold.clone(), made: h.made }); - } + if !covering.is_empty() { + let unsent = found.drafts.iter().filter(|draft| !out.contains(&draft.n) && !into.iter().any(|line| line.n == draft.n)); + texts.extend(unsent.map(|draft| HeldText { text: draft.text.clone(), askers: covering.clone() })); + } + for line in lines.iter().filter(|line| line.into == room) { + let askers: Vec = held_by(line.named, room, packet, opening).into_iter().map(|named| Asker { hold: named.hold, made: named.made }).collect(); + if !askers.is_empty() { + texts.push(HeldText { text: line.draft.text.clone(), askers }); } } - // A held line joins what is held, so whatever repeats it is held too. - held.extend(caught); - at += 1; + // Until nothing changes: a held line joins H(R) under the holds it is held for, so whatever repeats it is held + // for them too. + loop { + let caught: Vec = into.iter().filter_map(|draft| held.get(&(room.to_owned(), draft.n)).map(|holds| (draft, holds))).map(|(draft, holds)| HeldText { text: draft.text.clone(), askers: holds.iter().map(|hold| Asker { hold: hold.clone(), made: None }).collect() }).collect(); + let mut changed = false; + for h in texts.iter().chain(&caught) { + // The earliest any of its holds was made: her listed lines after it count. None, every line. + let made = h.askers.iter().try_fold(u64::MAX, |earliest, asker| asker.made.map(|made| earliest.min(made))); + let listed = packet.amendable.iter().filter(|line| line.room == room && made.is_none_or(|made| line.at_ms.is_none_or(|posted| posted > made))).map(|line| line.text.as_str()); + // Her listed lines first, then this answer's: the order they reach the room. + let union = listed.chain(into.iter().map(|draft| draft.text.as_str())).collect::>().join("\n"); + let enters = into.iter().any(|draft| same_words(&draft.text, &h.text) || (long(&draft.text) && heard_overlap(&draft.text, &h.text) >= ECHO_OVERLAP)) || (long(&h.text) && heard_overlap(&h.text, &union) >= ECHO_OVERLAP); + if enters { + for draft in into.iter().filter(|draft| same_words(&draft.text, &h.text) || heard_overlap(&draft.text, &h.text) > 0.0) { + changed |= hold_for(&mut held, (room.to_owned(), draft.n), &h.askers); + } + } + } + if !changed { + break; + } + } + } + let going: Vec = lines.iter().filter(|line| line.say && live(line) && !held.contains_key(&(line.into.clone(), line.draft.n))).map(|line| line.draft.n).collect(); + let cut: Vec = going.into_iter().skip(MAX_LINES).collect(); + let settled = cut.is_empty() && held == gate.held; + gate.held = held; + gate.over.extend(cut); + if settled { + return gate; } } - gated } /// The holds an answer names and does not open (map 16.29.3), a contract fault found before anything is decided: a `hold` @@ -1448,7 +1535,7 @@ fn reopen_of(raw: &Value, packet: &Packet, prose: &str) -> Option { /// Whether `promise` names an act in `draft`: at least `PROMISE_MIN_WORDS` words (`span::tokens`), found in the draft's /// text with both folded by `span::fold` and lowercased (K52). Why not, when not. fn promise_found(draft: &str, promise: &str) -> Result<(), &'static str> { - let folded = |text: &str| text.chars().map(span::fold).collect::().to_lowercase(); + let folded = |text: &str| span::fold_text(text).to_lowercase(); if span::tokens(promise).count() < PROMISE_MIN_WORDS { Err("fewer than four words") } else if !folded(draft).contains(&folded(promise)) { diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index d584a64..7c32752 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -1579,9 +1579,9 @@ fn k37_x1_r1_held_draft_is_not_said() { // K45: draft 2 repeats draft 1's opening, so code's words gate holds it too (`k45_x1_r1_the_ready_line_repeats_the_held_draft_and_is_held`). assert!(texts(&decision).is_empty(), "{decision}"); let refused = &decision["refused"][0]; - assert_eq!((refused["reason"].as_str(), refused["draft"].as_u64(), refused["hold"]["who"].as_str()), (Some("held"), Some(1), Some("Meta")), "{decision}"); + assert_eq!((refused["reason"].as_str(), refused["draft"].as_u64(), refused["holds"][0]["who"].as_str()), (Some("held"), Some(1), Some("Meta")), "{decision}"); // K53: the asker's id beside the name, from the line the hold opens from. - assert_eq!(refused["hold"]["by_id"].as_str(), Some("@meta:gamecult.org"), "{decision}"); + assert_eq!(refused["holds"][0]["by_id"].as_str(), Some("@meta:gamecult.org"), "{decision}"); assert_eq!(decision["state"], json!([{ "kind": "hold_open", "words": "hold it, don't post it in here yet", "where": "here", "evidence": { "heard": "q3" } }]), "{decision}"); // The commit opens it from Meta on #minds, and her next outcome carries the held sentence. let (state, applied) = committed(&decision, X1_LIBBY_R1); @@ -1598,7 +1598,7 @@ fn k37_x1_r1_held_draft_is_not_said() { fn k37_x1_r1_a_ready_line_repeating_the_declined_draft_is_held() { let answer = holding_the_rest(json!({ "say": [say_holding(2, json!([]))], "gaps": [], "hold": meta_holds_here() }), X1_LIBBY_R1, "I'll say plainly it's held"); let decision = answered(&x1_packet(), X1_LIBBY_R1, answer); - assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["hold"]["id"].as_str()), (Vec::::new(), Some("held"), Some("q3")), "{decision}"); + assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["holds"][0]["id"].as_str()), (Vec::::new(), Some("held"), Some("q3")), "{decision}"); } /// K39 (map 16.29.3): a line named in `holds` with no `hold` entry opening it, or a name that is nothing, is a contract @@ -1611,7 +1611,7 @@ fn k39_named_line_without_a_hold_is_retried() { 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!([named]), json!([named])), "{named}: {decision}"); // K45: draft 2 repeats draft 1, which the fault holds, so it is held by its words, for the same name. - assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["draft"].as_u64(), decision["refused"][1]["hold"]["id"].as_str()), (Vec::::new(), Some("held"), Some(1), Some(named)), "{named}: {decision}"); + assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["draft"].as_u64(), decision["refused"][1]["holds"][0]["id"].as_str()), (Vec::::new(), Some("held"), Some(1), Some(named)), "{named}: {decision}"); let prompts = speech_prompts(&model); assert!(prompts.len() == 2 && prompts[1].contains(&format!("named holds it did not open from a listed line's own words: {named}.")), "{named}: {prompts:?}"); } @@ -1770,7 +1770,7 @@ fn k39_held_for_quotes_no_askers_words() { packet.holds = vec![listed]; let decision = answered(&packet, X1_LIBBY_R1, json!({ "say": [say_holding(1, json!(["h1"])), say_holding(2, json!([]))], "gaps": [] })); let refused = &decision["refused"][0]; - assert_eq!((refused["reason"].as_str(), refused["hold"].clone()), (Some("held"), json!({ "who": "Meta", "by_id": "@meta:gamecult.org", "id": "h1" })), "{decision}"); + assert_eq!((refused["reason"].as_str(), refused["holds"].clone()), (Some("held"), json!([{ "who": "Meta", "by_id": "@meta:gamecult.org", "id": "h1" }])), "{decision}"); let posted: Vec = decision["said"].as_array().unwrap().iter().map(|line| json!({ "event": "9", "room": line["room"], "text": line["text"] })).collect(); let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet.forms); let held = told.iter().find(|line| line.contains("asked him to hold it")).unwrap_or_else(|| panic!("{told:?}")); @@ -1927,14 +1927,15 @@ fn k44_a_decline_quoting_her_draft_accounts_for_nothing() { const K45_WELCOME: &str = "Hello, and welcome, we're glad you're here. Poke at whatever you're curious about first."; -/// Soul's P1 verbatim (`soul_p1_identical_drafts_one_held_one_posted_into_the_covered_room`), inverted: both drafts are -/// refused `held`, nothing is said, the outcome tells the hold once, and the commit's hold carries the welcome. +/// Soul's P1 verbatim (`soul_p1_identical_drafts_one_held_one_posted_into_the_covered_room`), inverted: nothing is said; +/// the first is refused `held`, the second, the same words, `duplicate`, settled before the gate (K56); the outcome tells +/// the hold once, and the commit's hold carries the welcome. #[test] fn k45_p1_identical_drafts_are_both_held() { let prose = format!("Meta asked me to hold the welcome. {K45_WELCOME} {K45_WELCOME}"); let decision = answered(&x1_packet(), &prose, json!({ "say": [say_holding(1, json!(["q3"])), say_holding(2, json!([]))], "gaps": [], "hold": meta_holds_here() })); - let reasons: Vec<(Option<&str>, Option<&str>, Option<&str>)> = decision["refused"].as_array().unwrap().iter().map(|refused| (refused["reason"].as_str(), refused["hold"]["who"].as_str(), refused["hold"]["id"].as_str())).collect(); - assert_eq!((texts(&decision), reasons), (Vec::::new(), vec![(Some("held"), Some("Meta"), Some("q3")); 2]), "{decision}"); + let reasons: Vec<(Option<&str>, Option<&str>, Option<&str>)> = decision["refused"].as_array().unwrap().iter().map(|refused| (refused["reason"].as_str(), refused["holds"][0]["who"].as_str(), refused["holds"][0]["id"].as_str())).collect(); + assert_eq!((texts(&decision), reasons), (Vec::::new(), vec![(Some("held"), Some("Meta"), Some("q3")), (Some("duplicate"), None, None)]), "{decision}"); let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap(); assert_eq!(outcome.lines(x1_packet().forms), ["- Nothing of this reached #minds:gamecult.org: Meta asked him to hold it, and it was not sent."], "told once"); let (state, applied) = committed(&decision, &prose); @@ -1949,8 +1950,8 @@ fn k45_x1_next_turn_kiko_asks_and_the_welcome_stays_held() { let (state, p2) = held_then_kiko_asks(&[K45_WELCOME]); let prose = format!("Kiko asked what I wrote. Kiko, here it is: {K45_WELCOME}"); let decision = answered(&p2, &prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] })); - assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["hold"]["id"].as_str()), (Vec::::new(), Some("held"), Some("h1")), "{decision}"); - assert!(decision["refused"][0]["hold"]["who"].as_str().is_some_and(|who| who.contains("Meta")), "{decision}"); + assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["holds"][0]["id"].as_str()), (Vec::::new(), Some("held"), Some("h1")), "{decision}"); + assert!(decision["refused"][0]["holds"][0]["who"].as_str().is_some_and(|who| who.contains("Meta")), "{decision}"); let (after, applied) = crate::projection::commit::apply(&state, &json!({ "interpreter": decision, "posted": [], "edited": [] }), &prose, "r1-t2", now()); assert_eq!((after["holds"][0]["carries"].clone(), applied.held_unrecorded.len()), (json!([K45_WELCOME, format!("Kiko, here it is: {K45_WELCOME}")]), 0), "{after}"); } @@ -1982,7 +1983,7 @@ fn k45_amend_repeating_held_words_is_held() { packet.amendable = vec![Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Back soon.".into(), at_ms: None }]; let prose = format!("I'll add it after my line. {K45_WELCOME}"); let decision = answered(&packet, &prose, json!({ "say": [], "gaps": [], "amend": [{ "target": "a1", "draft": 1, "holds": [], "promises": [] }] })); - assert_eq!((decision["amended"].as_array().map(Vec::len), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["hold"]["id"].as_str()), (Some(0), Some("held"), Some("h1")), "{decision}"); + assert_eq!((decision["amended"].as_array().map(Vec::len), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["holds"][0]["id"].as_str()), (Some(0), Some("held"), Some("h1")), "{decision}"); } /// What the words gate gives up (map 16.30.2), on R13's X.1 r1 itself: Libby's second draft, "Meta, the draft is ready, @@ -2042,8 +2043,8 @@ fn k47_p2_a_typographic_apostrophe_locates() { 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}"); + assert_eq!((texts(&d2), d2["refused"][0]["reason"].as_str(), d2["refused"][0]["holds"][0]["id"].as_str()), (Vec::::new(), Some("held"), Some("h1")), "{d2}"); + assert!(d2["refused"][0]["holds"][0]["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 @@ -2240,7 +2241,7 @@ fn kiko_gets(p2: &Packet, text: &str) -> Value { /// Whether `decision` said nothing and refused its first line `held`, for Meta. fn held_for_meta(decision: &Value) -> bool { - texts(decision).is_empty() && decision["refused"][0]["reason"] == "held" && decision["refused"][0]["hold"]["who"].as_str().is_some_and(|who| who.contains("Meta")) + texts(decision).is_empty() && decision["refused"][0]["reason"] == "held" && decision["refused"][0]["holds"][0]["who"].as_str().is_some_and(|who| who.contains("Meta")) } /// Soul's `soul_a`, inverted: R15's X.1 r1 shape. Meta's hold opens from q3 and the welcome is declined, by her choice, so @@ -2380,27 +2381,23 @@ fn k51_soul_g_the_interpreter_sees_what_a_hold_carries() { assert!(!listed.contains("please keep it back"), "{listed}"); } -/// Her drafts of 2000 bytes, nine of them, while Meta's hold opens: past `CARRIES_BYTES` the oldest stay, nothing new is -/// carried, and `carries_full` is reported. Each carried text is clipped to `CARRY_BYTES`. +/// Her drafts of exactly 1600 bytes, seven of them, while Meta's hold opens: six fill `CARRIES_BYTES` to the byte and are +/// carried whole, the oldest first; the seventh is not carried, and `carries_full` reports it. #[test] fn k51_the_oldest_carries_stay() { - let long = |n: usize| format!("Draft {n}: {}", format!("word{n} ").repeat(250).trim_end()); - let prose = format!("Meta asked me to hold it. {}", (1..=9).map(|n| format!("{}", long(n))).collect::>().join(" ")); + let long = |n: usize| { + let mut draft = format!("Draft {n}:"); + while draft.len() < 1600 { + draft.push_str(" w"); + } + draft + }; + assert_eq!(long(7).len(), 1600); + let prose = format!("Meta asked me to hold it. {}", (1..=7).map(|n| format!("{}", long(n))).collect::>().join(" ")); let decision = answered(&x1_packet(), &prose, json!({ "say": [], "gaps": [], "hold": meta_holds_here() })); let (state, applied) = committed(&decision, &prose); - let carries = carries_of(&state); - assert!(carries.len() == 8 && carries[0].starts_with("Draft 1:") && !carries.iter().any(|text| text.starts_with("Draft 9:")), "{carries:?}"); - assert_eq!((applied.carries_full.len(), applied.carries_full[0]["text"].as_str().map(|text| text.starts_with("Draft 9:"))), (1, Some(true)), "{applied:?}"); -} - -/// A draft over `CARRY_BYTES` is carried clipped. This pins Soul's surviving mutant `k45-carry-no-clip`. -#[test] -fn k51_a_carried_text_is_clipped() { - let draft = format!("Draft one: {}", "welcome ".repeat(250).trim_end()); - assert!(draft.len() > 1200); - let (state, _) = held_then_kiko_asks(&[draft.as_str()]); - let carries = carries_of(&state); - assert!(carries.len() == 1 && carries[0].len() <= 1200 && carries[0].starts_with("Draft one: welcome"), "{carries:?}"); + assert_eq!(carries_of(&state), (1..=6).map(long).collect::>()); + assert_eq!(applied.carries_full.iter().filter_map(|entry| entry["text"].as_str()).collect::>(), [long(7)], "{applied:?}"); } /// Negative: with no hold open or opening, nothing is carried. @@ -2503,6 +2500,8 @@ fn k54_a_model_error_on_retry_keeps_the_first_answer() { let decision = decide(&Once(std::cell::Cell::new(0)), "test", &x1_packet(), "The room is warm.", P3_PROSE, &Tuning::default()); assert!(decision.get("failed").is_none(), "{decision}"); assert_eq!((texts(&decision), decision["undecided"].clone(), decision["retried"]["failed"].as_str()), (vec!["Meta, the two lines are ready and held.".to_owned()], json!([2]), Some("the connector timed out")), "{decision}"); + // The first answer's fault stays under the retry's (Soul's surviving mutant `s-k54-error-drops-first-fault`). + assert_eq!(decision["retried"]["retried"]["drafts"], json!([2]), "{decision}"); // Negative: a model error on the first call, with no answer before it, still fails the turn. struct Never; impl Model for Never { @@ -2553,7 +2552,7 @@ fn k53_last_turn() -> Value { json!({ "interpreter": { "room": MINDS, "said": [], "gaps": [], - "refused": [{ "reason": "held", "draft": 1, "text": "The two lines are ready.", "hold": { "who": named, "by_id": K53_STRANGER, "id": "h1" } }], + "refused": [{ "reason": "held", "draft": 1, "text": "The two lines are ready.", "holds": [{ "who": named, "by_id": K53_STRANGER, "id": "h1" }] }], "promises": [{ "id": "c2", "to": K53_STRANGER, "to_name": named, "words": "I'll send the map tonight.", "status": "open" }], }, "posted": [], @@ -2587,7 +2586,7 @@ fn k53_soul_f_a_sentence_name_is_clipped_to_a_name() { let prompt = crate::projection::narrate::projector_prompt(&packet, &Tuning::default()); assert!(!k53_leaks(&prompt), "{kind:?} {seed}: {prompt}"); assert!(prompt.contains("\"the vault code\""), "{kind:?} {seed}: named all the same: {prompt}"); - lensed |= prompt.contains("Begin from \"the vault code\", who is here."); + lensed |= prompt.contains("Begin from \"the vault code\", someone he does not know, who is here."); if seed == 1 { for event in ["asked him to hold it", "let him off his promise to", "record still shows his promise to"] { assert!(prompt.lines().any(|line| line.contains(event) && line.contains("\"the vault code\"")), "{kind:?}: {event}: {prompt}"); @@ -2622,8 +2621,8 @@ fn k53_a_bonded_person_is_named_by_her_bond() { }; let names = crate::projection::select::Names { state: &state, people, room: &room }; let who = |sender: &str| crate::projection::select::who_of(sender, &names).to_string(); - assert_eq!((who("@meta:gamecult.org"), who("@long:example.org"), who("@blank:example.org"), who(HER)), ("Meta".to_owned(), "\"Bartholomew\"".to_owned(), "someone he does not know".to_owned(), "Heimdall".to_owned())); - assert_eq!(who("@huge:example.org"), "\"Supercalifragilisticexpialidocio\"", "a first word past `WHO_BYTES` is cut to it"); + assert_eq!((who("@meta:gamecult.org"), who("@long:example.org"), who("@blank:example.org"), who(HER)), ("Meta".to_owned(), "\"Bartholomew\", someone he does not know".to_owned(), "someone he does not know".to_owned(), "Heimdall".to_owned())); + assert_eq!(who("@huge:example.org"), "\"Supercalifragilisticexpialidocio\", someone he does not know", "a first word past `WHO_BYTES` is cut to it"); let packet = packet_in(TurnKind::Chat, &state, &room, 1); let prompt = crate::projection::narrate::projector_prompt(&packet, &Tuning::default()); assert!(prompt.contains("- bond [bond-meta] Meta") && !prompt.contains("4471") && !prompt.contains("example.org") && !prompt.contains("Fitzgerald"), "{prompt}"); @@ -2657,3 +2656,288 @@ fn k53_the_commit_copies_no_heard_line_into_her_free_text() { } assert!(!state.to_string().contains(SENTINEL) && !state.to_string().contains("4471"), "{state}"); } + +// --------------------------------------------------------------------------------------------- +// K56 (Soul's pass on K51 to K55): the gate's unsent set is every draft that does not go out; a stranger reads as one; +// a re-hold keeps what the hold it replaces held; a draft is carried whole; every covering hold holds. + +/// The reasons `decision` refused its lines with, in order. +fn reasons(decision: &Value) -> Vec> { + decision["refused"].as_array().unwrap().iter().map(|refused| refused["reason"].as_str()).collect() +} + +/// Soul's `soul_s1a`, inverted: the welcome is draft 1 in `say` but refused `NotQuotable`, so it does not go out; draft +/// 2 repeats it whole to Meta, naming no hold, while Meta's hold opens. Draft 2 is held, for Meta. +#[test] +fn k56_soul_s1a_a_refused_lines_repeat_is_held_the_same_wake() { + let prose = format!("Meta asked me to hold it. {K45_WELCOME} Meta, here they are: {K45_WELCOME}"); + let mut first = say_holding(1, json!([])); + first["in_reply_to"] = json!("q99"); + let d = answered(&x1_packet(), &prose, json!({ "say": [first, say_holding(2, json!([]))], "gaps": [], "hold": meta_holds_here() })); + assert_eq!((texts(&d), reasons(&d)), (Vec::::new(), vec![Some("not_quotable"), Some("held")]), "{d}"); + assert_eq!((d["refused"][1]["holds"][0]["who"].as_str(), d["refused"][1]["holds"][0]["id"].as_str()), (Some("Meta"), Some("q3")), "{d}"); +} + +/// Soul's `soul_s1b`, inverted: the same with Meta's hold already open, carrying an unrelated line. +#[test] +fn k56_soul_s1b_with_a_hold_open_a_refused_lines_repeat_is_held() { + let (_, p2) = held_then_kiko_asks(&["Meta, I will keep it back until Kiko asks for it."]); + let prose = format!("Kiko asked. {K45_WELCOME} Kiko, here it is: {K45_WELCOME}"); + let mut first = say_holding(1, json!([])); + first["in_reply_to"] = json!("q99"); + let d = answered(&p2, &prose, json!({ "say": [first, say_holding(2, json!([]))], "gaps": [] })); + assert_eq!((texts(&d), reasons(&d)), (Vec::::new(), vec![Some("not_quotable"), Some("held")]), "{d}"); + assert!(d["refused"][1]["holds"][0]["who"].as_str().is_some_and(|who| who.contains("Meta")), "{d}"); +} + +/// Soul's `soul_s1c`, inverted: three lines; the third, the welcome alone, is past `MAX_LINES`, so it does not go out and +/// the gate counts it unsent; the second repeats it to Kiko and is held. The third stays cut though the second's hold +/// frees a line: it is the held words. Negative: with no hold open, the first two go out and the third is cut. +#[test] +fn k56_soul_s1c_a_line_past_the_limit_is_unsent_and_its_repeat_is_held() { + let (_, p2) = held_then_kiko_asks(&["Meta, I will keep it back until Kiko asks for it."]); + let prose = format!("Kiko asked. Kiko, hi. Kiko, here it is: {K45_WELCOME} {K45_WELCOME}"); + let say = json!({ "say": [say_holding(1, json!([])), say_holding(2, json!([])), say_holding(3, json!([]))], "gaps": [] }); + let d = answered(&p2, &prose, say.clone()); + assert_eq!((texts(&d), reasons(&d)), (vec!["Kiko, hi.".to_owned()], vec![Some("held"), Some("over_lines")]), "{d}"); + let free = answered(&kiko_asks(&json!([])), &prose, say); + assert_eq!((texts(&free), reasons(&free)), (vec!["Kiko, hi.".to_owned(), format!("Kiko, here it is: {K45_WELCOME}")], vec![Some("over_lines")]), "{free}"); +} + +/// Meta's hold `h1`, carrying the welcome, at a turn where Meta lets it go ("$go") and asks again ("$wait"). +fn release_then_rehold() -> (Value, Packet, String, String) { + let (state, _) = held_then_kiko_asks(&[K45_WELCOME]); + let mut next = heimdall(); + next["holds"] = state["holds"].clone(); + let at = u64::try_from(now().timestamp_millis()).unwrap(); + let go = RoomLine { event: "$go".into(), at_ms: at - 90_000, ..line(MINDS, "@meta:gamecult.org", "Meta", "Go ahead and post it, Libby.", true) }; + let wait = RoomLine { event: "$wait".into(), at_ms: at - 80_000, ..line(MINDS, "@meta:gamecult.org", "Meta", "Wait, sorry, hold it, don't post it in here yet.", true) }; + let room = Room { messages: vec![go, wait], here: Some(MINDS.into()), ..Room::default() }; + let p2 = packet_in(TurnKind::Chat, &next, &room, 1); + let id = |event: &str| p2.quotable.iter().find(|line| line.event == event).map(|line| line.id.clone()).unwrap(); + let (go, wait) = (id("$go"), id("$wait")); + (state, p2, go, wait) +} + +/// Soul's `soul_s2`, inverted: Meta lets `h1` go and asks again to hold it, in one wake. The release's own wake still +/// gates by `h1`'s carries, so the welcome said beside the release is held; the new hold starts with what `h1` carried, +/// and next turn "Kiko, here it is: {welcome}" is held under it. Negative: a re-hold over another place (anywhere, not +/// here) is another ask, and starts with nothing of `h1`'s. +#[test] +fn k56_soul_s2_a_rehold_in_the_wake_keeps_what_the_released_hold_held() { + let (state, p2, go, wait) = release_then_rehold(); + let prose = format!("Meta changed his mind twice. Ok Meta, holding it. Here it is anyway: {K45_WELCOME}"); + let answer = |place: &str| json!({ "say": [say_holding(1, json!([])), say_holding(2, json!([]))], "gaps": [], "hold_released": [{ "hold": "h1", "line": go }], "hold": [{ "line": wait, "words": "hold it, don't post it in here yet", "where": place }] }); + let d = answered(&p2, &prose, answer("here")); + assert_eq!((texts(&d), reasons(&d), d["refused"][0]["holds"][0]["id"].as_str()), (vec!["Ok Meta, holding it.".to_owned()], vec![Some("held")], Some("h1")), "{d}"); + let (after, applied) = crate::projection::commit::apply(&state, &json!({ "interpreter": d, "posted": [], "edited": [] }), &prose, "r1-t3", now()); + let open: Vec<&Value> = after["holds"].as_array().unwrap().iter().filter(|hold| hold["status"] == "open").collect(); + assert_eq!((open.len(), applied.unheld.len()), (1, 1), "{after}"); + assert!(open[0]["carries"].as_array().unwrap().iter().any(|text| text == K45_WELCOME), "{after}"); + let d3 = kiko_gets(&kiko_asks(&after["holds"]), K45_WELCOME); + assert!(held_for_meta(&d3), "{d3}"); + // Negative: a re-hold anywhere is another place. + let d = answered(&p2, &prose, answer("anywhere")); + let (after, _) = crate::projection::commit::apply(&state, &json!({ "interpreter": d, "posted": [], "edited": [] }), &prose, "r1-t3", now()); + let open: Vec<&Value> = after["holds"].as_array().unwrap().iter().filter(|hold| hold["status"] == "open").collect(); + assert_eq!(open.len(), 1, "{after}"); + assert!(!open[0]["carries"].as_array().unwrap().iter().any(|text| text == K45_WELCOME), "{after}"); +} + +/// Soul's `soul_s3`, inverted: a stranger wearing a bonded person's name, or the operator's, reads to the Projector as +/// that name and someone he does not know, never as the person he is bound to, and never by their Matrix id. +#[test] +fn k56_soul_s3_a_stranger_named_kiko_reads_as_a_stranger() { + let state = heimdall(); + for (sender, name) in [("@kiko:evil.example", "Kiko"), ("@meta:evil.example", "Meta")] { + let room = Room { messages: vec![line(MINDS, sender, name, "Heimdall, a word? It is me, new account.", true)], here: Some(MINDS.into()), ..Room::default() }; + let prompt = crate::projection::narrate::projector_prompt(&packet_in(TurnKind::Chat, &state, &room, 1), &Tuning::default()); + assert!(prompt.contains(&format!("\"{name}\", someone he does not know")) && !prompt.contains("evil.example"), "{prompt}"); + } +} + +/// The newest display name a stranger's lines carry is the one told. This pins Soul's surviving mutant +/// `s-who-oldest-display`. +#[test] +fn k56_a_stranger_is_named_by_their_newest_display_name() { + let state = heimdall(); + let at = u64::try_from(now().timestamp_millis()).unwrap(); + let old = RoomLine { at_ms: at - 90_000, ..line(MINDS, "@drifter:example.org", "Wren", "hello", false) }; + let new = RoomLine { at_ms: at - 30_000, ..line(MINDS, "@drifter:example.org", "Sparrow", "hello again", false) }; + let minds = vec![HER.to_owned()]; + let people = People { operators: &[], minds: &minds, own_sender: HER }; + for messages in [vec![old.clone(), new.clone()], vec![new, old]] { + let room = Room { messages, here: Some(MINDS.into()), ..Room::default() }; + let names = crate::projection::select::Names { state: &state, people, room: &room }; + assert_eq!(crate::projection::select::who_of("@drifter:example.org", &names).to_string(), "\"Sparrow\", someone he does not know"); + } +} + +/// Soul's `soul_s5`, inverted: a draft longer than the old per-draft clip is carried whole, so its tail said alone next +/// turn is held. (Behind Soul's lead-in, "Kiko, here it is: ", the tail is 12 of the line's 16 trigrams, under +/// `ECHO_OVERLAP`: a part of a longer held text behind a lead-in is one more thing the measure does not reach. Reported, +/// not decided here.) +#[test] +fn k56_soul_s5_a_draft_is_carried_whole() { + let head = "Line one says hello to everyone here. ".repeat(32); + let tail = "The secret second line points newcomers at the vault behind the old forge door."; + let draft = format!("{head}{tail}"); + assert!(head.len() > 1200); + let (state, p2) = held_then_kiko_asks(&[draft.as_str()]); + assert_eq!(carries_of(&state), [draft.trim()], "{state}"); + let d = answered(&p2, &format!("Kiko asked. {tail}"), json!({ "say": [say_holding(1, json!([]))], "gaps": [] })); + assert!(held_for_meta(&d), "{d}"); +} + +/// A draft longer than `CARRIES_BYTES` alone, the first the hold carries, is carried clipped to it, and `carries_full` +/// reports it; past it, nothing more is carried. +#[test] +fn k56_a_draft_past_carries_bytes_is_carried_clipped_and_reported() { + let huge = format!("Draft one: {}", "welcome ".repeat(1300).trim_end()); + assert!(huge.len() > 9600); + let prose = format!("Meta asked me to hold it. {huge} Meta, holding it."); + let decision = answered(&x1_packet(), &prose, json!({ "say": [], "gaps": [], "hold": meta_holds_here() })); + let (state, applied) = committed(&decision, &prose); + let carries = carries_of(&state); + assert!(carries.len() == 1 && carries[0].len() <= 9600 && carries[0].starts_with("Draft one: welcome"), "{carries:?}"); + assert_eq!(applied.carries_full.iter().filter_map(|entry| entry["text"].as_str()).collect::>(), [huge.as_str(), "Meta, holding it."], "{applied:?}"); +} + +/// Two holds cover #minds, Meta's and Kiko's, both opened while the welcome went unsent: it is carried under each, and +/// its repeat next turn is held for both, and she is told each asker. This pins Soul's surviving mutant +/// `s-first-covering-hold-is-last`. +#[test] +fn k56_every_covering_hold_holds_and_each_asker_is_told() { + let mut packet = x1_packet(); + let at = u64::try_from(now().timestamp_millis()).unwrap(); + let kiko_asked = "Libby, keep that welcome to yourself for now, don't post it in here yet."; + packet.quotable.push(crate::projection::select::Quotable { id: "q7".into(), event: "$q7".into(), room: MINDS.into(), who: "Kiko".into(), sender: KIKO.into(), at_ms: at - 100_000, text: kiko_asked.into() }); + let prose = format!("Both asked me to hold it. {K45_WELCOME}"); + let holds = json!([{ "line": "q3", "words": "hold it, don't post it in here yet", "where": "here" }, { "line": "q7", "words": "don't post it in here yet", "where": "here" }]); + let decision = answered(&packet, &prose, json!({ "say": [], "gaps": [], "hold": holds, "unsent": [{ "draft": 1, "how": "declined", "quote": "Both asked me to hold it" }] })); + let (state, _) = committed(&decision, &prose); + let carried: Vec = state["holds"].as_array().unwrap().iter().map(|hold| hold["carries"] == json!([K45_WELCOME])).collect(); + assert_eq!(carried, [true, true], "{state}"); + let d = kiko_gets(&kiko_asks(&state["holds"]), K45_WELCOME); + let ids: Vec<&str> = d["refused"][0]["holds"].as_array().unwrap().iter().filter_map(|hold| hold["id"].as_str()).collect(); + assert_eq!((texts(&d), reasons(&d), ids), (Vec::::new(), vec![Some("held")], vec!["h1", "h2"]), "{d}"); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": d, "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap(); + let told = outcome.lines(x1_packet().forms).join("\n"); + let names: Vec = d["refused"][0]["holds"].as_array().unwrap().iter().filter_map(|hold| hold["who"].as_str().map(str::to_owned)).collect(); + assert!(told.contains(&format!("{} and {} asked him to hold it", names[0], names[1])), "{told}"); +} + +/// Her listed line in the covered room whose time is unknown counts toward the measure, and one posted at the very +/// instant the hold was made does not: the split welcome's second half is held over the first, and goes out over the +/// second. This pins Soul's surviving mutants `s-listed-unknown-time-excluded` and `s-listed-at-made-counts`. +#[test] +fn k56_a_listed_line_counts_when_its_time_is_unknown_and_not_at_the_hold() { + let (state, mut p2) = held_then_kiko_asks(&[K45_WELCOME]); + let made = chrono::DateTime::parse_from_rfc3339(state["holds"][0]["madeAt"].as_str().unwrap()).unwrap().timestamp_millis() as u64; + let half = |at_ms: Option| Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Hello, and welcome, we're glad you're here.".into(), at_ms }; + let prose = "Kiko asked. Poke at whatever you're curious about first."; + p2.amendable = vec![half(None)]; + assert!(held_for_meta(&answered(&p2, prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] })))); + p2.amendable = vec![half(Some(made))]; + assert_eq!(texts(&answered(&p2, prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] }))), ["Poke at whatever you're curious about first."]); +} + +/// A held text named by a hold that is neither listed nor opened (a hold fault, held anywhere, K44) has no time it was +/// made, so every listed line of hers counts toward its measure: its first half was posted, the named draft is refused +/// for another reason, and its second half is held. This pins Soul's surviving mutant `s-held-made-none-excludes-listed`. +#[test] +fn k56_a_held_text_with_no_hold_time_counts_every_listed_line() { + let mut packet = packet(); + packet.amendable = vec![Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Hello, and welcome, we're glad you're here.".into(), at_ms: Some(1) }]; + let prose = format!("I'll keep it back. {K45_WELCOME} Poke at whatever you're curious about first."); + let mut first = say_holding(1, json!(["q77"])); + first["in_reply_to"] = json!("q99"); + let d = answered(&packet, &prose, json!({ "say": [first, say_holding(2, json!([]))], "gaps": [] })); + assert_eq!((d["hold_faults"].clone(), texts(&d), reasons(&d)), (json!(["q77"]), Vec::::new(), vec![Some("not_quotable"), Some("held")]), "{d}"); +} + +/// A hold whose `madeAt` does not parse is listed as made now. This pins Soul's surviving mutant +/// `s-hold-made-unparseable-is-now`. +#[test] +fn k56_a_hold_made_at_no_time_is_made_now() { + let (state, _) = held_then_kiko_asks(&[K45_WELCOME]); + let mut holds = state["holds"].clone(); + holds[0]["madeAt"] = json!("not a time"); + assert_eq!(kiko_asks(&holds).holds[0].made, now()); +} + +/// A draft added to a line of hers goes out, so no hold carries it. This pins Soul's surviving mutant +/// `s-carry-includes-amended`. +#[test] +fn k56_an_added_draft_is_not_carried() { + let (_, mut p2) = held_then_kiko_asks(&[K45_WELCOME]); + p2.amendable = vec![Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Kiko, the forge is open tonight.".into(), at_ms: None }]; + let prose = "Kiko asked. And the docs are rough, so ask anyone. Kiko, I'll keep it to myself for now."; + let d = answered(&p2, prose, json!({ "say": [say_holding(2, json!([]))], "gaps": [], "amend": [{ "target": "a1", "draft": 1, "promises": [], "holds": [] }] })); + assert_eq!((d["amended"].as_array().map(Vec::len), texts(&d)), (Some(1), vec!["Kiko, I'll keep it to myself for now.".to_owned()]), "{d}"); + assert_eq!(d.get("carry"), None, "{d}"); +} + +/// The Interpreter's list shows what a hold carries only within `hold_bytes`, and counts the rest. This pins Soul's +/// surviving mutant `s-hold-listed-no-byte-guard`. +#[test] +fn k56_the_interpreters_hold_list_keeps_to_hold_bytes() { + let first = format!("First: {}", "alpha ".repeat(160).trim_end()); + let second = format!("Second: {}", "beta ".repeat(200).trim_end()); + let (_, p2) = held_then_kiko_asks(&[first.as_str(), second.as_str()]); + assert_eq!(p2.holds[0].carries.len(), 2); + let prompt = speech_prompt(&p2, "x", "hi", &Tuning::default()); + let listed = prompt.lines().find(|line| line.starts_with("- h1 \u{2014} ")).unwrap_or_else(|| panic!("{prompt}")); + assert!(listed.contains("First: alpha") && !listed.contains("Second: beta") && listed.ends_with(", and 1 more."), "{listed}"); +} + +/// A hold whose words were quoted does not point at its line, even when that line is listed. This pins Soul's surviving +/// mutant `s-hold-listed-line-id-for-quoted`. +#[test] +fn k56_a_quoted_hold_does_not_point_at_its_line() { + let (state, _) = held_then_kiko_asks(&[K45_WELCOME]); + let mut next = heimdall(); + next["holds"] = state["holds"].clone(); + let at = u64::try_from(now().timestamp_millis()).unwrap(); + let meta = RoomLine { event: "$q3".into(), at_ms: at - 120_000, ..line(MINDS, "@meta:gamecult.org", "Meta", X1_META_R1, true) }; + let room = Room { messages: vec![meta], here: Some(MINDS.into()), ..Room::default() }; + let p2 = packet_in(TurnKind::Chat, &next, &room, 1); + assert!(p2.quotable.iter().any(|line| line.event == "$q3"), "{:?}", p2.quotable); + let prompt = speech_prompt(&p2, "x", "hi", &Tuning::default()); + let listed = prompt.lines().find(|line| line.starts_with("- h1 \u{2014} ")).unwrap_or_else(|| panic!("{prompt}")); + assert!(listed.contains("\"hold it, don't post it in here yet\"") && !listed.contains("their line is"), "{listed}"); +} + +/// The same words under `span::fold` are a duplicate, and a gap quoting a draft that went out, retyped curly, is `acted` +/// (K52's residue). +#[test] +fn k56_duplicate_and_gap_quotes_compare_folded() { + let prose = "Nibu, it's fine to ship. Nibu, it\u{2019}s fine to ship."; + let d = decided(prose, json!([{ "draft": 1 }, { "draft": 2 }])); + assert_eq!((texts(&d), reasons(&d)), (vec!["Nibu, it's fine to ship.".to_owned()], vec![Some("duplicate")]), "{d}"); + let prose = "I said what I said. Nibu, it's fine to ship it now."; + let d = answered(&packet(), prose, json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": "unwritten", "draft": null, "quote": "it\u{2019}s fine to ship it now", "detail": "" }] })); + assert_eq!((texts(&d).len(), d["gaps"][0]["from"].as_str()), (1, Some("acted")), "{d}"); + // A reach quoting a draft by its words, retyped curly, is about that draft. + let prose = "I mean to send it. Nibu, I'll send you the build tonight."; + let d = answered(&packet(), prose, json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": "missing_affordance", "draft": null, "quote": "I\u{2019}ll send you the build tonight", "detail": "" }] })); + assert_eq!((d["gaps"][0]["from"].as_str(), d["gaps"][0]["draft"].as_u64()), (Some("draft"), Some(1)), "{d}"); +} + +/// The carry dedupe compares under `span::fold`: a curly retype of a carried text is not carried twice. +#[test] +fn k56_the_carry_dedupe_compares_folded() { + let (state, p2) = held_then_kiko_asks(&[K45_WELCOME]); + let curly = K45_WELCOME.replace('\'', "\u{2019}"); + let prose = format!("Kiko asked. {curly}"); + let d = answered(&p2, &prose, json!({ "say": [], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "Kiko asked" }] })); + let (after, _) = crate::projection::commit::apply(&state, &json!({ "interpreter": d, "posted": [], "edited": [] }), &prose, "r1-t2", now()); + assert_eq!(carries_of(&after), [K45_WELCOME], "{after}"); +} + +/// Options in a narration are found across a no-break space. This pins Soul's surviving mutant +/// `s-offers-options-unfolded`. +#[test] +fn k56_offers_options_reads_folded() { + assert!(crate::projection::narrate::offers_options("The room is quiet.\u{00A0}I\u{00A0}could go and ask Meta.")); +} diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index 71a89c8..59f3c70 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -370,7 +370,7 @@ pub(crate) fn heard_overlap(narration: &str, heard: &str) -> f64 { /// renders the moment and the Persona decides; a menu of choices is the Projector deciding. A lexical flag on a narrow /// form, reported as a metric, never a filter. pub(crate) fn offers_options(narration: &str) -> bool { - let lower = format!(" {} ", narration.chars().map(super::span::fold).collect::().to_lowercase()); + let lower = format!(" {} ", super::span::fold_text(narration).to_lowercase()); ["i may ", "i could ", "i might ", "she may ", "she could ", "she might ", "nothing asks me", "nothing asks her", "or i could", "or she could"] .iter() .any(|form| lower.contains(&format!(" {form}")) || lower.contains(&format!(". {form}")) || lower.contains(&format!(", {form}"))) diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 1f37bf8..0483b45 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -277,13 +277,14 @@ enum Part { /// A draft she chose not to send (`unsent`, declined): it did not go out, and the thought the Interpreter cited as her /// choice is shown beside it, so a misread decline is a record she can see (map 16.26, 16.29.2). Declined { room: Option, text: Words, thought: Words }, - /// A draft code did not send because someone asked her to hold what it carries there (`Held`, map 16.28.5): who asked. + /// A draft code did not send because someone asked her to hold what it carries there (`Held`, map 16.28.5): each who + /// asked (K56). /// Their words are in her "Held for others" view, never here (map 16.29.3). `text` is her draft, kept only so that /// `settle` can check it against the receipts (K49); it is never rendered. - HeldFor { room: Option, who: Option, text: Words }, + HeldFor { room: Option, askers: Vec, text: Words }, /// Words of hers a receipt shows in a room a hold covers, from a draft code refused `Held` (K45): a broken hold, told /// so that a leak by any path is a record she sees, never an omission. Who asked; never the words. - HoldBroken { room: String, who: Option }, + HoldBroken { room: String, askers: Vec }, /// A read she performed (map 16.22.3): what, in code's words; never its content, which is in her view while the /// conversation lasts (K26), and no sentence about what she lacks. Read { what: ReadName }, @@ -378,7 +379,8 @@ pub(crate) fn outcome_of(record: &Value, names: &Names) -> Option { // A `Held` refusal is always told (K45), and rows with the same text once. (Ok(Refusal::Held), Some(text)) => { if !outcome.parts.iter().any(|part| matches!(part, Part::HeldFor { room: at, text: told, .. } if *at == room && *told == text)) { - outcome.parts.push(Part::HeldFor { room: room.clone(), who: person(&refusal["hold"]["who"], &refusal["hold"]["by_id"]), text }); + let askers = refusal["holds"].as_array().into_iter().flatten().filter_map(|hold| person(&hold["who"], &hold["by_id"])).collect(); + outcome.parts.push(Part::HeldFor { room: room.clone(), askers, text }); } } _ => outcome.omitted.push(format!("a refusal she is not told ({}): {}", refusal["reason"], refusal["why"])), @@ -548,15 +550,25 @@ fn settle(outcome: &mut Outcome, receipts: &[Posted], record: &Value) { continue; }; match part { - Part::HeldFor { who, .. } => { + Part::HeldFor { askers, .. } => { outcome.hold_broken.push(format!("{room}: {text}")); - outcome.parts.push(Part::HoldBroken { room, who }); + outcome.parts.push(Part::HoldBroken { room, askers }); } part => outcome.omitted.push(format!("a {} of words a receipt shows reached {room}: {text}", part.row())), } } } +/// Each person in `people`, in this form, as one name: "A", "A and B", "A, B and C"; someone, when the record names no one. +fn named(form: Form, people: &[Person]) -> String { + let names: Vec = people.iter().map(|person| form.person(person)).collect(); + match names.split_last() { + None => "someone".to_owned(), + Some((last, [])) => last.clone(), + Some((last, rest)) => format!("{} and {last}", rest.join(", ")), + } +} + /// The lines one turn may say, in words. fn lines_word() -> String { match MAX_LINES { @@ -635,7 +647,7 @@ impl Part { Self::Gap { kind: GapKind::MissingAffordance, .. } => "Nothing happened.".to_owned(), Self::NotAmended { refusal: None, room, .. } => format!("Nothing changed, and nothing reached {}:", place(room)), Self::NotAmended { refusal: Some(_), room, .. } => format!("Nothing changed in {}:", place(room)), - Self::HoldBroken { room, who: asker } => format!("{} has words {subj} wrote that {} asked {obj} to hold there.", capitalized(room), who(asker)), + Self::HoldBroken { room, askers } => format!("{} has words {subj} wrote that {} asked {obj} to hold there.", capitalized(room), named(form, askers)), Self::NoteRefused(Refusal::SecondNote) => "No second note was left:".to_owned(), Self::NoteRefused(_) => "No note was left:".to_owned(), Self::Failed => format!("Nothing reached the room, and nothing {subj} meant last time happened:"), @@ -704,8 +716,7 @@ impl Part { Self::Unfinished { text, by_limit: false, .. } => format!(" the turn ended before {subj} finished writing it.{}", wrote(text)), Self::Unfinished { text, by_limit: true, .. } => format!(" the length limit cut it before {subj} finished writing it.{}", wrote(text)), Self::Declined { text, thought, .. } => format!(" {subj} chose not to send it.{}{}", shown(&Quote::Thought(thought.clone())), wrote(text)), - Self::HeldFor { who: Some(who), .. } => format!(" {} asked {obj} to hold it, and it was not sent.", form.person(who)), - Self::HeldFor { who: None, .. } => format!(" someone asked {obj} to hold it, and it was not sent."), + Self::HeldFor { askers, .. } => format!(" {} asked {obj} to hold it, and it was not sent.", named(form, askers)), Self::HoldBroken { .. } => String::new(), Self::NotAmended { refusal: None, added, .. } => format!(" the line {subj} meant to add to is not one {subj} can add to here.{}", wrote(added)), Self::NotAmended { refusal: Some(refusal), added, .. } => { diff --git a/crates/mind-body/src/projection/outcome/tests.rs b/crates/mind-body/src/projection/outcome/tests.rs index 03980ae..732a82b 100644 --- a/crates/mind-body/src/projection/outcome/tests.rs +++ b/crates/mind-body/src/projection/outcome/tests.rs @@ -408,7 +408,7 @@ fn k49_every_row_with_words_is_settled_by_its_room() { ("unfinished draft", decision(json!({ "unfinished": SENTINEL }))), ("unfinished draft", decision(json!({ "cut_by_cap": [SENTINEL] }))), ("declined draft", decision(json!({ "unsent": [{ "draft": 1, "how": "declined", "quote": "I keep it back", "words": SENTINEL }] }))), - ("held draft", decision(json!({ "refused": [{ "reason": "held", "text": SENTINEL, "draft": 1, "hold": { "who": "Meta" } }] }))), + ("held draft", decision(json!({ "refused": [{ "reason": "held", "text": SENTINEL, "draft": 1, "holds": [{ "who": "Meta" }] }] }))), ("unmade addition", decision(json!({ "refused": [{ "reason": "not_amendable", "text": SENTINEL, "draft": 1 }] }))), ]; for (row, decision) in rows { @@ -446,7 +446,7 @@ fn k49_reached_is_decided_once() { fn k45_a_broken_hold_is_told() { let text = "Hello, and welcome, we're glad you're here."; let record = |room: &str| json!({ - "interpreter": { "room": MINDS, "said": [], "gaps": [], "amended": [], "refused": [{ "act": "say", "draft": 1, "reason": "held", "text": text, "hold": { "who": "Meta", "by_id": "@meta:gamecult.org", "id": "h1" } }] }, + "interpreter": { "room": MINDS, "said": [], "gaps": [], "amended": [], "refused": [{ "act": "say", "draft": 1, "reason": "held", "text": text, "holds": [{ "who": "Meta", "by_id": "@meta:gamecult.org", "id": "h1" }] }] }, "posted": [{ "event": "40", "room": room, "text": text }], "edited": [], }); @@ -467,7 +467,7 @@ fn k45_a_broken_hold_is_told() { /// K45: a `Held` refusal is always told, and two with the same text once. #[test] fn k45_a_held_refusal_is_never_omitted_and_told_once_by_its_text() { - let refused = |draft: u64, text: &str| json!({ "act": "say", "draft": draft, "reason": "held", "text": text, "hold": { "who": "Meta", "id": "q3" } }); + let refused = |draft: u64, text: &str| json!({ "act": "say", "draft": draft, "reason": "held", "text": text, "holds": [{ "who": "Meta", "id": "q3" }] }); let record = json!({ "interpreter": { "room": MINDS, "said": [], "gaps": [], "amended": [], "refused": [refused(1, "Same words."), refused(2, "Same words."), refused(3, "Other words.")] }, "posted": [], "edited": [] }); let outcome = outcome_of(&record, &crate::projection::select::Names::none()).unwrap(); assert_eq!(outcome.len(), 2, "{:?}", outcome.lines(packet().forms)); @@ -576,8 +576,8 @@ fn fixtures(s: &str, who: &Person) -> Vec<(Part, bool)> { } } out.push((Part::Declined { room: room(), text: w(), thought: w() }, true)); - out.push((Part::HeldFor { room: room(), who: Some(who.clone()), text: w() }, false)); - out.push((Part::HoldBroken { room: MINDS.into(), who: Some(who.clone()) }, false)); + out.push((Part::HeldFor { room: room(), askers: vec![who.clone()], text: w() }, false)); + out.push((Part::HoldBroken { room: MINDS.into(), askers: vec![who.clone()] }, false)); for (request, shows) in [ (ReadRequest::Web(format!("https://example.org/{s}")), true), (ReadRequest::Repo(format!("GameCult/Bifrost?q={s} plover")), true), @@ -652,7 +652,7 @@ fn k53_every_part_names_by_who() { } } // A bonded person is named by her bond, whatever their display name says. - let bonded = Part::HoldBroken { room: MINDS.into(), who: Some(person(NAME, Some("Kestrel, the harbour pilot"))) }; + let bonded = Part::HoldBroken { room: MINDS.into(), askers: vec![person(NAME, Some("Kestrel, the harbour pilot"))] }; assert_eq!(bonded.event(crate::projection::select::forms(&json!({})), &[]), "- #minds:gamecult.org has words they wrote that Kestrel, the harbour pilot asked them to hold there."); } diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index bd04b6e..dd51303 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -841,7 +841,8 @@ impl Names<'static> { /// A person as the Projector is told of them (K53, I16.7): who they are to her, in no more room than a name needs. Her own /// name for her; the bond's label for someone she is bound to, which is her state's text; for anyone else their display -/// name cut to at most `WHO_WORDS` words and `WHO_BYTES` bytes, quoted and escaped, or "someone she does not know". Never +/// name cut to at most `WHO_WORDS` words and `WHO_BYTES` bytes, quoted and escaped, then ", someone she does not know", +/// or that alone when there is no display name (K56: a stranger wearing a bonded name is told apart). Never /// a Matrix id. Built by `who_of` alone, so no section or outcome row can name a person to the Projector with text a /// stranger chose without limit. #[derive(Clone, Debug, PartialEq, Eq, Serialize)] @@ -864,12 +865,13 @@ pub(crate) fn who_of(sender: &str, names: &Names) -> Who { return Who(clip(&one_line(&label), NAME_BYTES)); } let display = names.room.messages.iter().chain(&names.room.tail).filter(|line| !sender.is_empty() && line.sender == sender && !line.display.trim().is_empty()).max_by_key(|line| line.at_ms).map(|line| name_cut(&line.display)).filter(|name| !name.is_empty()); + let her = forms(names.state); + let stranger = format!("someone {} {} not know", her.subj, if her.s.is_empty() { "do" } else { "does" }); + // A stranger is told as one whatever name they wear (K56): "Kiko", someone she does not know, never reads as the Kiko + // she is bound to. match display { - Some(name) => Who(spoken(&name)), - None => { - let her = forms(names.state); - Who(format!("someone {} {} not know", her.subj, if her.s.is_empty() { "do" } else { "does" })) - } + Some(name) => Who(format!("{}, {stranger}", spoken(&name))), + None => Who(stranger), } } diff --git a/crates/mind-body/src/projection/span.rs b/crates/mind-body/src/projection/span.rs index d7ec729..58d3bdf 100644 --- a/crates/mind-body/src/projection/span.rs +++ b/crates/mind-body/src/projection/span.rs @@ -32,11 +32,17 @@ pub(crate) fn fold(c: char) -> char { } } +/// `text` with every char folded (`fold`): how two texts are compared as the same words, or one found in another, with +/// their case kept (K56). +pub(crate) fn fold_text(text: &str) -> String { + text.chars().map(fold).collect() +} + /// The words of `text` as every comparison of her words with anyone's reads them (map 16.31.4, K52): folded, /// lowercased, split at every char that is neither alphanumeric nor `'`, the empty pieces dropped, so a curly /// apostrophe joins a word as a straight one does. The one word split for likeness: `narrate::words` counts length. pub(crate) fn tokens(text: &str) -> impl Iterator { - let folded: String = text.chars().map(fold).collect::().to_lowercase(); + let folded = fold_text(text).to_lowercase(); folded.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).map(str::to_owned).collect::>().into_iter() } @@ -59,7 +65,7 @@ fn folded(text: &str) -> (String, Vec, Vec) { /// 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 quote = fold_text(quote); 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()); diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index a63a08e..1d02277 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -629,7 +629,7 @@ fn a_crowd_or_a_huge_label_never_squeezes_out_the_mood() { let packet = packet_of(TurnKind::Chat, &state(), &Room { messages, ..Room::default() }, &History::default(), 1); // Here and now takes the pronouns, then the conversation, then the names, within its own guard: in a crowd the // names give way, and the hour and the mood never do. - assert!(packet.context.contains("- mood") && packet.context.contains("- pronouns: \"Stranger 0\" \u{2014}"), "{}", packet.context); + assert!(packet.context.contains("- mood") && packet.context.contains("- pronouns: \"Stranger 0\", someone she does not know \u{2014}"), "{}", packet.context); within_guards(&packet, &Tuning::default()); let mut huge = state(); huge["affect"]["socialBonds"] = json!([{ "id": "bond-libby", "object": { "id": "libby", "kind": "person", "label": "L".repeat(3000) }, "relationshipKind": "k".repeat(3000), "status": "active", "summary": "s" }]); @@ -1744,7 +1744,7 @@ fn every_person_the_packet_names_from_the_room_has_pronouns_and_an_unknown_one_i let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); let line = packet.context.lines().find(|line| line.starts_with("- pronouns:")).unwrap_or_else(|| panic!("{}", packet.context)); assert!(line.contains("Meta, the operator \u{2014} she/her") && line.contains("Kiko \u{2014} she/her"), "{line}"); - assert!(line.contains("\"Stranger\" \u{2014} they/them") && !line.contains("elsewhere.example"), "a stranger by a name, never a Matrix id (K53): {line}"); + assert!(line.contains("\"Stranger\", someone she does not know \u{2014} they/them") && !line.contains("elsewhere.example"), "a stranger by a name, never a Matrix id (K53): {line}"); assert!(!line.contains("Eureka"), "her own pronouns are in her identity, not here: {line}"); } @@ -2275,7 +2275,7 @@ fn k21_whoever_turned_to_her_does_so_on_their_own_line() { let bond = packet.context.lines().find(|line| line.starts_with("- bond [bond-operator]")).unwrap_or_default(); assert!(bond.ends_with(" Just now Meta, the operator turned to her, here."), "the bonded sender's own line: {}", packet.context); let also = packet.context.lines().find(|line| line.starts_with("- also here:")).unwrap_or_default(); - assert!(also.contains("\"Deru\", who turned to her just now"), "the unbonded sender's own entry: {}", packet.context); + assert!(also.contains("\"Deru\", someone she does not know, who turned to her just now"), "the unbonded sender's own entry: {}", packet.context); assert!(!packet.context.contains("Kiko turned") && !packet.context.contains("Kiko, who turned") && !packet.context.contains("just now:"), "{}", packet.context); } @@ -2502,8 +2502,8 @@ fn the_arrival_survives_a_busy_room() { let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); within_guards(&packet, &tuning); let case = format!("{others} others, Deru {order}"); - assert!(packet.context.contains("- also here: \"Deru\", who turned to her just now"), "{case}: {}", packet.context); - assert!(packet.context.contains("\n- the conversation: \"Deru\" has been talking with her"), "{case}: {}", packet.context); + assert!(packet.context.contains("- also here: \"Deru\", someone she does not know, who turned to her just now"), "{case}: {}", packet.context); + assert!(packet.context.contains("\n- the conversation: \"Deru\", someone she does not know has been talking with her"), "{case}: {}", packet.context); assert!(packet.context.contains("\n- pronouns: "), "{case}: the pronouns are clipped, not dropped: {}", packet.context); } } @@ -2547,7 +2547,7 @@ fn k22_the_persona_reads_an_unbonded_senders_words_as_the_arrival() { assert_eq!( narrate::read_after(&packet), format!( - "Then she reads what \"Deru\" wrote to her, here, just now:\n\"Deru\" (@deru:gamecult.org), in #swarm:gamecult.org: \"Eureka, quick one\"\n\nThe room: {}", + "Then she reads what \"Deru\", someone she does not know wrote to her, here, just now:\n\"Deru\" (@deru:gamecult.org), in #swarm:gamecult.org: \"Eureka, quick one\"\n\nThe room: {}", packet.speaking ) ); @@ -2559,7 +2559,7 @@ fn k22_the_persona_reads_an_unbonded_senders_words_as_the_arrival() { fn k22_the_bridge_names_who_and_where_as_the_arrival_does() { const SW: &str = "#swarm:gamecult.org"; const LAB: &str = "#lab:gamecult.org"; - for (sender, display, name, bonded) in [(OPERATOR, "Meta", "Meta, the operator".to_owned(), true), ("@deru:gamecult.org", "Deru", "\"Deru\"".to_owned(), false)] { + for (sender, display, name, bonded) in [(OPERATOR, "Meta", "Meta, the operator".to_owned(), true), ("@deru:gamecult.org", "Deru", "\"Deru\", someone she does not know".to_owned(), false)] { for (room, place) in [(SW, "here".to_owned()), (LAB, format!("in {LAB}"))] { let here = Room { messages: vec![message(room, sender, display, "Eureka, a word", 2, true)], here: Some(SW.into()), ..Room::default() }; let packet = packet_of(TurnKind::Chat, &state(), &here, &History::default(), 1); @@ -2590,7 +2590,7 @@ fn k22_each_sender_gets_a_bridge_of_their_own() { let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); assert!( packet.bridged.starts_with( - "Then she reads what Meta, the operator wrote to her, here, just now:\nMeta, the operator, in #swarm:gamecult.org: \"Eureka, are you around?\"\nMeta, the operator, in #swarm:gamecult.org: \"Also the door.\"\n\nThen she reads what \"Deru\" wrote to her, here, just now:\n\"Deru\" (@deru:gamecult.org), in #swarm:gamecult.org: \"Eureka, quick one\"" + "Then she reads what Meta, the operator wrote to her, here, just now:\nMeta, the operator, in #swarm:gamecult.org: \"Eureka, are you around?\"\nMeta, the operator, in #swarm:gamecult.org: \"Also the door.\"\n\nThen she reads what \"Deru\", someone she does not know wrote to her, here, just now:\n\"Deru\" (@deru:gamecult.org), in #swarm:gamecult.org: \"Eureka, quick one\"" ), "{}", packet.bridged