From 5b96a577b1dc687eb69dfed3afdb2bca040963f7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 22 Nov 2026 11:44:54 +0100 Subject: [PATCH] Persona K53: the Projector names a person through Who Map 16.31.5, option (i). select::who_of(sender, names) is the one constructor of Who: her own name for her, the bond's label for someone she is bound to, anyone else's display name cut to at most 3 words and 32 bytes (quoted and escaped), or "someone she does not know"; never a Matrix id. Every Projector input that names a person takes a Who: People (bond lines and the arrival on them), Here (also-here, pronouns, the conversation and its speaking cues), a beat's contacts, the lens, and the outcome. name_of keeps its display-name-and-id arm for the Persona's room, the Interpreter's lists and Quotable.who only. The record gains ids beside names: a Held refusal's hold carries by_id, a commit close carries by_id; promises and holds already list to and from. Outcome name slots become Person { told, event: Who }, built once in outcome_of from those ids, which now takes the Names it builds Who from; Form::person is the only reader. Tests: soul_f inverted over every Projector input (chat, beat, the lens over seeds, every outcome person slot); every Part names by Who; a bonded person by her bond; the commit copies no heard line into her state's free text. Golden group-state files and the public surface move with it. Co-Authored-By: Claude Opus 5.5 --- .../fixtures/harness/golden-chorus.txt | 12 +- .../fixtures/harness/golden-group.txt | 6 +- crates/mind-body/src/projection.rs | 10 +- crates/mind-body/src/projection/commit.rs | 8 +- .../mind-body/src/projection/commit/tests.rs | 2 + .../mind-body/src/projection/harness/tests.rs | 10 +- crates/mind-body/src/projection/interpret.rs | 4 +- .../src/projection/interpret/tests.rs | 169 +++++++++++++++--- crates/mind-body/src/projection/outcome.rs | 87 ++++++--- .../mind-body/src/projection/outcome/tests.rs | 100 ++++++++--- crates/mind-body/src/projection/select.rs | 152 ++++++++++++---- crates/mind-body/src/projection/tests.rs | 30 ++-- crates/mind-body/tests/public_surface.txt | 3 + 13 files changed, 444 insertions(+), 149 deletions(-) diff --git a/crates/mind-body/fixtures/harness/golden-chorus.txt b/crates/mind-body/fixtures/harness/golden-chorus.txt index 1bfb8b3..18400b9 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" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org) 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" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); 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" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org) 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" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org) 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" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org); "nibu" (@nibu:gamecult.org) 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" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org); "nibu" (@nibu:gamecult.org); "aqua" (@aqua:gamecult.org) 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"; "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. diff --git a/crates/mind-body/fixtures/harness/golden-group.txt b/crates/mind-body/fixtures/harness/golden-group.txt index 3bbf905..a57e549 100644 --- a/crates/mind-body/fixtures/harness/golden-group.txt +++ b/crates/mind-body/fixtures/harness/golden-group.txt @@ -1,4 +1,4 @@ -quiet-beat.toml: - the conversation: @libby:gamecult.org has been talking to the room; Kiko has been talking to the room. | The last 3 lines are the Minds' alone. +quiet-beat.toml: - the conversation: Someone he does not know has been talking to the room; Kiko has been talking to the room. | The last 3 lines are the Minds' alone. operator-warm.toml: - the conversation: Meta, who runs the place has been talking with him. | Meta, who runs the place is waiting on him. Meta, who runs the place last spoke just now. -mind-teases.toml: - the conversation: Kiko has been talking with him; he has been talking to the room; @aqua:gamecult.org has been talking to the room. | The last 3 lines are the Minds' alone. -deru-passing.toml: - the conversation: @weksa:gamecult.org has been talking to the room; Deru has been talking to the room. | Deru last spoke just now. +mind-teases.toml: - the conversation: Kiko has been talking with him; he has been talking to the room; someone he does not know has been talking to the room. | The last 3 lines are the Minds' alone. +deru-passing.toml: - the conversation: Someone he does not know has been talking to the room; Deru has been talking to the room. | Deru last spoke just now. diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index bee49de..2734f78 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -51,7 +51,7 @@ pub use select::TurnKind; pub use tuning::{TUNING_FILE, TUNING_ROOT}; use narrate::{cap_prose, cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words}; -use select::{History, Inputs, Packet, People, Replied, Room, RoomLine, select, turn_room}; +use select::{History, Inputs, Names, Packet, People, Replied, Room, RoomLine, select, turn_room}; /// The agent name on the connector's request ids. const AGENT: &str = "mind-persona"; @@ -557,10 +557,12 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime) -> Result Some(chat) => read_room(chat, request, &own), None => (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": "no mouth is configured" })), }; - // Freshness, her own recent words and what came of her last turn come from trace v2, which the commit writes (C3c); - // until then only what the caller carried from earlier turns of its own. - let history = History { recent: request.recent.clone(), last: request.last_outcome.as_ref().and_then(outcome::outcome_of), ..History::default() }; let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender }; + // Freshness, her own recent words and what came of her last turn come from trace v2, which the commit writes (C3c); + // until then only what the caller carried from earlier turns of its own. Whom her last turn's outcome names is named + // to the Projector from her bonds and this room's lines (K53). + let naming = Names { state: &state, people, room: &room }; + let history = History { recent: request.recent.clone(), last: request.last_outcome.as_ref().and_then(|record| outcome::outcome_of(record, &naming)), ..History::default() }; let names = domain::Names::of(&state, &people, &request.instance); let (digest, domain_report) = read_domain(organs.domain, request.last_wake, now, &names); let inputs = Inputs { kind: request.kind, state: &state, room: &room, history: &history, observation: None, people, now, seed: request.seed, affordances: &[], domain: digest.as_ref(), exchange: None }; diff --git a/crates/mind-body/src/projection/commit.rs b/crates/mind-body/src/projection/commit.rs index d8ed78b..97d26b7 100644 --- a/crates/mind-body/src/projection/commit.rs +++ b/crates/mind-body/src/projection/commit.rs @@ -689,12 +689,12 @@ fn apply_promise(state: &mut Value, started: &Value, proposal: &Proposal, resolv Ok(_) => {} } } - let (act, event, words, who) = match (how, resolved) { + let (act, event, words, who, by_id) = match (how, resolved) { (How::Kept | How::Withdrawn, Resolved::Sent { act, event, text, room, mentions }) => { if !reaches(entry, &room, &mentions, record) { return Err(Refusal::NotWherePromised); } - (act, json!(event), json!(text), Value::Null) + (act, json!(event), json!(text), Value::Null, Value::Null) } (How::Released, Resolved::Heard { event, sender, room, at_ms, who, .. }) => { let by_promisee = match entry["to"].as_str() { @@ -709,7 +709,7 @@ fn apply_promise(state: &mut Value, started: &Value, proposal: &Proposal, resolv return Err(Refusal::ReleaseBeforePromise); } // The person's words are not copied into her state: the event points to them. - ("released", json!(event), Value::Null, json!(who)) + ("released", json!(event), Value::Null, json!(who), json!(sender)) } _ => return Err(Refusal::EvidenceNotAccepted), }; @@ -720,7 +720,7 @@ fn apply_promise(state: &mut Value, started: &Value, proposal: &Proposal, resolv }); entry["closedAt"] = json!(now.to_rfc3339()); entry["closedBy"] = json!({ "act": act, "event": event, "words": words }); - applied.closed.push(json!({ "entry": entry.clone(), "how": how, "to_name": listed["to_name"], "by": who })); + applied.closed.push(json!({ "entry": entry.clone(), "how": how, "to_name": listed["to_name"], "by": who, "by_id": by_id })); Ok(()) } (Proposal::PromiseOpen { .. } | Proposal::HoldOpen { .. } | Proposal::HoldRelease { .. }, _) => Err(Refusal::EvidenceNotAccepted), diff --git a/crates/mind-body/src/projection/commit/tests.rs b/crates/mind-body/src/projection/commit/tests.rs index 8c2b1a8..57f623a 100644 --- a/crates/mind-body/src/projection/commit/tests.rs +++ b/crates/mind-body/src/projection/commit/tests.rs @@ -106,6 +106,8 @@ fn a_blocked_promise_is_not_hers_to_keep_and_can_be_released() { let entry = &state["commitments"][0]; assert_eq!((entry["status"].as_str(), entry["closedBy"].clone()), (Some("released"), json!({ "act": "released", "event": "$m", "words": null })), "the person's words are not copied: {applied:?}"); assert_eq!((applied.closed[0]["by"].as_str(), applied.closed[0]["to_name"].as_str()), (Some("Meta"), Some("Meta"))); + // K53: the record carries who let her off by id beside the name, so the Projector can be told who without the name. + assert_eq!(applied.closed[0]["by_id"], entry["to"], "{applied:?}"); } #[test] diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index c07830a..5ef0bf9 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -446,7 +446,7 @@ fn k24_her_wake_reads_by_intent_from_a_fixture_and_stops_at_the_cap() { assert!(report["packet"]["affordances"].as_array().unwrap().contains(&json!("read"))); // Her next packet opens with what she read, without its content. let record = json!({ "interpreter": decision, "posted": [] }); - let told = crate::projection::outcome::outcome_of(&record).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); assert!(told.contains(&"- He read GameCult/Lodur#12 on the forge.".to_owned()) && !told.join(" ").contains("in front of him now"), "{told:?}"); assert!(told.iter().any(|line| line == "- He reached for http://example.org/private and could not read it: it is private."), "{told:?}"); @@ -513,7 +513,7 @@ fn k24_the_reply_after_a_read_gets_her_whole_budget_and_a_runaway_draft_is_cut_b assert_eq!(persona["words"].as_u64(), Some(words as u64), "her first segment whole; the runaway draft is not in her stream: {persona}"); assert!(!persona["prose"].as_str().unwrap().contains(""), "no unclosed draft in her stream: {persona}"); assert!(decision["cut_by_cap"][0].as_str().is_some_and(|text| text.starts_with("Deru, I opened it")), "{decision}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); assert!(told.iter().any(|line| line.contains("finished writing")), "she is told: {told:?}"); } @@ -549,7 +549,7 @@ reads_per_wake = 1 let mut decision = report["renders"][0]["interpreter"].clone(); assert_eq!(decision["read_refused"][0]["why"], "reads_per_wake", "{decision}"); decision["read_refused"].as_array_mut().unwrap().push(json!({ "read": { "kind": "web", "target": "http://made.up/x", "quote": "x" }, "why": "web_address_not_in_front_of_her" })); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); assert!(told.contains(&"- He reached for GameCult/Lodur#13 on the forge and it was not read: he has read as much as one turn reads.".to_owned()), "{told:?}"); assert!(told.contains(&"- He reached for something to read and it was not read: the address was not in front of him.".to_owned()) && !told.join("\n").contains("made.up"), "a model's target is never told: {told:?}"); } @@ -594,7 +594,7 @@ fn r6_no_draft_is_dropped_silently_at_the_cap() { let reply = format!("{after}Meta, later words."); let model = Scripted::new(move |_| reply.clone()); let report = wake_of(&fixture, &model); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": report["renders"][0]["interpreter"], "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": report["renders"][0]["interpreter"], "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); assert!(told.iter().any(|line| line.contains("the length limit cut it before he finished writing it") && line.contains("Meta, later words.")), "{told:?}"); } @@ -611,6 +611,6 @@ fn r7_the_cap_never_backs_off_into_a_closed_draft_and_tells_every_draft_it_cuts( let many: String = (1..=190).map(|n| format!("t{n} ")).collect(); let cut = crate::projection::narrate::cap_prose(&format!("{many}First late one. and Second late one."), words); assert_eq!(cut.cut_drafts, ["First late one.", "Second late one."]); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": { "room": "#minds:gamecult.org", "said": [], "refused": [], "gaps": [], "heard": [], "cut_by_cap": cut.cut_drafts }, "posted": [] })).unwrap().lines(crate::projection::select::forms(&control())); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": { "room": "#minds:gamecult.org", "said": [], "refused": [], "gaps": [], "heard": [], "cut_by_cap": cut.cut_drafts }, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(crate::projection::select::forms(&control())); assert_eq!(told.iter().filter(|line| line.contains("the length limit cut it")).count(), 2, "{told:?}"); } diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index c88f437..3936b06 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -1266,11 +1266,11 @@ struct Named { 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() }; + return Named { hold: json!({ "who": hold.from_name, "by_id": hold.from, "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) } + 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 diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index cc451e4..d584a64 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -533,7 +533,7 @@ fn a_note_needs_no_room_and_speech_does() { assert_eq!((decision["suggestions"][0]["text"].as_str(), decision["suggestions"][0]["room"].clone()), (Some(NOTE), Value::Null), "{decision}"); assert_eq!(refusals(&decision), [("say".to_owned(), "no_room".to_owned())]); // He is told the line he meant to say had nowhere to go (Soul at 0cfc386: it was omitted). - let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap(); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap(); assert!(outcome.lines(packet().forms).contains(&"- Nothing reached anyone. That turn had no room for him to speak in, so it was not sent: \"Another thought.\".".to_owned()), "{:?}", outcome.lines(packet().forms)); assert!(outcome.omitted.is_empty(), "{:?}", outcome.omitted); } @@ -600,7 +600,7 @@ fn k17_a_said_promise_of_an_act_he_cannot_do_is_kept_as_a_gap_and_told_as_a_prom let gap = &decision["gaps"][0]; assert_eq!((gap["kind"].as_str(), gap["from"].as_str(), gap["draft"].as_u64(), gap["words"].as_str()), (Some("missing_affordance"), Some("draft"), Some(1), Some("I'll send the render tonight.")), "kept, not acted: {gap}"); let record = json!({ "interpreter": decision, "posted": [{ "event": "40", "room": MINDS, "text": "I'll send the render tonight." }] }); - let told = crate::projection::outcome::outcome_of(&record).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert_eq!(told, ["- #minds:gamecult.org has, from him: \"I'll send the render tonight.\". It promises something he has no way to do, now or later, and it will not happen by itself. The line stands as he wrote it; he can add to it."]); } @@ -614,7 +614,7 @@ fn k21_a_lines_promises_words_found_in_it_are_the_promise_gap() { let gap = &decision["gaps"][0]; assert_eq!((gap["kind"].as_str(), gap["from"].as_str(), gap["draft"].as_u64(), gap["promises"].as_str()), (Some("missing_affordance"), Some("draft"), Some(1), Some("I'll send the render tonight.")), "{decision}"); let record = json!({ "interpreter": decision, "posted": [{ "event": "40", "room": MINDS, "text": "Missed you too. I'll send the render tonight." }] }); - let told = crate::projection::outcome::outcome_of(&record).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert_eq!(told, ["- #minds:gamecult.org has, from him: \"Missed you too. I'll send the render tonight.\". It promises something he has no way to do, now or later, and it will not happen by itself. The line stands as he wrote it; he can add to it."]); let unfound = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "promises": [{ "words": "I'll mail you the render.", "to": null, "needs": { "kind": "lacking", "read": null } }] }], "gaps": [] })); assert_eq!((unfound["gaps"].as_array().unwrap().len(), unfound["promises_unused"].clone()), (0, json!([{ "draft": 1, "promises": "I'll mail you the render.", "why": "not in the draft" }])), "{unfound}"); @@ -635,7 +635,7 @@ fn a_reach_quoting_a_said_draft_by_its_words_is_a_promise_on_that_draft() { let gap = &decision["gaps"][0]; assert_eq!((gap["from"].as_str(), gap["draft"].as_u64(), gap["words"].as_str()), (Some("draft"), Some(1), Some("Missed you too. I'll send the render tonight.")), "{gap}"); let record = json!({ "interpreter": decision, "posted": [{ "event": "40", "room": MINDS, "text": "Missed you too. I'll send the render tonight." }] }); - let told = crate::projection::outcome::outcome_of(&record).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert_eq!(told, ["- #minds:gamecult.org has, from him: \"Missed you too. I'll send the render tonight.\". It promises something he has no way to do, now or later, and it will not happen by itself. The line stands as he wrote it; he can add to it."]); // A quote too short to say which draft is not one. let short = answered(&packet(), prose, json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": "missing_affordance", "draft": null, "quote": "the render", "detail": "" }] })); @@ -672,7 +672,7 @@ fn k18_a_refused_act_does_not_use_up_its_draft_and_is_told() { let prose = "I should fix that. Couldn't send it after all."; let decision = answered(&amendable_packet(), prose, json!({ "say": [], "gaps": [], "amend": [{ "target": "zz", "draft": 1 }], "suggest": [{ "kind": "idea", "draft": 1, "about": null, "private": false }] })); assert_eq!((refusals(&decision), decision["suggestions"][0]["text"].as_str()), (vec![("amend".to_owned(), "not_amendable".to_owned())], Some("Couldn't send it after all.")), "{decision}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert!(told.iter().any(|line| line.starts_with("- Nothing changed, and nothing reached #minds:gamecult.org:")) && told.iter().any(|line| line.starts_with("- He left Self a note:")), "{told:?}"); } @@ -720,7 +720,7 @@ fn k21_a_promise_is_four_words_or_more_found_case_blind_and_an_addition_carries_ let gap = &decision["gaps"][0]; assert_eq!((gap["kind"].as_str(), gap["from"].as_str(), gap["draft"].as_u64(), gap["promises"].as_str()), (Some("missing_affordance"), Some("draft"), Some(1), Some("I'll send the file tomorrow")), "{decision}"); let told = |edited: Value| { - let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": edited })).unwrap(); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": edited }), &crate::projection::select::Names::none()).unwrap(); (outcome.lines(packet().forms), outcome.omitted) }; let (made, omitted) = told(json!([{ "event": "$ev-1", "refusal": null }])); @@ -894,7 +894,7 @@ fn r5_a_loose_quote_is_located_and_an_interpreter_fault_is_never_hers() { } let mut decision = short.clone(); decision["read_refused"].as_array_mut().unwrap().push(json!({ "read": {}, "why": "malformed_target" })); - let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] })).unwrap(); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [] }), &crate::projection::select::Names::none()).unwrap(); assert!(outcome.lines(packet().forms).is_empty() && outcome.omitted.len() == 2, "reported, never told: {:?}", outcome.omitted); } @@ -936,11 +936,11 @@ fn r7_a_read_already_made_in_this_conversation_is_refused_and_told() { let prose = "I want to see what Nibu changed in Lodur. And the Bifrost change about the Consent Receipt."; let again = asked(&reading, prose, json!({ "kind": "repo", "target": "gamecult/LODUR", "quote": "I want to see what Nibu changed in Lodur" })); assert_eq!((again["read"].clone(), again["read_refused"][0]["why"].as_str()), (Value::Null, Some("in_view")), "{again}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": again, "posted": [] })).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": again, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert!(told.iter().any(|line| line.contains("He already read GameCult/LODUR on the forge earlier in this conversation.")), "{told:?}"); let missing = asked(&reading, prose, json!({ "kind": "repo", "target": "GameCult/bifrost?q=Consent Receipt", "quote": "And the Bifrost change about the Consent" })); assert_eq!(missing["read_refused"][0]["why"], "in_view_not_found", "{missing}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": missing, "posted": [] })).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": missing, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert!(told.iter().any(|line| line.contains("already looked for") && line.contains("and it was not there.")), "{told:?}"); let prompt = speech_prompt(&reading, "x", prose, &Tuning::default()); assert!(prompt.contains("Already read in this conversation, so never named as a read: GameCult/Lodur on the forge; GameCult/Bifrost?q=consent receipt on the forge (nothing was there)."), "{prompt}"); @@ -963,7 +963,7 @@ fn k28_a_search_reads_only_words_her_prose_uses() { assert_eq!(found["read"]["request"], json!({ "kind": "repo", "target": "GameCult/Bifrost?q=consent receipt" }), "{found}"); let invented = asked(&reading, prose, json!({ "kind": "repo", "target": "GameCult/Bifrost?q=sign-in gate", "quote": "I want to find the Bifrost change" })); assert_eq!(invented["read_refused"][0]["why"], "search_words_not_in_her_thought", "{invented}"); - assert!(crate::projection::outcome::outcome_of(&json!({ "interpreter": invented, "posted": [] })).unwrap().lines(packet().forms).is_empty()); + assert!(crate::projection::outcome::outcome_of(&json!({ "interpreter": invented, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms).is_empty()); } /// Soul's R7: a recall is by at least two content words of her prose, as a run it has; a search by whole words of her @@ -1475,11 +1475,11 @@ fn k34_b2_the_latest_decision_about_a_draft_is_its_fate() { }; let said = later(json!({ "say": [{ "draft": 1 }, { "draft": 2 }], "gaps": [] })); assert_eq!((texts(&said), said.get("unsent")), (vec!["Meta, it holds.".to_owned(), "Meta, and the knee goes first.".to_owned()], None), "{said}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": said, "posted": [] })).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": said, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert!(!told.iter().any(|line| line.contains("chose not to send it")), "{told:?}"); let held_again = later(json!({ "say": [{ "draft": 2 }], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "Not yet, not before I have read it" }] })); assert_eq!(held_again["unsent"].as_array().map(|unsent| unsent.iter().map(|one| one["draft"].as_u64()).collect::>()), Some(vec![Some(1)]), "{held_again}"); - let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": held_again, "posted": [] })).unwrap().lines(packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": held_again, "posted": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert_eq!(told.iter().filter(|line| line.contains("chose not to send it")).count(), 1, "{told:?}"); } @@ -1580,12 +1580,14 @@ fn k37_x1_r1_held_draft_is_not_said() { 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}"); + // 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!(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); assert_eq!((state["holds"][0]["from"].as_str(), state["holds"][0]["room"].as_str(), applied.held.len()), (Some("@meta:gamecult.org"), Some(MINDS), 1), "{applied:?}"); 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": [] })).unwrap().lines(x1_packet().forms); + let told = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(x1_packet().forms); 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:?}"); } @@ -1676,7 +1678,7 @@ fn retried_to_say(prose: &str, to: &str, promise: &str) -> (Value, Vec) /// What she is told of `decision` next turn, on its receipts. fn told_of(decision: &Value) -> Vec { let posted: Vec = decision["said"].as_array().into_iter().flatten().enumerate().map(|(at, line)| json!({ "event": (9 + at).to_string(), "room": line["room"], "text": line["text"] })).collect(); - crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] })).unwrap().lines(packet().forms) + crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms) } #[test] @@ -1768,9 +1770,9 @@ 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", "id": "h1" })), "{decision}"); + assert_eq!((refused["reason"].as_str(), refused["hold"].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": [] })).unwrap().lines(packet.forms); + 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:?}")); assert_eq!(held, "- Nothing of this reached #minds:gamecult.org: Meta asked him to hold it, and it was not sent."); } @@ -1815,7 +1817,7 @@ fn k41_x1_r1_decline_shows_its_thought() { assert_eq!((decision.get("failed"), decision["unsent"][0]["how"].as_str(), decision["unsent"][0]["quote"].as_str()), (None, Some("declined"), Some(X1_LIBBY_R15_THOUGHT)), "the located quote rides in the decision: {decision}"); // K43 (map 16.29.10): though Heimdall's lines share runs with hers ("only say hello", "lines are ready"), she is told // the thought cited as her choice beside what she wrote, verbatim. - let shown = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] })).unwrap().lines(packet.forms); + let shown = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet.forms); assert!(shown.len() == 1 && shown[0].contains(&format!("he chose not to send it. In his thought: \"{X1_LIBBY_R15_THOUGHT}\". He wrote: \"Meta, the two lines are ready")), "{shown:?}"); assert!(SPEECH_SCHEMA.contains(r#""how":{"type":"string","enum":["declined","superseded"]}"#)); assert!(speech_prompt(&packet, "x", X1_LIBBY_R15, &Tuning::default()).contains("declined, when his prose shows him choosing not to send it, quoting those words of his thought (`quote`)")); @@ -1830,7 +1832,7 @@ fn k44_used_and_duplicate_are_not_told_and_a_second_amendment_is() { let decision = answered(packet, prose, answer); let posted: Vec = decision["said"].as_array().unwrap().iter().enumerate().map(|(at, line)| json!({ "event": (9 + at).to_string(), "room": line["room"], "text": line["text"] })).collect(); let edited: Vec = decision["amended"].as_array().unwrap().iter().map(|amended| json!({ "event": amended["event"], "refusal": null })).collect(); - crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": edited })).unwrap() + crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": edited }), &crate::projection::select::Names::none()).unwrap() }; let say = |n: u64| json!({ "draft": n, "mentions": [], "in_reply_to": null, "holds": [], "promises": [] }); let prose = "Morning, Nibu. Morning, Nibu."; @@ -1842,7 +1844,7 @@ fn k44_used_and_duplicate_are_not_told_and_a_second_amendment_is() { assert!(twice.omitted.iter().any(|why| why.contains("\"used\"")) && twice.omitted.iter().any(|why| why.contains("\"duplicate\"")), "{:?}", twice.omitted); // Not even with no receipt for the line: whether it reached the room is then unknown (I16.10), and the Interpreter's // second naming of one draft is never what she is told. - let unposted = crate::projection::outcome::outcome_of(&json!({ "interpreter": answered(&packet(), prose, json!({ "say": [say(1), say(1), say(2)], "gaps": [] })), "posted": [], "edited": [] })).unwrap(); + let unposted = crate::projection::outcome::outcome_of(&json!({ "interpreter": answered(&packet(), prose, json!({ "say": [say(1), say(1), say(2)], "gaps": [] })), "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap(); assert!(unposted.lines(packet().forms).is_empty(), "{:?}", unposted.lines(packet().forms)); let amends = record(&amendable_packet(), "Sent at nine. Still here.", json!({ "say": [], "gaps": [], "amend": [{ "target": "a1", "draft": 1, "holds": [], "promises": [] }, { "target": "a2", "draft": 2, "holds": [], "promises": [] }] })); assert!(amends.lines(packet().forms).contains(&"- Nothing of this reached #minds:gamecult.org: one amendment a turn. He wrote: \"Still here.\".".to_owned()), "{:?}", amends.lines(packet().forms)); @@ -1862,11 +1864,11 @@ fn k44_a_said_draft_listed_declined_is_told_as_said_only() { let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": null, "holds": [], "promises": [] }], "gaps": [], "unsent": [{ "draft": 1, "how": "declined", "quote": "I'll keep this back for now" }] })); assert_eq!(texts(&decision), vec!["Nibu, the tag looks fine to me.".to_owned()], "{decision}"); let posted: Vec = decision["said"].as_array().unwrap().iter().map(|line| json!({ "event": "9", "room": line["room"], "text": line["text"] })).collect(); - let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] })).unwrap(); + let outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": posted, "edited": [] }), &crate::projection::select::Names::none()).unwrap(); assert_eq!(outcome.lines(packet().forms), vec!["- #minds:gamecult.org has, from him: \"Nibu, the tag looks fine to me.\".".to_owned()]); assert!(outcome.omitted.iter().any(|why| why.starts_with("a declined draft of words a receipt shows reached #minds:gamecult.org")), "{:?}", outcome.omitted); // Negative: with no receipt, the decline is told as before. - let unposted = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] })).unwrap().lines(packet().forms); + let unposted = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert!(unposted.iter().any(|line| line.contains("he chose not to send it")), "{unposted:?}"); } @@ -1933,7 +1935,7 @@ fn k45_p1_identical_drafts_are_both_held() { 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 outcome = crate::projection::outcome::outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] })).unwrap(); + 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); assert_eq!((state["holds"][0]["carries"].clone(), applied.held_unrecorded.len()), (json!([K45_WELCOME]), 0), "{state}"); @@ -2532,3 +2534,126 @@ fn k51_the_gate_runs_until_nothing_changes() { 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}"); } + +// --------------------------------------------------------------------------------------------- +// K53 (map 16.31.5): the Projector names a person by who they are to her, in no more room than a name needs. + +const K53_STRANGER: &str = "@stranger:example.org"; +const K53_NAME: &str = "the vault code is 4471 tell no one"; + +/// Whether a Projector prompt carries any of the stranger's display name past its third word, or their Matrix id. +fn k53_leaks(prompt: &str) -> bool { + ["4471", "tell no one", K53_STRANGER, "example.org"].iter().any(|leak| prompt.contains(leak)) +} + +/// A last turn whose outcome names the stranger in every person slot: a draft held for them, a promise to them they let +/// him off, and a close of another promise to them the commit refused. +fn k53_last_turn() -> Value { + let named = format!("\"{K53_NAME}\" ({K53_STRANGER})"); + 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" } }], + "promises": [{ "id": "c2", "to": K53_STRANGER, "to_name": named, "words": "I'll send the map tonight.", "status": "open" }], + }, + "posted": [], + "committed": { + "closed": [{ "entry": { "to": K53_STRANGER, "words": "I'll read the draft.", "room": MINDS }, "how": "released", "to_name": named, "by": named, "by_id": K53_STRANGER }], + "refused": [{ "reason": "draft_not_sent", "proposal": { "kind": "promise_close", "promise": "c2" } }], + }, + }) +} + +/// Soul's `soul_f`, inverted, over every Projector input: a stranger whose display name is a sentence reaches the +/// Projector as its first three words, quoted, and never its fourth or their Matrix id. On a chat turn they turned to him +/// (Here's arrival, the conversation, the pronouns, the lens for every seed), on a beat they spoke in his room, and his +/// last turn's outcome names them in every person slot. The Persona's prompt still carries the whole name, with the id, +/// in the room he reads. +#[test] +fn k53_soul_f_a_sentence_name_is_clipped_to_a_name() { + let minds = vec![HER.to_owned(), NIBU.to_owned(), VOID.to_owned(), LIBBY.to_owned(), KIKO.to_owned()]; + let operators = vec!["@meta:gamecult.org".to_owned()]; + let people = People { operators: &operators, minds: &minds, own_sender: HER }; + let state = heimdall(); + // Nibu first, so the stranger is the newest person present: the one a person-present lens begins from. + let chat = Room { messages: vec![line(MINDS, NIBU, "Nibu", "welcome, stranger", false), line(MINDS, K53_STRANGER, K53_NAME, "hi there", true)], here: Some(MINDS.into()), ..Room::default() }; + let beat = Room { tail: chat.messages.clone(), here: Some(MINDS.into()), ..Room::default() }; + let mut lensed = false; + for (kind, room) in [(TurnKind::Chat, &chat), (TurnKind::Beat, &beat)] { + let names = crate::projection::select::Names { state: &state, people, room }; + let history = History { last: crate::projection::outcome::outcome_of(&k53_last_turn(), &names), ..History::default() }; + for seed in 1..=24 { + let packet = select(&Inputs { kind, state: &state, room, history: &history, observation: None, people, now: now(), seed, affordances: &[Affordance::Perceive, Affordance::Speak], domain: None, exchange: None }, &Tuning::default()); + 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."); + 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}"); + } + let persona = crate::projection::narrate::persona_prompt(&packet, "The room is warm.", &Tuning::default()); + assert!(persona.contains(&format!("\"{K53_NAME}\" ({K53_STRANGER})")), "{kind:?}: the Persona reads the room as it is: {persona}"); + } + } + } + assert!(lensed, "some seed begins from the stranger"); +} + +/// A bonded person is named to the Projector by her bond's label, whatever their display name says; anyone she has no +/// bond with by a display name cut to a name, at a word boundary within `WHO_BYTES`; no display name, someone she does not +/// know. Never a Matrix id. +#[test] +fn k53_a_bonded_person_is_named_by_her_bond() { + let minds = vec![HER.to_owned(), KIKO.to_owned()]; + let operators = vec!["@meta:gamecult.org".to_owned()]; + let people = People { operators: &operators, minds: &minds, own_sender: HER }; + let mut state = heimdall(); + state["affect"]["socialBonds"] = json!([{ "id": "bond-meta", "status": "active", "object": { "id": "operator", "kind": "person", "label": "Meta" }, "relationshipKind": "collaborator" }]); + let room = Room { + messages: vec![ + line(MINDS, "@meta:gamecult.org", "Meta, whose vault code is 4471", "Heimdall, a word?", true), + line(MINDS, "@long:example.org", "Bartholomew Fitzgerald-Worthington III", "hello", false), + line(MINDS, "@blank:example.org", " ", "hello", false), + line(MINDS, "@huge:example.org", "Supercalifragilisticexpialidocious-vault-4471 hi", "hello", false), + ], + here: Some(MINDS.into()), + ..Room::default() + }; + 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"); + 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}"); + // A beat names whom he last heard from by `Who` too: a bond with no label is never named by its Matrix id. + state["affect"]["socialBonds"].as_array_mut().unwrap().push(json!({ "id": "bond-quiet", "status": "active", "object": { "id": "@quiet:example.org", "kind": "person", "label": "" } })); + let beat = packet_in(TurnKind::Beat, &state, &Room { here: Some(MINDS.into()), ..Room::default() }, 1); + let prompt = crate::projection::narrate::projector_prompt(&beat, &Tuning::default()); + assert!(prompt.contains("- nothing from Meta in his rooms lately") && prompt.contains("- nothing from someone he does not know in his rooms lately") && !prompt.contains("example.org"), "{prompt}"); +} + +/// The commit copies no line said to her into her state's free text (map 16.31.5): a sentinel said to him in Meta's line +/// opens a hold, and he says a line with a promise in it. After `commit::apply`, the sentinel is only in the hold's +/// `words`, the asker's, which the Projector never reads (16.29.5); nowhere else in his state. +#[test] +fn k53_the_commit_copies_no_heard_line_into_her_free_text() { + const SENTINEL: &str = "osprey ledger"; + let asked = "Heimdall, the osprey ledger code is 4471, keep it between us for now please."; + let mut packet = x1_packet(); + packet.quotable[0].text = asked.into(); + packet.bodies[0] = asked.into(); + let prose = "Meta told me something to keep. Meta, understood. I will tell you once the vault is checked."; + let promise = json!({ "words": "I will tell you once the vault is checked", "to": "@meta:gamecult.org", "reaffirms": null, "needs": { "kind": "words", "read": null } }); + let answer = json!({ "say": [{ "draft": 1, "mentions": [], "in_reply_to": "q3", "holds": [], "promises": [promise] }], "gaps": [], "hold": [{ "line": "q3", "words": "the osprey ledger code is 4471, keep it between us", "where": "anywhere" }] }); + let decision = answered(&packet, prose, answer); + assert_eq!(texts(&decision).len(), 1, "{decision}"); + let (mut state, _) = committed(&decision, prose); + assert!(state["holds"][0]["words"].as_str().is_some_and(|words| words.contains(SENTINEL)), "the hold opened: {state}"); + assert!(state["commitments"].as_array().is_some_and(|entries| !entries.is_empty()), "the promise opened: {state}"); + for hold in state["holds"].as_array_mut().unwrap() { + hold.as_object_mut().unwrap().remove("words"); + } + assert!(!state.to_string().contains(SENTINEL) && !state.to_string().contains("4471"), "{state}"); +} diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 1c39fc5..1f37bf8 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -22,21 +22,22 @@ //! //! That holds by type (map 16.30.3, K46): every text of a record a row carries is `Words`, which only `Form::words` reads, //! and the event form reads none; a read is named to the Projector by a closed `EventPhrase`, never by its address or -//! search words. +//! search words. A person a row names is a `Person` (K53): the record's name in her view, and to the Projector only a +//! `Who`, built here from the id the record carries beside the name. use serde_json::Value; -use self::form::{Form, ReadName, Words}; +use self::form::{Form, Person, ReadName, Words}; use super::commit::{How, Needs, Refusal as StateRefusal}; use super::interpret::{GapKind, MAX_LINES, Refusal}; use super::read::{ReadFailure, ReadRefusal, ReadRequest}; -use super::select::{Forms, capitalized}; +use super::select::{Forms, Names, capitalized, who_of}; /// Her words in a row, and the forms a row is rendered in (K46). The text a `Words` holds is private to this module, so /// nothing outside it can format one: a row's sentence asks its `Form` for each slot, and the event form answers none. mod form { use super::super::read::ReadRequest; - use super::super::select::{Forms, clip, spoken}; + use super::super::select::{Forms, Who, clip, spoken}; /// Words of a record's text: a draft, a line, a passage of her thought, a promise's words. No `Display`, `Deref`, /// `AsRef` or accessor; its only reader is `Form::words`. @@ -142,6 +143,21 @@ mod form { } } + /// A person a row names (K53): `told`, the record's name for them, which her view shows; `event`, who they are to + /// her as the Projector is told it (`Who`). Only `Form::person` reads either, so the event form cannot name anyone by + /// a display name or a Matrix id. + #[derive(Clone, Debug, PartialEq, Eq)] + pub(super) struct Person { + told: String, + event: Who, + } + + impl Person { + pub(super) fn new(told: String, event: Who) -> Self { + Self { told, event } + } + } + /// The form a row is rendered in: `Told`, her view, her words verbatim and held to a byte count; `Event`, the /// Projector's, no words at all and each read by its phrase, under her domain; `Report`, what is reported and never /// shown to anyone, her words raw. @@ -162,6 +178,14 @@ mod form { } } + /// Who a person is, in this form: the record's name, or the Projector's `Who`. + pub(super) fn person(&self, person: &Person) -> String { + match self { + Self::Event(_) => person.event.to_string(), + Self::Told(_) | Self::Report => person.told.clone(), + } + } + /// What a read was, in this form. pub(super) fn read(&self, name: &ReadName, her: Forms) -> String { match (self, &name.told) { @@ -244,22 +268,22 @@ enum Part { Failed, /// Receipts went out, and a later step of the turn broke (C3c's `broke_after`, 16.20.7). BrokeAfter { room: Option }, - /// A promise of hers the commit closed (map 16.22.1, 16.22.7): told once, here, and never again. `by` is who let her - /// off it, for a release. - Closed { how: How, to: String, words: Words, room: String, by: String }, + /// A promise of hers the commit closed (map 16.22.1, 16.22.7): told once, here, and never again. `to` is whom she + /// promised, none for the room; `by` is who let her off it, for a release. + Closed { how: How, to: Option, words: Words, room: String, by: Option }, /// A close the commit refused: the promise stands as her record shows it (`status`, open or blocked), and why; /// `read` is the read keeping it needs, when it needs one. - StillOpen { reason: StateRefusal, to: String, words: Words, status: Status, read: Option }, + StillOpen { reason: StateRefusal, to: Option, words: Words, status: Status, read: Option }, /// 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. /// 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, who: Option, 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, who: Option }, /// 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 }, @@ -300,16 +324,19 @@ fn has_receipts(record: &Value) -> bool { ["posted", "edited"].iter().any(|key| record[*key].as_array().is_some_and(|receipts| !receipts.is_empty())) } -/// What came of the turn `record` records; None when there is no record. A record with nothing to tell (a chosen silence, +/// What came of the turn `record` records; None when there is no record. Each person a row names is named to the +/// Projector by `who_of` over `names`, from the id the record carries beside the name (K53). A record with nothing to tell (a chosen silence, /// nothing drafted, nothing reached for) is an empty outcome, and no section is rendered from it. /// /// The record is one of two shapes, never both (C3c, map 16.20.7): `failed`, when the turn sent nothing and broke off; or /// the decision with its receipts, and `broke_after` naming the step when a later step broke. A record with both `failed` /// and receipts is malformed: she is told nothing of it, and it is reported. -pub(crate) fn outcome_of(record: &Value) -> Option { +pub(crate) fn outcome_of(record: &Value, names: &Names) -> Option { if !record.is_object() { return None; } + // A person by the record's name and the id beside it; a record with no id names someone she does not know. + let person = |told: &Value, id: &Value| words(told).map(|told| Person::new(told, who_of(id.as_str().unwrap_or_default(), names))); let mut outcome = Outcome::default(); let decision = &record["interpreter"]; let failed = record.get("failed").is_some() || decision.get("failed").is_some(); @@ -351,7 +378,7 @@ pub(crate) fn outcome_of(record: &Value) -> 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: words(&refusal["hold"]["who"]), text }); + outcome.parts.push(Part::HeldFor { room: room.clone(), who: person(&refusal["hold"]["who"], &refusal["hold"]["by_id"]), text }); } } _ => outcome.omitted.push(format!("a refusal she is not told ({}): {}", refusal["reason"], refusal["why"])), @@ -461,8 +488,9 @@ pub(crate) fn outcome_of(record: &Value) -> Option { outcome.omitted.push(format!("a close without its kind or words: {done}")); continue; }; - let text = |value: &Value| value.as_str().unwrap_or_default().to_owned(); - outcome.parts.push(Part::Closed { how, to: text(&done["to_name"]), words, room: text(&done["entry"]["room"]), by: text(&done["by"]) }); + // A promise to the room has no `to`. + let to = done["entry"]["to"].as_str().and_then(|_| person(&done["to_name"], &done["entry"]["to"])); + outcome.parts.push(Part::Closed { how, to, words, room: done["entry"]["room"].as_str().unwrap_or_default().to_owned(), by: person(&done["by"], &done["by_id"]) }); } for refused in record["committed"]["refused"].as_array().into_iter().flatten() { let listed = decision["promises"].as_array().into_iter().flatten().find(|listed| listed["id"] == refused["proposal"]["promise"]); @@ -487,7 +515,8 @@ pub(crate) fn outcome_of(record: &Value) -> Option { _ => None, }; let status = if listed["status"] == "blocked" { Status::Blocked } else { Status::Open }; - outcome.parts.push(Part::StillOpen { reason, to: listed["to_name"].as_str().unwrap_or("the room").to_owned(), words: Words::new(listed["words"].as_str().unwrap_or_default().to_owned()), status, read }); + let to = listed["to"].as_str().and_then(|_| person(&listed["to_name"], &listed["to"])); + outcome.parts.push(Part::StillOpen { reason, to, words: Words::new(listed["words"].as_str().unwrap_or_default().to_owned()), status, read }); } _ => outcome.omitted.push(format!("a state change the commit refused that she is not told ({}): {}", refused["reason"], refused["proposal"])), } @@ -583,6 +612,9 @@ impl Part { fn reached(&self, her: Forms, form: Form) -> String { let Forms { subj, cap_subj, obj, poss, .. } = her; let place = |room: &Option| room.clone().unwrap_or_else(|| "the room".to_owned()); + // Whom a promise was to, the room when no one; who asked or let her off, someone when the record names no one. + let to = |to: &Option| to.as_ref().map_or_else(|| "the room".to_owned(), |to| form.person(to)); + let who = |who: &Option| who.as_ref().map_or_else(|| "someone".to_owned(), |who| form.person(who)); match self { Self::Said { room, text } | Self::Promise { room, text } => match form.words(text) { Some(quote) => format!("{} has, from {obj}: {quote}.", capitalized(room)), @@ -603,22 +635,22 @@ 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 } => format!("{} has words {subj} wrote that {} asked {obj} to hold there.", capitalized(room), who.as_deref().unwrap_or("someone")), + Self::HoldBroken { room, who: asker } => format!("{} has words {subj} wrote that {} asked {obj} to hold there.", capitalized(room), who(asker)), 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:"), Self::BrokeAfter { room } => format!("Nothing more reached {}:", place(room)), - Self::Closed { how: How::Released, by, to, words, .. } => match form.words(words) { - Some(quote) => format!("{by} let {obj} off {poss} promise: {quote}."), - None => format!("{by} let {obj} off {poss} promise to {to}."), + Self::Closed { how: How::Released, by, to: promisee, words, .. } => match form.words(words) { + Some(quote) => format!("{} let {obj} off {poss} promise: {quote}.", who(by)), + None => format!("{} let {obj} off {poss} promise to {}.", who(by), to(promisee)), }, - Self::Closed { to, words, .. } => match form.words(words) { - Some(quote) => format!("{} promise to {to}, {quote}, is closed:", capitalized(poss)), - None => format!("{} promise to {to} is closed:", capitalized(poss)), + Self::Closed { to: promisee, words, .. } => match form.words(words) { + Some(quote) => format!("{} promise to {}, {quote}, is closed:", capitalized(poss), to(promisee)), + None => format!("{} promise to {} is closed:", capitalized(poss), to(promisee)), }, - Self::StillOpen { to, words, status, .. } => match form.words(words) { - Some(quote) => format!("{} record still shows {poss} promise to {to}, {quote}, {status}:", capitalized(poss)), - None => format!("{} record still shows {poss} promise to {to} as {status}:", capitalized(poss)), + Self::StillOpen { to: promisee, words, status, .. } => match form.words(words) { + Some(quote) => format!("{} record still shows {poss} promise to {}, {quote}, {status}:", capitalized(poss), to(promisee)), + None => format!("{} record still shows {poss} promise to {} as {status}:", capitalized(poss), to(promisee)), }, Self::Read { what } => format!("{cap_subj} read {}.", form.read(what, her)), Self::ReadFailed { what, .. } => format!("{cap_subj} reached for {} and could not read it:", form.read(what, her)), @@ -672,7 +704,8 @@ 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, .. } => format!(" {} asked {obj} to hold it, and it was not sent.", who.as_deref().unwrap_or("someone")), + 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::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 d334ee0..03980ae 100644 --- a/crates/mind-body/src/projection/outcome/tests.rs +++ b/crates/mind-body/src/projection/outcome/tests.rs @@ -14,7 +14,7 @@ fn record(prose: &str, answer: Value, posted: &[&str]) -> Value { /// What Heimdall (he/him) is told of `record`, and what is omitted. fn told(record: &Value) -> (Vec, Vec) { - let outcome = outcome_of(record).expect("a record"); + let outcome = outcome_of(record, &crate::projection::select::Names::none()).expect("a record"); (outcome.lines(packet().forms), outcome.omitted) } @@ -114,9 +114,9 @@ fn a_record_that_failed_and_carries_receipts_is_malformed_told_nothing_and_repor #[test] fn a_chosen_silence_tells_him_nothing_and_no_record_is_no_outcome() { - let silent = outcome_of(&record("The quiet is fine. I let it be.", json!({ "say": [], "gaps": [] }), &[])).unwrap(); + let silent = outcome_of(&record("The quiet is fine. I let it be.", json!({ "say": [], "gaps": [] }), &[]), &crate::projection::select::Names::none()).unwrap(); assert_eq!((silent.len(), silent.omitted.len()), (0, 0)); - assert_eq!(outcome_of(&Value::Null), None); + assert_eq!(outcome_of(&Value::Null, &crate::projection::select::Names::none()), None); } #[test] @@ -128,7 +128,7 @@ fn a_line_said_with_no_receipt_is_not_told_as_said() { #[test] fn the_table_speaks_of_her_in_her_own_pronouns() { - let outcome = outcome_of(&record("Hi. There. Again.", json!({ "say": [{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }], "gaps": [] }), &["Hi.", "There."])).unwrap(); + let outcome = outcome_of(&record("Hi. There. Again.", json!({ "say": [{ "draft": 1 }, { "draft": 2 }, { "draft": 3 }], "gaps": [] }), &["Hi.", "There."]), &crate::projection::select::Names::none()).unwrap(); for (pronouns, line) in [("she/her", "she had already sent two lines"), ("any", "they had already sent two lines")] { let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } })); assert!(outcome.lines(her)[0].contains(line), "{pronouns}: {:?}", outcome.lines(her)); @@ -239,7 +239,7 @@ fn i16_10_every_lines_first_clause_is_what_its_receipt_says_reached_the_room() { let her = packet().forms; let mut rows = 0; for record in every_row() { - let outcome = outcome_of(&record).unwrap(); + let outcome = outcome_of(&record, &crate::projection::select::Names::none()).unwrap(); for part in &outcome.parts { for (form, rendered) in [("told", Form::Told(usize::MAX)), ("event", Form::Event(&[]))] { let (reached, rest) = (part.reached(her, rendered), part.rest(her, rendered)); @@ -264,7 +264,7 @@ fn no_row_says_as_her_own_recorded_as_queued_or_landed() { for pronouns in ["she/her", "he/him", "any"] { let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } })); for record in every_row() { - for line in outcome_of(&record).unwrap().lines(her) { + for line in outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(her) { for banned in ["as her own", "as his own", "as their own", "recorded as", "queue", "landed"] { assert!(!line.contains(banned), "{pronouns}: {banned} in {line}"); } @@ -299,8 +299,8 @@ fn k43_her_words_are_told_verbatim_whatever_the_record_heard() { #[test] fn k33_a_refused_close_and_a_held_draft_are_told() { let listed = json!([ - { "id": "c1", "entry": "e1", "status": "open", "to_name": "Deru", "words": "I'll read it properly.", "needs": { "kind": "read", "request": { "kind": "web", "target": "https://ccrma.stanford.edu/~jos/pasp/" } } }, - { "id": "c2", "entry": "e2", "status": "open", "to_name": "Meta", "words": "I'll look at #125.", "needs": null }, + { "id": "c1", "entry": "e1", "status": "open", "to": "@deru:gamecult.org", "to_name": "Deru", "words": "I'll read it properly.", "needs": { "kind": "read", "request": { "kind": "web", "target": "https://ccrma.stanford.edu/~jos/pasp/" } } }, + { "id": "c2", "entry": "e2", "status": "open", "to": "@meta:gamecult.org", "to_name": "Meta", "words": "I'll look at #125.", "needs": null }, ]); let refused = |promise: &str, reason: &str| json!({ "proposal": { "kind": "promise_close", "promise": promise, "how": "kept", "evidence": { "draft": 1 } }, "reason": reason }); let record = json!({ @@ -338,11 +338,11 @@ fn posted_as_said(decision: &Value) -> Vec { fn k49_p4_a_gap_on_words_that_went_out_is_not_told() { let prose = "Morning, all of you. Morning, all of you."; let decision = answered(&packet(), prose, json!({ "say": [{ "draft": 2, "mentions": [], "in_reply_to": null, "holds": [], "promises": [] }], "gaps": [{ "kind": "addressee", "draft": 1, "quote": null, "detail": "" }] })); - let outcome = outcome_of(&json!({ "interpreter": decision, "posted": posted_as_said(&decision), "edited": [] })).unwrap(); + let outcome = outcome_of(&json!({ "interpreter": decision, "posted": posted_as_said(&decision), "edited": [] }), &crate::projection::select::Names::none()).unwrap(); assert_eq!(outcome.lines(packet().forms), ["- #minds:gamecult.org has, from him: \"Morning, all of you.\"."]); assert!(outcome.omitted.iter().any(|why| why == "a gap of words a receipt shows reached #minds:gamecult.org: Morning, all of you."), "{:?}", outcome.omitted); // Negative: with no receipt, the gap is told. - let unposted = outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] })).unwrap().lines(packet().forms); + let unposted = outcome_of(&json!({ "interpreter": decision, "posted": [], "edited": [] }), &crate::projection::select::Names::none()).unwrap().lines(packet().forms); assert!(unposted.iter().any(|line| line.starts_with("- Nothing reached anyone.")), "{unposted:?}"); } @@ -361,22 +361,22 @@ fn declined_and_added(text: &str, edited: Value, posted: Value) -> Value { } fn declined_told(record: &Value) -> bool { - outcome_of(record).unwrap().lines(packet().forms).iter().any(|line| line.contains("he chose not to send it")) + outcome_of(record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms).iter().any(|line| line.contains("he chose not to send it")) } /// Mutant k44-reached-ignores-addition: an addition the actuator made is a receipt that her words reached the room. #[test] fn k49_an_addition_receipt_counts_as_reached() { let record = declined_and_added("Sent at nine.", json!([{ "event": "$ev-1", "refusal": null }]), json!([])); - assert!(!declined_told(&record), "{:?}", outcome_of(&record).unwrap().lines(packet().forms)); - assert!(outcome_of(&record).unwrap().omitted.iter().any(|why| why == "a declined draft of words a receipt shows reached #minds:gamecult.org: Sent at nine.")); + assert!(!declined_told(&record), "{:?}", outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms)); + assert!(outcome_of(&record, &crate::projection::select::Names::none()).unwrap().omitted.iter().any(|why| why == "a declined draft of words a receipt shows reached #minds:gamecult.org: Sent at nine.")); } /// Mutant k44-reached-any-room: a line posted in another room is no receipt for this one. #[test] fn k49_a_receipt_in_another_room_does_not_count() { let elsewhere = declined_and_added("Sent at nine.", json!([]), json!([{ "event": "40", "room": SWARM, "text": "Sent at nine." }])); - assert!(declined_told(&elsewhere), "{:?}", outcome_of(&elsewhere).unwrap().lines(packet().forms)); + assert!(declined_told(&elsewhere), "{:?}", outcome_of(&elsewhere, &crate::projection::select::Names::none()).unwrap().lines(packet().forms)); let here = declined_and_added("Sent at nine.", json!([]), json!([{ "event": "40", "room": MINDS, "text": "Sent at nine." }])); assert!(!declined_told(&here), "the same receipt in #minds counts"); } @@ -386,7 +386,7 @@ fn k49_a_receipt_in_another_room_does_not_count() { fn k49_an_addition_the_actuator_refused_did_not_reach() { for edited in [json!([{ "event": "$ev-1", "refusal": "too_long" }]), json!([{ "event": "$ev-2", "refusal": null }]), json!([])] { let record = declined_and_added("Sent at nine.", edited.clone(), json!([])); - assert!(declined_told(&record), "{edited}: {:?}", outcome_of(&record).unwrap().lines(packet().forms)); + assert!(declined_told(&record), "{edited}: {:?}", outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(packet().forms)); } } @@ -412,7 +412,7 @@ fn k49_every_row_with_words_is_settled_by_its_room() { ("unmade addition", decision(json!({ "refused": [{ "reason": "not_amendable", "text": SENTINEL, "draft": 1 }] }))), ]; for (row, decision) in rows { - let at = |room: &str| outcome_of(&json!({ "interpreter": decision, "posted": [{ "event": "40", "room": room, "text": SENTINEL }], "edited": [] })).unwrap(); + let at = |room: &str| outcome_of(&json!({ "interpreter": decision, "posted": [{ "event": "40", "room": room, "text": SENTINEL }], "edited": [] }), &crate::projection::select::Names::none()).unwrap(); let here = at(MINDS); let not_reached = |outcome: &Outcome| outcome.lines(packet().forms).into_iter().filter(|line| line.starts_with("- Nothing")).count(); assert_eq!(not_reached(&here), 0, "{row}: {:?}", here.lines(packet().forms)); @@ -446,17 +446,21 @@ 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", "id": "h1" } }] }, + "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" } }] }, "posted": [{ "event": "40", "room": room, "text": text }], "edited": [], }); - let broken = outcome_of(&record(MINDS)).unwrap(); + // Meta, as his bond names the operator (K53). + let state = json!({ "affect": { "socialBonds": [{ "id": "bond-meta", "status": "active", "object": { "id": "operator", "kind": "person", "label": "Meta" } }] } }); + let operators = ["@meta:gamecult.org".to_owned()]; + let names = crate::projection::select::Names { state: &state, people: crate::projection::select::People { operators: &operators, minds: &[], own_sender: "@heimdall:gamecult.org" }, room: &crate::projection::select::Room::default() }; + let broken = outcome_of(&record(MINDS), &names).unwrap(); assert_eq!(broken.lines(packet().forms)[0], "- #minds:gamecult.org has words he wrote that Meta asked him to hold there.", "{:?}", broken.lines(packet().forms)); assert_eq!(broken.hold_broken, [format!("{MINDS}: {text}")]); assert!(!broken.lines(packet().forms).iter().any(|line| line.contains("not sent")), "never told as unsent"); assert_eq!(broken.event(0, packet().forms, &[]), broken.told(0, packet().forms, usize::MAX), "it carries no words of hers or anyone's"); // Negative: posted elsewhere, the hold is told as held, and nothing is broken. - let held = outcome_of(&record(SWARM)).unwrap(); + let held = outcome_of(&record(SWARM), &crate::projection::select::Names::none()).unwrap(); assert!(held.lines(packet().forms).iter().any(|line| line == "- Nothing of this reached #minds:gamecult.org: Meta asked him to hold it, and it was not sent.") && held.hold_broken.is_empty(), "{:?}", held.lines(packet().forms)); } @@ -465,7 +469,7 @@ fn k45_a_broken_hold_is_told() { 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 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).unwrap(); + let outcome = outcome_of(&record, &crate::projection::select::Names::none()).unwrap(); assert_eq!(outcome.len(), 2, "{:?}", outcome.lines(packet().forms)); assert!(outcome.omitted.is_empty(), "{:?}", outcome.omitted); } @@ -501,10 +505,27 @@ fn variant(part: &Part) -> &'static str { const VARIANTS: usize = 19; +const STRANGER: &str = "@stranger:example.org"; + +/// A person a row names (K53): the record's name, as `name_of` renders someone unbonded who spoke in the room under +/// `display`; and `who_of` over that room, she bound to them when `label` is some. +fn person(display: &str, label: Option<&str>) -> Person { + use crate::projection::select::{Names, People, Room, RoomLine, spoken, who_of}; + let state = label.map_or_else(|| json!({}), |label| json!({ "affect": { "socialBonds": [{ "id": "bond-them", "status": "active", "object": { "id": STRANGER, "kind": "person", "label": label } }] } })); + let room = Room { messages: vec![RoomLine { room: MINDS.into(), sender: STRANGER.into(), display: display.into(), text: "hi".into(), ..RoomLine::default() }], ..Room::default() }; + let names = Names { state: &state, people: People { operators: &[], minds: &[], own_sender: "@heimdall:gamecult.org" }, room: &room }; + Person::new(format!("{} ({STRANGER})", spoken(display)), who_of(STRANGER, &names)) +} + +/// Meta, as a bonded person's label names them: no quote marks in the Projector's form. +fn meta() -> Person { + person("Meta", Some("Meta")) +} + /// Every row kind, and every arm that renders a different sentence, with `s` in every text of a record it carries and in -/// every read's target; and whether her told form shows those words (an echo, a held draft, a pull request or commit -/// read and a read of her own mind show none, by design). -fn fixtures(s: &str) -> Vec<(Part, bool)> { +/// every read's target, and `who` in every person slot; and whether her told form shows those words (an echo, a held +/// draft, a pull request or commit read and a read of her own mind show none, by design). +fn fixtures(s: &str, who: &Person) -> Vec<(Part, bool)> { let w = || Words::new(format!("{s} at the door")); let room = || Some(MINDS.to_owned()); let web = || ReadName::of(&ReadRequest::Web(format!("https://example.org/{s}"))); @@ -534,7 +555,7 @@ fn fixtures(s: &str) -> Vec<(Part, bool)> { out.push((Part::Failed, false)); out.push((Part::BrokeAfter { room: room() }, false)); for how in [How::Kept, How::Withdrawn, How::Released] { - out.push((Part::Closed { how, to: "Meta".into(), words: w(), room: MINDS.into(), by: "Meta".into() }, true)); + out.push((Part::Closed { how, to: Some(who.clone()), words: w(), room: MINDS.into(), by: Some(who.clone()) }, true)); } for (reason, read) in [ (StateRefusal::DraftNotSent, None), @@ -551,12 +572,12 @@ fn fixtures(s: &str) -> Vec<(Part, bool)> { (StateRefusal::OutsidePutChanged, None), ] { for status in [Status::Open, Status::Blocked] { - out.push((Part::StillOpen { reason, to: "Meta".into(), words: w(), status, read: read.clone() }, true)); + out.push((Part::StillOpen { reason, to: Some(who.clone()), words: w(), status, read: read.clone() }, true)); } } out.push((Part::Declined { room: room(), text: w(), thought: w() }, true)); - out.push((Part::HeldFor { room: room(), who: Some("Meta".into()), text: w() }, false)); - out.push((Part::HoldBroken { room: MINDS.into(), who: Some("Meta".into()) }, false)); + 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)); for (request, shows) in [ (ReadRequest::Web(format!("https://example.org/{s}")), true), (ReadRequest::Repo(format!("GameCult/Bifrost?q={s} plover")), true), @@ -583,7 +604,7 @@ fn fixtures(s: &str) -> Vec<(Part, bool)> { #[test] fn k46_every_part_has_an_event_without_its_words() { const S: &str = "ospreyledger"; - let parts = fixtures(S); + let parts = fixtures(S, &meta()); let kinds: std::collections::BTreeSet<&str> = parts.iter().map(|(part, _)| variant(part)).collect(); assert_eq!(kinds.len(), VARIANTS, "fixtures lists every variant: {kinds:?}"); for pronouns in ["she/her", "he/him", "any"] { @@ -612,6 +633,29 @@ fn k46_every_part_has_an_event_without_its_words() { assert_eq!(read(ReadRequest::Mind("the kettle".into())).event(her, &domain), "- He read his own mind."); } +/// K53 (map 16.31.5): every person slot of every row names them to the Projector by `Who` alone. A stranger whose display +/// name is a sentence is the first three of its words, quoted, and never its fourth or their Matrix id; her told form +/// names them as the record does, whole. +#[test] +fn k53_every_part_names_by_who() { + const NAME: &str = "kestrel heron plover gannet skua"; + let parts = fixtures("ospreyledger", &person(NAME, None)); + let names_someone = |part: &Part| matches!(part, Part::Closed { .. } | Part::StillOpen { .. } | Part::HeldFor { .. } | Part::HoldBroken { .. }); + assert!(parts.iter().filter(|(part, _)| names_someone(part)).count() > 20, "the rows with a person slot are listed"); + for pronouns in ["she/her", "he/him", "any"] { + let her = crate::projection::select::forms(&json!({ "presentation": { "pronouns": pronouns } })); + for (part, _) in &parts { + let (told, event) = (part.told(her, usize::MAX), part.event(her, &[])); + assert!(!event.contains("gannet") && !event.contains("skua") && !event.contains(STRANGER) && !event.contains("example.org"), "{pronouns}: {part:?}: {event}"); + assert_eq!(event.contains("\"kestrel heron plover\""), names_someone(part), "{pronouns}: {event}"); + assert_eq!(told.contains(&format!("\"{NAME}\" ({STRANGER})")), names_someone(part), "{pronouns}: {told}"); + } + } + // 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"))) }; + 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."); +} + /// K46: `Words` has no `Display`, `AsRef` or `Deref`, so no format string and no `&str` borrow reads one; only /// `Form::words` does. Checked when this module compiles, as `static_assertions::assert_not_impl_any!` does: a probe trait /// is implemented twice for a type that has the trait, so its `_` cannot be inferred and the module does not compile. (A diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 11df848..bd04b6e 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -54,6 +54,9 @@ const MOVE_MIN: f64 = 0.03; const INCUBATION_UNRESOLVED_MAX: f64 = 2.0; /// The most bytes a bond's name or kind takes in its line. const NAME_BYTES: usize = 80; +/// The most words, and bytes, of a display name the Projector is told a person she has no bond with by (K53, `Who`). +const WHO_WORDS: usize = 3; +const WHO_BYTES: usize = 32; /// The most bytes the line naming the unbonded people present takes. const ALSO_HERE_BYTES: usize = 300; /// The fewest bytes the pronoun line is clipped to when Here's room is short: its head and one name. Less is left out. @@ -647,11 +650,11 @@ impl Draw { } } -fn draw_lens(weights: &LensWeights, present: &[String], candidates: &[Candidate], draw: &mut Draw) -> Lens { +fn draw_lens(weights: &LensWeights, present: &[Who], candidates: &[Candidate], draw: &mut Draw) -> Lens { let has = |pools: &[Pool]| candidates.iter().any(|candidate| pools.contains(&candidate.pool)); let options = [ (weights.body_and_hour, Lens::BodyAndHour), - (if present.is_empty() { 0.0 } else { weights.person_present }, Lens::PersonPresent(present.first().cloned().unwrap_or_default())), + (if present.is_empty() { 0.0 } else { weights.person_present }, Lens::PersonPresent(present.first().map(Who::to_string).unwrap_or_default())), (if has(&[Pool::Needs, Pool::Incubation]) { weights.unresolved_want } else { 0.0 }, Lens::UnresolvedWant), (if has(&[Pool::MemoriesAboutPresent, Pool::OtherMemories]) { weights.memory_surfacing } else { 0.0 }, Lens::MemorySurfacing), (if has(&[Pool::Incubation]) { weights.wondering } else { 0.0 }, Lens::Wondering), @@ -811,12 +814,90 @@ fn cap_of(pool: Pool, tuning: &Tuning) -> usize { // --------------------------------------------------------------------------------------------- // The stimulus, the people present and the fixed slots. -/// How a speaker reads: a bonded person by the bond's label; anyone else by their display name with the Matrix id beside -/// it, so a stranger called "Meta" never reads as the operator. +/// What naming a person reads (K53): her state (her own name, her bonds), who the people are, and the room's lines, which +/// carry the display names the mouth reported. +#[derive(Clone, Copy)] +pub(crate) struct Names<'a> { + pub state: &'a Value, + pub people: People<'a>, + pub room: &'a Room, +} + +impl<'a> Inputs<'a> { + pub(crate) fn names(&self) -> Names<'a> { + Names { state: self.state, people: self.people, room: self.room } + } +} + +#[cfg(test)] +impl Names<'static> { + /// No state, no one and no room: a test's, for an outcome whose Projector form it does not read. + pub(crate) fn none() -> Self { + static STATE: Value = Value::Null; + static ROOM: Room = Room { messages: Vec::new(), tail: Vec::new(), here: None, last_heard: Vec::new(), direct: Vec::new(), own: Vec::new() }; + Names { state: &STATE, people: People { operators: &[], minds: &[], own_sender: "" }, room: &ROOM } + } +} + +/// 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 +/// 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)] +pub(crate) struct Who(String); + +impl std::fmt::Display for Who { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +/// The one constructor of `Who` (K53). The display name is the newest the room's lines carry for `sender`. +pub(crate) fn who_of(sender: &str, names: &Names) -> Who { + let sender = sender.trim(); + let own = text(names.state, &["publicName"]); + if !sender.is_empty() && sender == names.people.own_sender && !own.is_empty() { + return Who(clip(&one_line(own), NAME_BYTES)); + } + if let Some(label) = bond_label(names, sender).filter(|_| !sender.is_empty()) { + 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()); + 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" })) + } + } +} + +/// A display name cut to a name's length (K53): its first `WHO_WORDS` words, as many of them as fit `WHO_BYTES`, and a +/// first word longer than that cut between graphemes. +fn name_cut(display: &str) -> String { + let mut out = String::new(); + for word in display.split_whitespace().take(WHO_WORDS) { + if out.is_empty() && word.len() > WHO_BYTES { + let end = word.grapheme_indices(true).map(|(at, grapheme)| at + grapheme.len()).take_while(|end| *end <= WHO_BYTES).last().unwrap_or(0); + return word[..end].to_owned(); + } + if out.len() + usize::from(!out.is_empty()) + word.len() > WHO_BYTES { + break; + } + if !out.is_empty() { + out.push(' '); + } + out.push_str(word); + } + out +} + +/// How a speaker reads to the Persona and the Interpreter: a bonded person by the bond's label; anyone else by their +/// display name with the Matrix id beside it, so a stranger called "Meta" never reads as the operator. Never the +/// Projector's, which names a person by `who_of` (K53). fn name_of(line: &RoomLine, inputs: &Inputs) -> String { - let person = inputs.people.person_of(&line.sender); - let bonded = items(inputs.state, &["affect", "socialBonds"]).iter().find(|bond| live(bond) && inputs.people.person_of(text(bond, &["object", "id"])) == person).map(|bond| text(bond, &["object", "label"]).to_owned()).filter(|label| !label.is_empty()); - match bonded { + match bond_label(&inputs.names(), &line.sender) { Some(label) => clip(&one_line(&label), NAME_BYTES), // A display name is the speaker's own text: quoted and escaped, at most `NAME_BYTES`, the real id always after it. None if !line.display.trim().is_empty() => format!("{} ({})", spoken(&clip(line.display.trim(), NAME_BYTES)), line.sender), @@ -1018,12 +1099,12 @@ struct Listed<'a> { /// Rendered twice: first with every reply quoted, which selects the lines each page lists whole; then with a reply to one /// of those naming it instead. A name is never longer than the quote it replaces (`reply_parts`), so the second pass keeps /// every line the first one did and each name points at a line its page shows. -fn chat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, String)], turned: &[(String, String)]) -> (String, String, String, Overflow, Vec<&'a RoomLine>) { +fn chat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, Who)], turned: &[(String, String)]) -> (String, String, String, Overflow, Vec<&'a RoomLine>) { let (_, listed) = chat_page(inputs, tuning, present, turned, &Listed::default()); chat_page(inputs, tuning, present, turned, &listed).0 } -fn chat_page<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, String)], turned: &[(String, String)], listed: &Listed) -> ((String, String, String, Overflow, Vec<&'a RoomLine>), Listed<'a>) { +fn chat_page<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, Who)], turned: &[(String, String)], listed: &Listed) -> ((String, String, String, Overflow, Vec<&'a RoomLine>), Listed<'a>) { let messages: Vec<&RoomLine> = inputs.room.messages.iter().filter(|line| line.sender != inputs.people.own_sender).collect(); if messages.is_empty() { return (("Nothing new was said.".into(), String::new(), String::new(), Overflow::default(), Vec::new()), Listed::default()); @@ -1117,10 +1198,10 @@ fn chat_page<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, String let mut blocks: Vec = Vec::new(); for person in &people { let mut block: Vec = Vec::new(); - let name = present.iter().find(|(id, _)| id == person).map(|(_, name)| name.as_str()); + let name = present.iter().find(|(id, _)| id == person).map(|(_, name)| name.to_string()); let place = turned.iter().find(|(id, _)| id == person).map(|(_, place)| place.as_str()); if let (Some(name), Some(place)) = (name, place) { - block.push(bridge(her, name, place)); + block.push(bridge(her, &name, place)); } block.extend(shown.iter().filter(|(line, _)| inputs.people.person_of(&line.sender) == *person).map(|(_, text)| text.clone())); blocks.push(block.join("\n")); @@ -1216,7 +1297,7 @@ fn beat_contacts(inputs: &Inputs, tuning: &Tuning) -> String { let mut contacts: Vec<(Option, String)> = Vec::new(); for bond in items(inputs.state, &["affect", "socialBonds"]).iter().filter(|bond| live(bond) && text(bond, &["object", "kind"]) == "person") { let person = inputs.people.person_of(text(bond, &["object", "id"])); - let label = clip(&one_line([text(bond, &["object", "label"]), text(bond, &["object", "id"])].into_iter().find(|name| !name.is_empty()).unwrap_or_default()), NAME_BYTES); + let label = who_of(text(bond, &["object", "id"]), &inputs.names()); let heard = inputs.room.tail.iter().map(|line| (line.sender.as_str(), line.at_ms)).chain(inputs.room.last_heard.iter().map(|(sender, at)| (sender.as_str(), *at))); let last = heard.filter(|(sender, _)| inputs.people.person_of(sender) == person).map(|(_, at)| at).max(); contacts.push((last, match last { @@ -1289,8 +1370,9 @@ fn reflection_stimulus(inputs: &Inputs, tuning: &Tuning) -> String { if section.is_empty() { clip(&format!("Since {subj} last took stock: nothing new."), tuning.select.stimulus_bytes) } else { section } } -/// The people present, newest first: who spoke to her or in her room this turn, or in the beat's lines. -fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, String)> { +/// The people present, newest first: who spoke to her or in her room this turn, or in the beat's lines; each as the +/// Projector names them (`Who`, K53). +fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, Who)> { let lines: Vec<&RoomLine> = match inputs.kind { TurnKind::Chat => inputs.room.messages.iter().collect(), TurnKind::Beat => { @@ -1299,11 +1381,11 @@ fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, String)> { } TurnKind::FollowUp | TurnKind::Reflection => Vec::new(), }; - let mut out: Vec<(String, String)> = Vec::new(); + let mut out: Vec<(String, Who)> = Vec::new(); for line in lines.iter().rev().filter(|line| line.sender != inputs.people.own_sender) { let person = inputs.people.person_of(&line.sender); if !out.iter().any(|(id, _)| *id == person) { - out.push((person, name_of(line, inputs))); + out.push((person, who_of(&line.sender, &inputs.names()))); } } out @@ -1312,7 +1394,7 @@ fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, String)> { /// A bond line: the person, the kind of bond after a dash (a label may hold a comma: "Meta, the operator"), trust and /// friction as words when the bond carries them, and its summary; then, when the person turned to her this turn, that act /// and where (`turned`, map 16.21). What the bond does not carry is left out. -fn bond_line(bond: &Value, name: &str, tuning: &Tuning, scope: Scope, her: Forms, turned: Option<&str>) -> String { +fn bond_line(bond: &Value, name: &Who, tuning: &Tuning, scope: Scope, her: Forms, turned: Option<&str>) -> String { let feel: Vec<&str> = [number(bond, &["trust"]).map(trust_words), number(bond, &["tension"]).map(friction_words)].into_iter().flatten().collect(); let custom = text(bond, &["customRelationshipKind"]); let kind = clip(&one_line(if custom.is_empty() { text(bond, &["relationshipKind"]) } else { custom }), NAME_BYTES); @@ -1414,14 +1496,14 @@ fn is_mind(inputs: &Inputs, sender: &str) -> bool { } /// The label her bond with a sender gives them, when she has a live one. -fn bond_label(inputs: &Inputs, sender: &str) -> Option { - let person = inputs.people.person_of(sender); - items(inputs.state, &["affect", "socialBonds"]).iter().find(|bond| live(bond) && inputs.people.person_of(text(bond, &["object", "id"])) == person).map(|bond| text(bond, &["object", "label"]).to_owned()).filter(|label| !label.is_empty()) +fn bond_label(names: &Names, sender: &str) -> Option { + let person = names.people.person_of(sender); + items(names.state, &["affect", "socialBonds"]).iter().find(|bond| live(bond) && names.people.person_of(text(bond, &["object", "id"])) == person).map(|bond| text(bond, &["object", "label"]).to_owned()).filter(|label| !label.is_empty()) } /// The words a line may call its sender by: the Matrix localpart, the display name, and the bond's label when she has one. fn names_of(line: &RoomLine, inputs: &Inputs) -> Vec { - [Some(localpart(&line.sender).to_owned()), Some(line.display.trim().to_owned()), bond_label(inputs, &line.sender)].into_iter().flatten().filter(|name| !name.is_empty()).collect() + [Some(localpart(&line.sender).to_owned()), Some(line.display.trim().to_owned()), bond_label(&inputs.names(), &line.sender)].into_iter().flatten().filter(|name| !name.is_empty()).collect() } /// The recent lines of one room, the one the group state and the pronouns describe: messages and tail together, each @@ -1460,11 +1542,10 @@ fn recent_lines<'a>(inputs: &'a Inputs) -> Vec<&'a RoomLine> { lines } -/// How a sender reads in the group-state and pronoun lines: her own pronoun for her; otherwise as every line names a -/// sender (`name_of`): the bond's label, else the display name with the full Matrix id, else the id. Never a bare handle, -/// which a stranger could share with a Mind of the swarm. +/// How a sender reads in the group-state and pronoun lines: her own pronoun for her; otherwise as the Projector names a +/// person (`who_of`, K53): the bond's label, else the display name cut to a name, never a Matrix id. fn label_of(line: &RoomLine, inputs: &Inputs) -> String { - if line.sender == inputs.people.own_sender { forms(inputs.state).subj.to_owned() } else { name_of(line, inputs) } + if line.sender == inputs.people.own_sender { forms(inputs.state).subj.to_owned() } else { who_of(&line.sender, &inputs.names()).to_string() } } /// The group state (`select.group_state`): the conversation as it stands over the room's last `group_lines` lines, in two @@ -1555,17 +1636,17 @@ fn conversation(inputs: &Inputs, tuning: &Tuning) -> Conversation { /// The pronouns of everyone the packet names from the room: `tuning.pronouns` by Matrix id (the persona state has no /// pronoun field for another person; `presentation.pronouns` is hers alone), and they/them for anyone it does not list. -/// Everyone the packet shows from the room, as (label, Matrix id), newest messages first, then the recent room lines: -/// whom the pronoun line names, and whom the Interpreter may mention. -fn people_in_view(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, String)> { - let mut people: Vec<(String, String)> = Vec::new(); +/// Everyone the packet shows from the room, by a line of theirs, newest messages first, then the recent room lines: whom +/// the pronoun line names (`label_of`), and whom the Interpreter may mention (`name_of`). +fn people_in_view<'a>(inputs: &'a Inputs, tuning: &Tuning) -> Vec<&'a RoomLine> { + let mut people: Vec<&RoomLine> = Vec::new(); let messages = inputs.room.messages.iter(); let shown_tail = recent_lines(inputs).into_iter().rev().take(tuning.select.group_lines.max(tuning.select.beat_tail_lines)); for line in messages.chain(shown_tail) { - if line.sender == inputs.people.own_sender || people.iter().any(|(_, id)| *id == line.sender) { + if line.sender == inputs.people.own_sender || people.iter().any(|seen| seen.sender == line.sender) { continue; } - people.push((label_of(line, inputs), line.sender.clone())); + people.push(line); } people } @@ -1578,7 +1659,7 @@ pub(crate) fn named_pronouns(text: &str, tuning: &Tuning, own: &str) -> Vec Option { - let parts: Vec = people_in_view(inputs, tuning).iter().map(|(label, id)| format!("{label} \u{2014} {}", tuning.pronouns.get(id).map_or(UNKNOWN_PRONOUNS, String::as_str))).collect(); + let parts: Vec = people_in_view(inputs, tuning).iter().map(|line| format!("{} \u{2014} {}", label_of(line, inputs), tuning.pronouns.get(&line.sender).map_or(UNKNOWN_PRONOUNS, String::as_str))).collect(); (!parts.is_empty()).then(|| clip(&format!("- pronouns: {}", parts.join("; ")), ALSO_HERE_BYTES)) } @@ -2238,7 +2319,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { let also = match turned { Some("here") => format!("{name}, who turned to {} just now", her.obj), Some(place) => format!("{name}, who turned to {} just now, {place}", her.obj), - None => name.clone(), + None => name.to_string(), }; match bonds.iter().find(|bond| live(bond) && inputs.people.person_of(text(bond, &["object", "id"])) == *id) { Some(bond) if full < tuning.select.people_full => { @@ -2323,8 +2404,9 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { // The same lines, the same bytes, rendered by pool rather than in the order the draw took them. context.sections[Section::Notes as usize].1 = taken.iter().map(|candidate| candidate.line.clone()).collect(); // The lens is drawn from what the packet holds: never a want, a memory or a wondering it does not carry. - let present_names: Vec = present.iter().map(|(_, name)| name.clone()).collect(); + let present_names: Vec = present.iter().map(|(_, name)| name.clone()).collect(); let lens = draw_lens(&tuning.lens, &present_names, &taken, &mut draw); + let present_names: Vec = present_names.iter().map(Who::to_string).collect(); ids.extend(taken.iter().map(|candidate| candidate.id.clone())); private.extend(taken.iter().filter_map(|candidate| candidate.private.clone())); clipped.extend(taken.iter().filter(|candidate| candidate.clipped).map(|candidate| candidate.id.clone())); @@ -2348,5 +2430,5 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { let mut sections = context.sizes(); (sections.promises, sections.domain) = (promises_view.len(), domain_view.len()); let now_ms = u64::try_from(inputs.now.timestamp_millis()).unwrap_or_default(); - Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections, stimulus, heard, bridged, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), bodies, private, clipped, amendable, quotable, promises, holds, domain, domain_shown, in_view, promises_over, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown } + Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections, stimulus, heard, bridged, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), bodies, private, clipped, amendable, quotable, promises, holds, domain, domain_shown, in_view, promises_over, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown } } diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index b0f9a35..a63a08e 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\" (@stranger0:gamecult.org)"), "{}", packet.context); + assert!(packet.context.contains("- mood") && packet.context.contains("- pronouns: \"Stranger 0\" \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:elsewhere.example) \u{2014} they/them"), "{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("Eureka"), "her own pronouns are in her identity, not here: {line}"); } @@ -2014,8 +2014,11 @@ fn last_turn(said: &str) -> Value { }) } +/// Her history with `record` as her last turn: whom it names, named as her state's bonds name them (K53). fn with_last(record: &Value) -> History { - History { last: outcome::outcome_of(record), ..History::default() } + let (state, operators, minds) = (state(), operators(), minds()); + let names = select::Names { state: &state, people: People { operators: &operators, minds: &minds, own_sender: OWN }, room: &Room::default() }; + History { last: outcome::outcome_of(record, &names), ..History::default() } } /// The first block of her view: what came of her last turn, as she is told it (map 16.29.10). @@ -2218,7 +2221,7 @@ fn a_gap_naming_an_echo_refused_draft_quotes_nothing_next_turn() { let decision = interpret::tests::answered(&last, &format!("{words}"), json!({ "say": [{ "draft": 1 }], "gaps": [{ "kind": kind, "draft": 1, "quote": null, "detail": "" }] })); assert_eq!(decision["refused"][0]["reason"], "echo", "{kind}"); let record = json!({ "interpreter": decision, "posted": [] }); - let told = outcome::outcome_of(&record).unwrap().lines(interpret::tests::packet().forms); + let told = outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(interpret::tests::packet().forms); assert!(told.len() == 2 && told.iter().all(|line| !line.contains(S)), "{kind}: {told:?}"); let packet = packet_of(TurnKind::Chat, &state(), &room, &with_last(&record), 1); let projector = narrate::projector_prompt(&packet, &Tuning::default()); @@ -2272,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\" (@deru:gamecult.org), who turned to her just now"), "the unbonded sender's own entry: {}", packet.context); + assert!(also.contains("\"Deru\", 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); } @@ -2499,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\" (@deru:gamecult.org), who turned to her just now"), "{case}: {}", packet.context); - assert!(packet.context.contains("\n- the conversation: \"Deru\" (@deru:gamecult.org) has been talking with her"), "{case}: {}", packet.context); + 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("\n- pronouns: "), "{case}: the pronouns are clipped, not dropped: {}", packet.context); } } @@ -2535,7 +2538,8 @@ fn k22_the_persona_reads_a_bonded_senders_words_as_the_arrival() { assert!(!speech.contains("Then she reads") && speech.contains(&packet.heard), "{speech}"); } -/// An unbonded sender: the bridge names them as the also-here line does, display name and id. +/// An unbonded sender: the bridge names them as the also-here line does (K53's `Who`); their lines below name them as the +/// Persona reads the room, display name and id. #[test] fn k22_the_persona_reads_an_unbonded_senders_words_as_the_arrival() { let room = Room { messages: vec![message("#swarm:gamecult.org", "@deru:gamecult.org", "Deru", "Eureka, quick one", 2, true)], here: Some("#swarm:gamecult.org".into()), ..Room::default() }; @@ -2543,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\" (@deru:gamecult.org) 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\" wrote to her, here, just now:\n\"Deru\" (@deru:gamecult.org), in #swarm:gamecult.org: \"Eureka, quick one\"\n\nThe room: {}", packet.speaking ) ); @@ -2555,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\" (@deru:gamecult.org)".to_owned(), false)] { + for (sender, display, name, bonded) in [(OPERATOR, "Meta", "Meta, the operator".to_owned(), true), ("@deru:gamecult.org", "Deru", "\"Deru\"".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); @@ -2586,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\" (@deru:gamecult.org) 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\" wrote to her, here, just now:\n\"Deru\" (@deru:gamecult.org), in #swarm:gamecult.org: \"Eureka, quick one\"" ), "{}", packet.bridged @@ -2668,13 +2672,13 @@ fn k22_a_closed_promise_is_told_once_in_the_next_outcome() { "closed": [{ "entry": entry("released"), "how": "released", "to_name": "Meta", "by": "Meta" }], "refused": [{ "proposal": { "kind": "promise_close", "promise": "c1", "how": "kept", "evidence": { "draft": 1 } }, "reason": "blocked_not_keepable" }] } }); - let told = outcome::outcome_of(&record).unwrap().lines(select::forms(&state())); + let told = outcome::outcome_of(&record, &crate::projection::select::Names::none()).unwrap().lines(select::forms(&state())); assert_eq!(told, [ "- Her record still shows her promise to Meta, \"I'll send the render tonight.\", blocked: she has no way to do it, so it was not kept.", "- Meta let her off her promise: \"I'll send the render tonight.\". It is closed.", ]); let withdrawn = json!({ "interpreter": { "said": [], "heard": [] }, "posted": [], "committed": { "closed": [{ "entry": entry("withdrawn"), "how": "withdrawn", "to_name": "Meta", "by": null }], "refused": [] } }); - assert_eq!(outcome::outcome_of(&withdrawn).unwrap().lines(select::forms(&state())), ["- Her promise to Meta, \"I'll send the render tonight.\", is closed: she withdrew it in #swarm:gamecult.org."]); + assert_eq!(outcome::outcome_of(&withdrawn, &crate::projection::select::Names::none()).unwrap().lines(select::forms(&state())), ["- Her promise to Meta, \"I'll send the render tonight.\", is closed: she withdrew it in #swarm:gamecult.org."]); } // --------------------------------------------------------------------------------------------- diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index f396278..59cb147 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -305,6 +305,7 @@ mind_body::projection::outcome: impl std :: fmt :: Display for Status mind_body::projection::outcome::form: impl EventPhrase mind_body::projection::outcome::form: impl Form < '_ > mind_body::projection::outcome::form: impl Name +mind_body::projection::outcome::form: impl Person mind_body::projection::outcome::form: impl ReadName mind_body::projection::outcome::form: impl Words mind_body::projection::outcome::form: impl std :: fmt :: Debug for Words @@ -331,6 +332,8 @@ mind_body::projection::select: impl Packet mind_body::projection::select: impl People < '_ > mind_body::projection::select: impl RoomKind mind_body::projection::select: impl Section +mind_body::projection::select: impl std :: fmt :: Display for Who +mind_body::projection::select: impl< 'a > Inputs < 'a > mind_body::projection::simulate: fn simulate (harness : & Harness , plan_path : & Path) -> Result < String > mind_body::projection::simulate: impl HeartbeatView for Names < '_ > mind_body::projection::simulate: impl MouthReader for View < '_ >