diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index 179035b..d8ed78b 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -35,8 +35,10 @@ 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 of her own held drafts a hold carries (K45): the oldest drop. -const CARRIES_KEPT: usize = 4; +/// 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. +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`). @@ -362,8 +364,11 @@ pub(crate) struct Applied { /// The holds opened (`hold_open`, map 16.28.5), and the holds released (`hold_release`), as they now stand. pub held: Vec, pub unheld: Vec, - /// The `Held` refusals whose hold no hold of hers answers (K45): their words are carried nowhere. + /// The decision's `carry` entries whose hold no open hold of hers answers (K45, K51): their words are carried nowhere. pub held_unrecorded: Vec, + /// The `carry` entries a hold had no room left for under `CARRIES_BYTES` (K51): not carried, so that what it already + /// carries stays. + pub carries_full: Vec, } /// The one applier: her state with one turn's proposals applied, as deltas to `state` as it stands at commit, and what @@ -421,15 +426,16 @@ pub(crate) fn apply(state: &Value, record: &Value, prose: &str, key: &str, now: (state, applied) } -/// Each `Held` refusal's draft, carried by its hold (map 16.30.2, K45), after the holds this apply opened: the hold's -/// handle is a hold listed to the Interpreter (`h1`), or the line an open hold opened from (`q3`). Duplicates are -/// skipped, at most `CARRIES_KEPT` are kept (the oldest drop), and each is held to `CARRY_BYTES`. A handle no open hold -/// answers carries nothing, and is reported. The decision proposes and the commit writes. +/// 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. fn carry_held(state: &mut Value, record: &Value, applied: &mut Applied) { let decision = &record["interpreter"]; - for refusal in decision["refused"].as_array().into_iter().flatten().filter(|refusal| refusal["reason"] == "held") { - let (Some(text), Some(handle)) = (refusal["text"].as_str(), refusal["hold"]["id"].as_str()) else { - applied.held_unrecorded.push(refusal.clone()); + for entry in decision["carry"].as_array().into_iter().flatten() { + let (Some(text), Some(handle)) = (entry["text"].as_str(), entry["hold"].as_str()) else { + applied.held_unrecorded.push(entry.clone()); continue; }; let listed = decision["holds"].as_array().into_iter().flatten().find(|listed| listed["id"].as_str() == Some(handle)).map(|listed| listed["entry"].clone()); @@ -438,7 +444,7 @@ fn carry_held(state: &mut Value, record: &Value, applied: &mut Applied) { hold["status"] == "open" && (listed.as_ref().is_some_and(|entry| hold["id"] == *entry) || line.as_ref().is_some_and(|event| hold["event"] == *event)) }); let Some(hold) = hold else { - applied.held_unrecorded.push(refusal.clone()); + applied.held_unrecorded.push(entry.clone()); continue; }; let text = super::select::clip(text, CARRY_BYTES); @@ -446,10 +452,14 @@ fn carry_held(state: &mut Value, record: &Value, applied: &mut Applied) { 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().any(|carried| carried.as_str() == Some(text.as_str())) { + 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 { carries.push(json!(text)); - let over = carries.len().saturating_sub(CARRIES_KEPT); - carries.drain(..over); } } } diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index 0d2eb38..8c2b1a8 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -1052,13 +1052,17 @@ fn k40_an_outside_close_is_not_hers_to_reopen() { assert_eq!(f2_r9(&amended, json!([reopening(F2_R9_WORDS, None, true)])).0["commitments"][0]["status"], "open"); } -/// K45 (map 16.30.2): each `Held` refusal's draft is carried by its hold once, at most four, the oldest dropping. +/// K51 (map 16.31.3): the commit carries the decision's `carry` and nothing else: each entry once, on the hold its handle +/// names. A `Held` refusal is one fate of an unsent draft, never how a text becomes carried, so a refusal alone carries +/// nothing (this pins the reason filter put back in `carry_held`). A handle no open hold answers carries nothing, and is +/// reported. #[test] -fn k45_a_hold_carries_each_held_draft_once_and_at_most_four() { +fn k51_carry_reads_the_decision_carry_and_nothing_else() { let (state, listed) = x1_holding(); - let held = |text: &str| json!({ "act": "say", "draft": 1, "reason": "held", "text": text, "hold": { "who": "Meta", "id": "h1" } }); + let carry = |hold: &str, text: &str| json!({ "hold": hold, "text": text }); let mut record = hearing(&[], listed, json!([])); - record["interpreter"]["refused"] = json!([held("One."), held("Two."), held("One."), held("Three."), held("Four."), held("Five.")]); + 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" } }]); 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.len()), (json!(["Two.", "Three.", "Four.", "Five."]), None, 0), "{after}"); + 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 35644fe..e011fd6 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -36,7 +36,7 @@ //! composes the edit), and leave Self one note (`suggest`, map 16.18; recorded in the turn's record, never a write to her //! Mind). A draft is said or added once, in one room; the same draft may also be her note to Self (map 16.29.8). -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use super::span; use serde::{Deserialize, Serialize}; @@ -588,7 +588,7 @@ pub(crate) fn speech_prompt_in(packet: &Packet, narration: &str, prose: &str, tu if promises.is_empty() { promises.push_str("- none\n"); } - let mut holds: String = packet.holds.iter().map(|hold| format!("- {} \u{2014} {}\n", hold.id, crate::projection::select::hold_line(hold, &hold.made.format("%Y-%m-%d %H:%M UTC").to_string()))).collect(); + let mut holds: String = packet.holds.iter().map(|hold| format!("- {} \u{2014} {}\n", hold.id, hold_listed(hold, packet, tuning))).collect(); if holds.is_empty() { holds.push_str("- none\n"); } @@ -659,6 +659,37 @@ pub(crate) fn speech_prompt_in(packet: &Packet, narration: &str, prose: &str, tu ) } +/// A hold as the Interpreter's list shows it (map 16.31.3, K51): `hold_line`, then what she has held for it, oldest first, +/// while it fits `hold_bytes`, the rest counted; and for a hold the record could not quote whose line is listed, that +/// line's id, so naming has the asker's words to judge by. The asker's words are not copied into the hold. +fn hold_listed(hold: &crate::projection::select::Hold, packet: &Packet, tuning: &Tuning) -> String { + let her = packet.forms; + let line = crate::projection::select::hold_line(hold, &hold.made.format("%Y-%m-%d %H:%M UTC").to_string()); + let mut more = String::new(); + if !hold.carries.is_empty() { + let mut shown: Vec = Vec::new(); + let mut bytes = 0; + for text in &hold.carries { + let quoted = spoken(text); + if bytes + quoted.len() > tuning.select.hold_bytes { + break; + } + bytes += quoted.len() + 2; + shown.push(quoted); + } + let rest = hold.carries.len() - shown.len(); + more.push_str(&match (shown.is_empty(), rest) { + (true, _) => format!("; {} {} held {rest} of {} drafts for them", her.subj, her.has, her.poss), + (false, 0) => format!("; {} {} held for them: {}", her.subj, her.has, shown.join(", ")), + (false, _) => format!("; {} {} held for them: {}, and {rest} more", her.subj, her.has, shown.join(", ")), + }); + } + if let Some(asked) = packet.quotable.iter().find(|line| hold.held["event"].as_str() == Some(line.event.as_str())).filter(|_| hold.words.is_none()) { + more.push_str(&format!("; their line is {} above", asked.id)); + } + if more.is_empty() { line } else { format!("{}{more}.", line.trim_end_matches('.')) } +} + /// Whether a line carries someone else's words (Q-E ruled rich-reply, `eureka-body:ruling:persona-pass-on-as-rich-reply`: she /// passes words on by replying to their line, and the echo refusal applies to her own words as before, with no flag to skip it): long enough to /// judge, and either nearly all a run of what she heard, or carrying nearly all of one line she heard that is itself @@ -814,11 +845,10 @@ 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(); - let holding = |named: &[String], into: &str| held_by(named, into, packet, &opening); - // Code's words gate (map 16.30.2, K45), before the act loops: what this decision holds, by its words. Naming a hold - // adds to it and never clears it. - let held = held_texts(&parsed, packet, &opening, &found); - let gate = |named: &[String], into: &str, text: &str| holding(named, into).or_else(|| repeats_held(text, into, &held)); + // 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 { let Some(draft) = line.draft.and_then(|n| found.numbered(n)) else { refusals.push(refused(Act::Say, None, line.draft, Refusal::NoDraft)); @@ -828,7 +858,7 @@ 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(&line.holds, into, &draft.text)); + 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) { @@ -872,7 +902,7 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na }; 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(&proposed.holds, into, &draft.text)); + 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) { @@ -943,6 +973,19 @@ pub(crate) fn decide_in(model: &dyn Model, request_id: &str, packet: &Packet, na gap["from"] = json!("acted"); } } + // What each hold has held (map 16.31.3, K51): every draft of the wake that neither went out as a line nor as an + // addition, whatever became of it, for every hold open or opening, whatever room the draft was written in. The commit + // writes it (`commit::carry_held`); no refusal reason and no fate keeps an unsent draft out of it. + let handles: Vec<&str> = packet.holds.iter().map(|hold| hold.id.as_str()).chain(opening.iter().map(|(line, _)| line.as_str())).fold(Vec::new(), |mut handles, handle| { + if !handles.contains(&handle) { + handles.push(handle); + } + handles + }); + let carry: Vec = handles.iter().flat_map(|handle| found.drafts.iter().filter(|draft| !said_drafts.contains(&draft.n) && !amended_drafts.contains(&draft.n)).map(move |draft| json!({ "hold": handle, "text": draft.text }))).collect(); + if !carry.is_empty() { + decision["carry"] = json!(carry); + } decision["amended"] = json!(amended); decision["suggestions"] = json!(suggestions); decision["room"] = json!(room); @@ -1194,67 +1237,116 @@ fn close_of(raw: &Value) -> Option { } /// A hold a draft names, resolved: its handle (the listed hold's id, `h1`, or the line this answer opens it from, `q3`), -/// as the refusal names it (`{who, id}`), and the room it covers (None for anywhere). An id that resolves to no hold +/// as the refusal names it (`{who, id}`), the room it covers (None for anywhere), and when it was made, in ms (the listed +/// hold's `made`, or the asker's line's time; None for an id that resolves to no hold). An id that resolves to no hold /// covers anywhere (fails closed, behind `hold_faults`), told by whose line it names. -fn hold_named(id: &str, packet: &Packet, opening: &[(String, Option)]) -> (Value, Option) { - if let Some(hold) = packet.holds.iter().find(|hold| hold.id == id) { - return (json!({ "who": hold.from_name, "id": id }), hold.room.clone()); - } - let who = packet.quotable.iter().find(|line| line.id == id).map(|line| line.who.as_str()); - let covers = opening.iter().find(|(line_id, _)| line_id == id).and_then(|(_, covers)| covers.clone()); - (json!({ "who": who, "id": id }), covers) -} - -/// The hold a draft going into `into` is held by (map 16.28.5), as the outcome tells it (who asked), when one is: 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 addition to code's words gate (`repeats_held`, K45): 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| id.trim()).find_map(|id| { - let (hold, covers) = hold_named(id, packet, opening); - covers.as_deref().is_none_or(|room| room == into).then_some(hold) - }) -} - -/// A text this decision holds (K45): its hold, as a refusal names it, the room it covers (None for anywhere), and the -/// text. -struct HeldText { +struct Named { hold: Value, covers: Option, + made: Option, +} + +fn hold_named(id: &str, packet: &Packet, opening: &[(String, Option)]) -> Named { + if let Some(hold) = packet.holds.iter().find(|hold| hold.id == id) { + return Named { hold: json!({ "who": hold.from_name, "id": id }), covers: hold.room.clone(), made: u64::try_from(hold.made.timestamp_millis()).ok() }; + } + let line = packet.quotable.iter().find(|line| line.id == id); + let opens = opening.iter().find(|(line_id, _)| line_id == id); + Named { hold: json!({ "who": line.map(|line| line.who.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 +/// 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)) +} + +/// Whether two texts are the same words, as `span::tokens` reads them. +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, + hold: Value, + made: Option, } -/// The held texts of one decision (map 16.30.2, K45), built before the act loops: the text of each say or amend whose -/// draft resolves and whose named `holds` hold it where it goes (`held_by`), and the `carries` of each open hold listed. -fn held_texts(answer: &Answer, packet: &Packet, opening: &[(String, Option)], found: &Drafts) -> Vec { - let mut held: Vec = Vec::new(); - let says = answer.say.iter().map(|line| (line.draft, &line.holds, packet.room.as_deref())); - let amends = answer.amend.iter().map(|amend| { +/// 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: +/// - 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. +/// +/// 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())); - (amend.draft, &amend.holds, target.map(|line| line.room.as_str()).or(packet.room.as_deref())) + Some((target.map(|line| line.room.clone()).or_else(|| packet.room.clone())?, numbered(amend.draft)?, &amend.holds)) }); - for (draft, named, into) in says.chain(amends) { - let (Some(draft), Some(into)) = (draft.and_then(|n| found.numbered(n)), into) else { continue }; - let covering = named.iter().map(|id| hold_named(id.trim(), packet, opening)).find(|(_, covers)| covers.as_deref().is_none_or(|room| room == into)); - if let Some((hold, covers)) = covering { - held.push(HeldText { hold, covers, text: draft.text.clone() }); + 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)); } } - for hold in &packet.holds { - for carried in &hold.carries { - held.push(HeldText { hold: json!({ "who": hold.from_name, "id": hold.id }), covers: hold.room.clone(), text: carried.clone() }); + 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(); + 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 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.iter().filter(|(draft, _)| !gated.contains_key(&(room.clone(), draft.n))) { + if 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 }); + } + } + } + // A held line joins what is held, so whatever repeats it is held too. + held.extend(caught); + at += 1; } } - held -} - -/// The hold whose held text a draft going into `into` repeats (K45): a held text whose hold covers `into`, said again -/// exactly, or by `echo`'s measure against it alone, so a short held line is held only when it is repeated exactly. -fn repeats_held(text: &str, into: &str, held: &[HeldText]) -> Option { - held.iter() - .find(|held| held.covers.as_deref().is_none_or(|room| room == into) && (text == held.text || echo(text, std::slice::from_ref(&held.text)))) - .map(|held| held.hold.clone()) + gated } /// The holds an answer names and does not open (map 16.29.3), a contract fault found before anything is decided: a `hold` diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index c7b70ed..e83957a 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -455,8 +455,8 @@ fn k20_a_line_replies_only_to_a_listed_line_and_the_echo_check_still_holds() { pub(crate) fn amendable_packet() -> Packet { let mut packet = packet(); packet.amendable = vec![ - Amendable { id: "a1".into(), event: "$ev-1".into(), room: MINDS.into(), text: "I'll send the file tonight.".into() }, - Amendable { id: "a2".into(), event: "$ev-2".into(), room: MINDS.into(), text: "Back soon.".into() }, + Amendable { id: "a1".into(), event: "$ev-1".into(), room: MINDS.into(), text: "I'll send the file tonight.".into(), at_ms: None }, + Amendable { id: "a2".into(), event: "$ev-2".into(), room: MINDS.into(), text: "Back soon.".into(), at_ms: None }, ]; packet } @@ -1589,11 +1589,14 @@ fn k37_x1_r1_held_draft_is_not_said() { assert!(told.iter().any(|line| line == "- Nothing of this reached #minds:gamecult.org: Meta asked him to hold it, and it was not sent."), "the asker's words are not in her outcome: {told:?}"); } +/// K51's cost (map 16.31.3): with Meta's hold opening, the welcome declined is held words, and the line saying it is +/// ready repeats its opening ("the draft is ready, and I'm holding it"), so it is held too. A ready line that shares no +/// run of the welcome's words goes out (`k51_a_line_sharing_no_trigram_goes_out`). #[test] -fn k37_x1_r1_a_line_saying_it_is_ready_still_goes() { +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), vec!["Meta, the draft is ready, and I'm holding it".to_owned()], "{decision}"); + assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["hold"]["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 @@ -1629,7 +1632,7 @@ fn k37_a_here_hold_covers_only_its_room() { let mut minds = x1_packet(); minds.holds = vec![hold(Some(MINDS))]; assert_eq!(said(&minds), 0); - minds.amendable = vec![Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Back soon.".into() }]; + minds.amendable = vec![Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Back soon.".into(), at_ms: None }]; let amend = answered(&minds, X1_LIBBY_R1, json!({ "say": [say_holding(2, json!([]))], "gaps": [], "amend": [{ "target": "a1", "draft": 1, "holds": ["h1"], "promises": [] }] })); assert_eq!((amend["amended"].as_array().map(Vec::len), amend["refused"][0]["reason"].as_str()), (Some(0), Some("held")), "{amend}"); } @@ -1922,14 +1925,6 @@ 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."; -/// Meta's #minds hold, listed as h1, carrying `carries`. -fn meta_hold_carrying(carries: &[&str]) -> crate::projection::select::Hold { - let (_, mut listed) = meta_hold(); - listed.carries = carries.iter().map(|text| (*text).to_owned()).collect(); - listed.held["carries"] = json!(carries); - listed -} - /// 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. #[test] @@ -1944,71 +1939,45 @@ fn k45_p1_identical_drafts_are_both_held() { assert_eq!((state["holds"][0]["carries"].clone(), applied.held_unrecorded.len()), (json!([K45_WELCOME]), 0), "{state}"); } -/// The X.1 turn-2 shape: Meta's hold carries the welcome, Kiko asks, and the answer says "Kiko, here it is: {welcome}" -/// naming no hold. It is refused `held`, for Meta. +/// The X.1 turn-2 shape, from turn 1's committed state: Meta's hold carries the welcome, Kiko asks, and the answer says +/// "Kiko, here it is: {welcome}" naming no hold. It is refused `held`, for Meta, and the commit carries it on the listed +/// hold too, once. #[test] fn k45_x1_next_turn_kiko_asks_and_the_welcome_stays_held() { - let mut packet = x1_packet(); - packet.holds = vec![meta_hold_carrying(&[K45_WELCOME])]; + 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(&packet, &prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] })); - assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str(), decision["refused"][0]["hold"].clone()), (Vec::::new(), Some("held"), json!({ "who": "Meta", "id": "h1" })), "{decision}"); - // The commit carries it on the listed hold too, once. - let (state, listed) = meta_hold(); - let mut started = state.clone(); - started["holds"][0]["carries"] = json!([K45_WELCOME]); - let mut decision = decision; - decision["holds"] = json!([{ "id": "h1", "entry": listed.entry, "held": started["holds"][0] }]); - let (after, applied) = crate::projection::commit::apply(&started, &json!({ "interpreter": decision, "posted": [], "edited": [] }), &prose, "r1-t2", now()); + 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}"); + 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}"); } -/// A `here` hold on #minds does not cover #swarm: the same line goes out there. +/// K51's uncovered room (K45's test, kept): a `here` hold on #minds does not cover #swarm, so the same line goes out there. #[test] fn k45_held_words_go_out_where_the_hold_does_not_cover() { - let mut packet = x1_packet(); - packet.holds = vec![meta_hold_carrying(&[K45_WELCOME])]; + let (_, mut packet) = held_then_kiko_asks(&[K45_WELCOME]); packet.room = Some("#swarm:gamecult.org".into()); let prose = format!("Kiko asked in #swarm. Kiko, here it is: {K45_WELCOME}"); assert_eq!(texts(&answered(&packet, &prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] }))), vec![format!("Kiko, here it is: {K45_WELCOME}")]); } -/// After Meta lets it go, the hold is released, the next packet lists no hold, and the line is said. -#[test] -fn k45_released_hold_holds_nothing() { - let (mut state, listed) = meta_hold(); - state["holds"][0]["carries"] = json!([K45_WELCOME]); - let mut released = json!({ "said": [], "amended": [], "refused": [], "promises": [], "holds": [{ "id": "h1", "entry": listed.entry, "held": state["holds"][0] }], "lines": [{ "id": "q9", "event": "$q9", "room": MINDS, "who": "Meta", "sender": "@meta:gamecult.org", "at_ms": u64::try_from(now().timestamp_millis()).unwrap(), "text": "Go ahead and post it, Libby." }] }); - released["state"] = json!([{ "kind": "hold_release", "hold": "h1", "evidence": { "heard": "q9" } }]); - let (after, applied) = crate::projection::commit::apply(&state, &json!({ "interpreter": released, "posted": [], "edited": [] }), "x", "r1-t3", now()); - assert_eq!((after["holds"][0]["status"].as_str(), applied.unheld.len()), (Some("released"), 1), "{applied:?}"); - let mut next = heimdall(); - next["holds"] = after["holds"].clone(); - let room = Room { messages: vec![line(MINDS, KIKO, "Kiko", "Libby, what did you end up writing for the newcomers?", true)], here: Some(MINDS.into()), ..Room::default() }; - let packet = packet_in(TurnKind::Chat, &next, &room, 1); - assert!(packet.holds.is_empty(), "{:?}", packet.holds); - let prose = format!("Kiko asked what I wrote. Kiko, here it is: {K45_WELCOME}"); - assert_eq!(texts(&answered(&packet, &prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] }))), vec![format!("Kiko, here it is: {K45_WELCOME}")]); -} - -/// A short line about a held text is below `echo`'s bar, and is said beside it. +/// A short line about a held text shares no run of its words, and is said beside it. #[test] fn k45_a_short_mention_is_not_held() { - let mut packet = x1_packet(); - packet.holds = vec![meta_hold_carrying(&[K45_WELCOME])]; + let (_, packet) = held_then_kiko_asks(&[K45_WELCOME]); let prose = "I wonder about the second line. Should the second line say poke around?"; assert_eq!(texts(&answered(&packet, prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] }))), vec!["Should the second line say poke around?".to_owned()]); // Negative: a short held text repeated exactly is held. - packet.holds = vec![meta_hold_carrying(&["Should the second line say poke around?"])]; + let (_, packet) = held_then_kiko_asks(&["Should the second line say poke around?"]); assert_eq!(answered(&packet, prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] }))["refused"][0]["reason"].as_str(), Some("held")); } /// An addition that repeats a held text into the room its hold covers is held, naming no hold. #[test] fn k45_amend_repeating_held_words_is_held() { - let mut packet = x1_packet(); - packet.holds = vec![meta_hold_carrying(&[K45_WELCOME])]; - packet.amendable = vec![Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Back soon.".into() }]; + let (_, mut packet) = held_then_kiko_asks(&[K45_WELCOME]); + 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}"); @@ -2022,15 +1991,20 @@ fn k45_x1_r1_the_ready_line_repeats_the_held_draft_and_is_held() { let decision = x1_r1(json!([say_holding(1, json!(["q3"])), say_holding(2, json!([]))]), meta_holds_here()); let drafts: Vec<(Option, Option<&str>)> = decision["refused"].as_array().unwrap().iter().map(|refused| (refused["draft"].as_u64(), refused["reason"].as_str())).collect(); assert_eq!((texts(&decision), drafts), (Vec::::new(), vec![(Some(1), Some("held")), (Some(2), Some("held"))]), "{decision}"); - // Negative: with draft 1 declined rather than held, the ready line goes (`k37_x1_r1_a_line_saying_it_is_ready_still_goes`). } -/// A `Held` refusal whose handle no open hold answers carries nothing, and is reported. +/// A draft naming a hold that nothing opens is held this turn (K44), and with no hold open or opening nothing is carried. +/// A `carry` entry whose handle no open hold answers carries nothing, and is reported (K45, K51). #[test] fn k45_a_held_refusal_no_hold_answers_is_reported() { let decision = answered(&x1_packet(), X1_LIBBY_R1, json!({ "say": [say_holding(1, json!(["h9"])), say_holding(2, json!([]))], "gaps": [], "hold": [] })); + assert_eq!((decision["refused"][0]["reason"].as_str(), decision.get("carry")), (Some("held"), None), "{decision}"); let (state, applied) = committed(&decision, X1_LIBBY_R1); - assert_eq!((state.get("holds"), applied.held_unrecorded.len()), (None, 2), "{applied:?}"); + assert_eq!((state.get("holds"), applied.held_unrecorded.len()), (None, 0), "{applied:?}"); + let mut stray = decision.clone(); + stray["carry"] = json!([{ "hold": "h9", "text": "Lost." }]); + let (state, applied) = committed(&stray, X1_LIBBY_R1); + assert_eq!((state.get("holds"), applied.held_unrecorded.len()), (None, 1), "{applied:?}"); } // --------------------------------------------------------------------------------------------- @@ -2251,3 +2225,242 @@ fn k52_one_fold_one_word_split() { } } } + +/// The state's carries of its first hold. +fn carries_of(state: &Value) -> Vec { + state["holds"][0]["carries"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect() +} + +/// Turn 2 says "Kiko, here it is: {text}" in #minds, naming no hold: the decision. +fn kiko_gets(p2: &Packet, text: &str) -> Value { + answered(p2, &format!("Kiko asked what I wrote. Kiko, here it is: {text}"), json!({ "say": [say_holding(1, json!([]))], "gaps": [] })) +} + +/// 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")) +} + +/// 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 +/// nothing names the hold. Turn 1's committed state carries it all the same, and at turn 2 "Kiko, here it is: {welcome}", +/// naming no hold, is refused `held`, for Meta, and nothing is said. +#[test] +fn k51_soul_a_a_declined_welcome_is_carried_and_held_next_turn() { + let answer = json!({ "say": [say_holding(2, json!([]))], "gaps": [], "hold": meta_holds_here(), "unsent": [{ "draft": 1, "how": "declined", "quote": "I'll say plainly it's held" }] }); + let decision = answered(&x1_packet(), X1_LIBBY_R1, answer); + assert!(decision.get("failed").is_none() && decision.get("undecided").is_none(), "{decision}"); + let (state, _) = committed(&decision, X1_LIBBY_R1); + assert_eq!(state["holds"][0]["status"].as_str(), Some("open"), "{state}"); + assert!(carries_of(&state).contains(&x1_libby_r1_draft_1()), "{state}"); + let d2 = kiko_gets(&kiko_asks(&state["holds"]), &x1_libby_r1_draft_1()); + assert!(held_for_meta(&d2), "{d2}"); +} + +/// Soul's `soul_b` and `soul_b2`, inverted: a draft that names the hold but is refused `NotQuotable` first is carried +/// all the same, and its repeat next turn is held. +#[test] +fn k51_soul_b_refused_not_quotable_first_is_still_carried() { + let mut first = say_holding(1, json!(["q3"])); + first["in_reply_to"] = json!("q99"); + let decision = answered(&x1_packet(), X1_LIBBY_R1, json!({ "say": [first.clone(), say_holding(2, json!(["q3"]))], "gaps": [], "hold": meta_holds_here() })); + assert_eq!(decision["refused"][0]["reason"].as_str(), Some("not_quotable"), "{decision}"); + let (state, _) = committed(&decision, X1_LIBBY_R1); + assert!(carries_of(&state).contains(&x1_libby_r1_draft_1()), "{state}"); + assert!(held_for_meta(&kiko_gets(&kiko_asks(&state["holds"]), &x1_libby_r1_draft_1()))); + // B2: her only draft, naming the hold, refused `NotQuotable`. + let prose = format!("Meta asked me to hold it. {K45_WELCOME}"); + let decision = answered(&x1_packet(), &prose, json!({ "say": [first], "gaps": [], "hold": meta_holds_here() })); + assert_eq!(decision["refused"][0]["reason"].as_str(), Some("not_quotable"), "{decision}"); + let (state, _) = committed(&decision, &prose); + assert_eq!(carries_of(&state), [K45_WELCOME], "{state}"); + let p2 = kiko_asks(&state["holds"]); + let d2 = answered(&p2, &format!("Kiko asked. {K45_WELCOME}"), json!({ "say": [say_holding(1, json!([]))], "gaps": [] })); + assert!(held_for_meta(&d2), "{d2}"); +} + +/// One row per fate of an unsent draft: superseded, undecided, an addressee gap, `Echo`, `Duplicate`, `NoRoom`, a note +/// to Self only, never mentioned, declined and `NotQuotable`. Each draft is carried, and at turn 2 its repeat into the +/// covered room is held. (`Used` has no row: a draft refused `Used` went out by another act this turn, so it is no unsent +/// draft.) +#[test] +fn k51_every_fate_is_carried() { + const TAIL: &str = "Actually I would rather put that differently later on."; + let prose = |text: &str| format!("Meta asked me to hold it. {text} {TAIL}"); + let with_hold = |answer: Value| { + let mut answer = answer; + answer["hold"] = meta_holds_here(); + answer + }; + let mut no_room = x1_packet(); + no_room.room = None; + let mut reply = say_holding(1, json!([])); + reply["in_reply_to"] = json!("q99"); + let rows: Vec<(&str, Packet, String, Value)> = vec![ + ("superseded", x1_packet(), prose(K45_WELCOME), json!({ "say": [], "gaps": [], "unsent": [{ "draft": 1, "how": "superseded", "quote": "I would rather put that differently" }] })), + ("undecided", x1_packet(), prose(K45_WELCOME), json!({ "say": [], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "nothing like this was ever thought" }] })), + ("addressee", x1_packet(), prose(K45_WELCOME), json!({ "say": [], "gaps": [{ "kind": "addressee", "draft": 1, "quote": null, "detail": "" }] })), + ("echo", x1_packet(), prose(X1_META_R1), json!({ "say": [say_holding(1, json!([]))], "gaps": [] })), + ("duplicate", x1_packet(), format!("Meta asked me to hold it. {K45_WELCOME} {K45_WELCOME}"), json!({ "say": [say_holding(1, json!([])), say_holding(2, json!([]))], "gaps": [] })), + ("no_room", no_room, prose(K45_WELCOME), json!({ "say": [say_holding(1, json!([]))], "gaps": [] })), + ("note", x1_packet(), prose(K45_WELCOME), json!({ "say": [], "gaps": [], "suggest": [{ "kind": "idea", "draft": 1, "about": null, "private": false }] })), + ("never mentioned", x1_packet(), prose(K45_WELCOME), json!({ "say": [], "gaps": [] })), + ("declined", x1_packet(), prose(K45_WELCOME), json!({ "say": [], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "Meta asked me to hold it" }] })), + ("not_quotable", x1_packet(), prose(K45_WELCOME), json!({ "say": [reply], "gaps": [] })), + ]; + for (fate, packet, prose, answer) in rows { + let decision = answered(&packet, &prose, with_hold(answer)); + assert!(decision.get("failed").is_none(), "{fate}: {decision}"); + let text = drafts(&prose).drafts.last().map(|draft| draft.text.clone()).unwrap(); + let (state, _) = committed(&decision, &prose); + assert!(carries_of(&state).contains(&text), "{fate}: {state}"); + let d2 = kiko_gets(&kiko_asks(&state["holds"]), &text); + assert!(held_for_meta(&d2), "{fate}: {d2}"); + } +} + +/// Soul's `soul_d`, inverted: the carried welcome split into two lines of seven words each, in one turn, naming no hold. +/// Each half is under `ECHO_MIN_WORDS`, but together they enter the room, so both are refused `held`. +#[test] +fn k51_soul_d_a_split_welcome_is_held_whole() { + let (_, p2) = held_then_kiko_asks(&[K45_WELCOME]); + let prose = "Kiko asked. Hello, and welcome, we're glad you're here. Poke at whatever you're curious about first."; + let d = answered(&p2, prose, json!({ "say": [say_holding(1, json!([])), say_holding(2, json!([]))], "gaps": [] })); + let reasons: Vec> = d["refused"].as_array().unwrap().iter().map(|refused| refused["reason"].as_str()).collect(); + assert_eq!((texts(&d), reasons), (Vec::::new(), vec![Some("held"); 2]), "{d}"); +} + +/// A split across two wakes: the first half went out last turn, after the hold was made (`amendable`), and the second +/// half is held this turn. Negative: a line of hers from before the hold does not count toward the measure. +#[test] +fn k51_a_split_across_two_wakes_is_held() { + 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: u64| Amendable { id: "a1".into(), event: "$a1".into(), room: MINDS.into(), text: "Hello, and welcome, we're glad you're here.".into(), at_ms: Some(at_ms) }; + let prose = "Kiko asked. Poke at whatever you're curious about first."; + p2.amendable = vec![half(made + 1000)]; + let d = answered(&p2, prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] })); + assert!(held_for_meta(&d), "{d}"); + p2.amendable = vec![half(made - 1000)]; + assert_eq!(texts(&answered(&p2, prose, json!({ "say": [say_holding(1, json!([]))], "gaps": [] }))), ["Poke at whatever you're curious about first."]); +} + +/// Soul's `soul_g`, inverted: the Interpreter sees what a hold carries, and a hold the record could not quote whose line is +/// listed names that line's id. The asker's words are not copied into the hold. +#[test] +fn k51_soul_g_the_interpreter_sees_what_a_hold_carries() { + // Golden: a quoted hold, with what she has held. + let (_, p2) = held_then_kiko_asks(&[K45_WELCOME]); + let hold = &p2.holds[0]; + let prompt = speech_prompt(&p2, "x", "hi", &Tuning::default()); + let golden = format!( + "Holds:\n- h1 \u{2014} held for {who}, asked {at} in #minds:gamecult.org: \"hold it, don't post it in here yet\". Not to go in #minds:gamecult.org until {who} lets it go; he has held for them: {welcome}.\n", + who = hold.from_name, + at = hold.made.format("%Y-%m-%d %H:%M UTC"), + welcome = spoken(K45_WELCOME), + ); + assert!(prompt.contains(&golden), "{golden}\n{prompt}"); + // A hold the retry could not quote, opened from Meta's line, which is listed again at turn 2. + let prose = format!("Meta asked me to hold it. {K45_WELCOME}"); + let unquoted = json!({ "say": [say_holding(1, json!(["q3"]))], "gaps": [], "hold": [{ "line": "q3", "words": "please keep it back", "where": "here" }] }); + let decision = answered(&x1_packet(), &prose, unquoted); + let (state, _) = committed(&decision, &prose); + assert_eq!((state["holds"][0]["words"].clone(), carries_of(&state)), (Value::Null, vec![K45_WELCOME.to_owned()]), "{state}"); + 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, line(MINDS, KIKO, "Kiko", "Libby, what did you end up writing for the newcomers?", true)], here: Some(MINDS.into()), ..Room::default() }; + let p2 = packet_in(TurnKind::Chat, &next, &room, 1); + let asked = p2.quotable.iter().find(|line| line.event == "$q3").map(|line| line.id.clone()).unwrap_or_else(|| panic!("{:?}", 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("the record could not quote what") && listed.contains("Poke at whatever") && listed.ends_with(&format!("; their line is {asked} above.")), "{listed}"); + 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`. +#[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 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:?}"); +} + +/// Negative: with no hold open or opening, nothing is carried. +#[test] +fn k51_nothing_is_carried_without_a_hold() { + let prose = "I'll keep this back for now and think it over. Nibu, the tag looks fine to me."; + let decision = answered(&packet(), prose, json!({ "say": [], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "I'll keep this back for now" }] })); + assert_eq!(decision.get("carry"), None, "{decision}"); + let (state, _) = committed(&decision, prose); + assert_eq!(state.get("holds"), None, "{state}"); +} + +/// Negative: a line sharing no run of three words with a held welcome goes out, beside it in the same turn and after it +/// next turn. +#[test] +fn k51_a_line_sharing_no_trigram_goes_out() { + let ready = "Meta, they're ready, holding them."; + let prose = format!("Meta asked me to hold it. {K45_WELCOME} {ready}"); + let decision = answered(&x1_packet(), &prose, json!({ "say": [say_holding(1, json!(["q3"])), say_holding(2, json!([]))], "gaps": [], "hold": meta_holds_here() })); + assert_eq!((texts(&decision), decision["refused"][0]["reason"].as_str()), (vec![ready.to_owned()], Some("held")), "{decision}"); + let (_, p2) = held_then_kiko_asks(&[K45_WELCOME]); + assert_eq!(texts(&answered(&p2, &format!("Meta asked. {ready}"), json!({ "say": [say_holding(1, json!([]))], "gaps": [] }))), [ready]); +} + +/// Negative: once Meta lets the hold go, the turn that releases it carries nothing more onto it, and the next turn's +/// packet lists no hold, so the welcome is said. +#[test] +fn k51_released_hold_carries_nothing() { + let (state, _) = held_then_kiko_asks(&[K45_WELCOME]); + let mut next = heimdall(); + next["holds"] = state["holds"].clone(); + let room = Room { messages: vec![line(MINDS, "@meta:gamecult.org", "Meta", "Go ahead and post it, Libby.", true)], here: Some(MINDS.into()), ..Room::default() }; + let p2 = packet_in(TurnKind::Chat, &next, &room, 1); + let go = p2.quotable[0].id.clone(); + let prose = "Meta let it go, and I wait to post it. Thanks, Meta, posting it next."; + let release = answered(&p2, prose, json!({ "say": [], "gaps": [], "hold_released": [{ "hold": "h1", "line": go }], "unsent": [{ "draft": 1, "how": "declined", "quote": "I wait to post it" }] })); + let (after, applied) = crate::projection::commit::apply(&state, &json!({ "interpreter": release, "posted": [], "edited": [] }), prose, "r1-t3", now()); + assert_eq!((after["holds"][0]["status"].as_str(), carries_of(&after), applied.unheld.len()), (Some("released"), vec![K45_WELCOME.to_owned()], 1), "{applied:?}"); + let p3 = kiko_asks(&after["holds"]); + assert!(p3.holds.is_empty(), "{:?}", p3.holds); + assert_eq!(texts(&kiko_gets(&p3, K45_WELCOME)), [format!("Kiko, here it is: {K45_WELCOME}")]); +} + +/// The named limit: a held text under `ECHO_MIN_WORDS` split across two lines goes out; repeated whole, it is held. +#[test] +fn k51_a_short_held_text_split_goes_out() { + let (_, p2) = held_then_kiko_asks(&["Say hello and poke around."]); + let split = "Kiko asked. Say hello. And poke around."; + assert_eq!(texts(&answered(&p2, split, json!({ "say": [say_holding(1, json!([])), say_holding(2, json!([]))], "gaps": [] }))).len(), 2); + let whole = "Kiko asked. Say hello and poke around!"; + assert_eq!(answered(&p2, whole, json!({ "say": [say_holding(1, json!([]))], "gaps": [] }))["refused"][0]["reason"].as_str(), Some("held")); +} + +/// K51's cost, pinned: with a `here` hold open in the room, draft 1 is superseded by draft 2, a near copy, about something +/// else, and draft 2 is held: while a hold is open every draft she does not send is held words. +#[test] +fn k51_a_revision_beside_a_superseded_draft_is_held_under_an_open_hold() { + let (_, p2) = held_then_kiko_asks(&[K45_WELCOME]); + let first = "Kiko, the newcomers get a short hello, a pointer to the forge, and an invitation to ask anything at all."; + let second = "Kiko, the newcomers get a brief hello, a pointer to the forge, and an invitation to ask anything at all."; + let prose = format!("Kiko asked. {first} No, better to say it another way. {second}"); + let d = answered(&p2, &prose, json!({ "say": [say_holding(2, json!([]))], "gaps": [], "unsent": [{ "draft": 1, "how": "superseded", "quote": "better to say it another way" }] })); + assert!(held_for_meta(&d), "{d}"); + assert_eq!(d["refused"][0]["draft"].as_u64(), Some(2), "{d}"); +} diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 5d21292..1c39fc5 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -180,6 +180,9 @@ pub(crate) struct Posted { pub event: String, pub room: String, pub text: String, + /// When it went out, in ms: the receipt's own time, else the decision's (`at_ms`); none when the record has neither. + /// What a hold measures her listed lines against (K51). + pub at_ms: Option, } /// Her words as she is shown them: a draft she wrote, or a passage of her thought; or, for a draft refused as an echo, @@ -329,7 +332,8 @@ pub(crate) fn outcome_of(record: &Value) -> Option { outcome.omitted.push(format!("a receipt without its event, room or text: {receipt}")); continue; }; - receipts.push(Posted { event, room, text }); + let at_ms = receipt["at_ms"].as_u64().or_else(|| decision["at_ms"].as_u64()); + receipts.push(Posted { event, room, text, at_ms }); } for line in decision["said"].as_array().into_iter().flatten() { let went = receipts.iter().any(|posted| Some(posted.room.as_str()) == line["room"].as_str() && Some(posted.text.as_str()) == line["text"].as_str()); diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index dbf4ff1..11df848 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -367,6 +367,9 @@ pub(crate) struct Amendable { pub event: String, pub room: String, pub text: String, + /// When it went out, in ms, when the record says (`Posted.at_ms`): a hold's words gate counts it only when it is + /// later than the hold (K51), and counts it when the time is unknown. + pub at_ms: Option, } /// A line of someone else's she may reply to (K20): one this packet shows her, in the turn's room. The Interpreter cites it @@ -423,7 +426,7 @@ pub(crate) struct Hold { pub made: DateTime, /// The asker's words naming what is held and where; none when the record could not quote them (K47). pub words: Option, - /// Her own drafts code refused `Held` for this hold (map 16.30.2, K45), oldest first: what code's words gate holds. + /// Her own drafts she did not send while it was open (map 16.31.3, K51), oldest first: what code's words gate holds. pub carries: Vec, pub held: Value, } @@ -2331,7 +2334,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { .flat_map(|last| &last.posted) .filter(|posted| Some(posted.room.as_str()) == here) .enumerate() - .map(|(at, posted)| Amendable { id: format!("a{}", at + 1), event: posted.event.clone(), room: posted.room.clone(), text: posted.text.clone() }) + .map(|(at, posted)| Amendable { id: format!("a{}", at + 1), event: posted.event.clone(), room: posted.room.clone(), text: posted.text.clone(), at_ms: posted.at_ms }) .collect(); let selected = taken.into_iter().map(|candidate| Pick { id: candidate.id, pool: candidate.pool, log_score: candidate.log_score }).collect(); // Her view (map 16.23.1, 16.29.10): what came of her last turn, then her promises, then her domain; the room follows diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index f19d53f..7e7c203 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -2079,7 +2079,7 @@ fn what_she_may_add_to_is_her_last_turns_lines_in_this_room_only() { { "event": "ev-there", "room": "#elsewhere:gamecult.org", "text": "Elsewhere line." }, ] }); let packet = packet_of(TurnKind::Chat, &state(), &chat_room(), &with_last(&record), 1); - let amendable = |id: &str, event: &str, text: &str| super::select::Amendable { id: id.into(), event: event.into(), room: "#swarm:gamecult.org".into(), text: text.into() }; + let amendable = |id: &str, event: &str, text: &str| super::select::Amendable { id: id.into(), event: event.into(), room: "#swarm:gamecult.org".into(), text: text.into(), at_ms: None }; assert_eq!(packet.amendable, [amendable("a1", "ev-here", "I'll send it.")]); assert!(!narrate::projector_prompt(&packet, &Tuning::default()).contains("- a1 "), "the Projector never sees the ids"); assert_eq!(packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1).amendable, []); diff --git a/crates/mind-body/src/projection/tuning.rs b/crates/mind-body/src/projection/tuning.rs index dfe99b0..6678241 100644 --- a/crates/mind-body/src/projection/tuning.rs +++ b/crates/mind-body/src/projection/tuning.rs @@ -146,6 +146,9 @@ pub struct SelectTuning { /// What she has said and read in this conversation, in her view, in bytes, heading included (map 16.24.1): past it the /// window shrinks from its old end. pub exchange_bytes: usize, + /// What one hold has held, in the Interpreter's list of holds, in bytes (map 16.31.3, K51): her carried drafts, oldest + /// first, while they fit; the rest are counted. + pub hold_bytes: usize, pub stimulus_bytes: usize, /// What was said to her, verbatim, for the Persona stage: on a chat turn, the room's earlier lines too, before the new /// ones (map 16.20.3). @@ -251,6 +254,7 @@ impl Default for SelectTuning { promises_bytes: 2000, domain_bytes: 4000, exchange_bytes: 3000, + hold_bytes: 1600, stimulus_bytes: 1500, heard_bytes: 2500, addressed_bytes: 8 * 1024, @@ -336,6 +340,7 @@ impl Tuning { ("select.promises_bytes", select.promises_bytes), ("select.domain_bytes", select.domain_bytes), ("select.exchange_bytes", select.exchange_bytes), + ("select.hold_bytes", select.hold_bytes), ("select.stimulus_bytes", select.stimulus_bytes), ("select.heard_bytes", select.heard_bytes), ("select.identity_bytes", select.identity_bytes), diff --git a/schemas/cultnet/gamecult.persona_state.v0.schema.json b/schemas/cultnet/gamecult.persona_state.v0.schema.json index 4a5a320..3e846cb 100644 --- a/schemas/cultnet/gamecult.persona_state.v0.schema.json +++ b/schemas/cultnet/gamecult.persona_state.v0.schema.json @@ -1098,7 +1098,7 @@ }, "hold": { "type": "object", - "description": "One hold. from: the asker's Matrix id. room: the room it covers, null for anywhere. event: the asker's line. words: the asker's words naming what is held and where, copied from that line, or null when they could not be quoted; the hold holds all the same. carries: her own drafts her turn's commit refused as held for this hold, at most four, oldest first; a draft into a place the hold covers that repeats one is not sent. releasedBy: the act that released it, heard (the asker's line, by event).", + "description": "One hold. from: the asker's Matrix id. room: the room it covers, null for anywhere. event: the asker's line. words: the asker's words naming what is held and where, copied from that line, or null when they could not be quoted; the hold holds all the same. carries: her own drafts she did not send while this hold was open, oldest first, written by her turn's commit; past 9600 bytes in all nothing new is carried; a draft into a place the hold covers that repeats one is not sent. releasedBy: the act that released it, heard (the asker's line, by event).", "additionalProperties": false, "properties": { "id": { @@ -1129,7 +1129,6 @@ }, "carries": { "type": "array", - "maxItems": 4, "items": { "type": "string", "minLength": 1