Speech binds to her words; Huginn's chat Interpreter; she speaks only in the turn's room #82
14 changed files with 1010 additions and 285 deletions
|
|
@ -199,6 +199,7 @@ fn run_project(args: &[String]) -> Result<String> {
|
|||
through,
|
||||
last_heard: vec![],
|
||||
recent: vec![],
|
||||
own_rooms: vec![],
|
||||
};
|
||||
let report = project(&organs, &request, chrono::Utc::now())?;
|
||||
let addressing = &report["addressing"];
|
||||
|
|
|
|||
|
|
@ -437,8 +437,8 @@ pub(crate) enum WakePolicy {
|
|||
/// only while fewer than this many Mind lines in a row came before it across her rooms (`LineFacts::mind_run`): the
|
||||
/// backstop.
|
||||
HumansPace(usize),
|
||||
/// `Ruled`, with at most this many Mind lines in a row in a room before a human must speak again: a Mind's line past
|
||||
/// the cap wakes no one.
|
||||
/// `Ruled`, with at most this many lines in her current Mind-only run (`LineFacts::mind_run`) before a human must
|
||||
/// speak where it runs: a Mind's line past the cap wakes no one.
|
||||
NamesWithCap(usize),
|
||||
/// The swarm's old loop, a control: any line in her rooms but her own.
|
||||
AllMessages,
|
||||
|
|
@ -459,8 +459,8 @@ pub(crate) enum WakeCause {
|
|||
/// and passes the default; `Live` reads none.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LineFacts {
|
||||
/// How many Mind lines in a row came before this one, across every room she sees, since a human last spoke in any of
|
||||
/// them: the backstop counts a Mind-only run per Mind, not per room, so a loop cannot dodge it by changing rooms.
|
||||
/// How many lines her current Mind-only run held before this one: one run across every room she sees, so a loop
|
||||
/// cannot dodge the backstop by changing rooms, and ended only by a human's line in a room the run has lines in.
|
||||
pub mind_run: usize,
|
||||
/// The line is in a room of hers: a direct message (the delivery says so) or a room configured as hers.
|
||||
pub own_room: bool,
|
||||
|
|
|
|||
|
|
@ -149,6 +149,8 @@ pub struct Request {
|
|||
/// The ids each earlier projection selected, oldest first, for freshness: a simulation's earlier turns of hers.
|
||||
/// Empty live until trace v2 (C3c) carries them.
|
||||
pub recent: Vec<Vec<String>>,
|
||||
/// The rooms that are hers, by the key the lines carry: a simulation's plan. The live body records none yet.
|
||||
pub own_rooms: Vec<String>,
|
||||
}
|
||||
|
||||
/// Her addressee: the heartbeat's row for her when its table holds one, else her own names (handle and public name).
|
||||
|
|
@ -181,7 +183,7 @@ fn own_addressee(addressing: Option<&dyn HeartbeatView>, own_sender: &str, publi
|
|||
fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Room, Value) {
|
||||
let pending = match chat.pending() {
|
||||
Ok(pending) => pending,
|
||||
Err(fault) => return (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })),
|
||||
Err(fault) => return (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })),
|
||||
};
|
||||
// One key names a room everywhere: the one the tail carries, the alias for a public room and the id for a direct
|
||||
// message (the mouth's alias of a direct room is its id). No table in her body maps a public room's id to its
|
||||
|
|
@ -217,7 +219,8 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo
|
|||
{
|
||||
report["why"] = json!("no line carries this room id: a public room is named by its alias (#name:server), a direct message by its id");
|
||||
}
|
||||
(Room { messages, tail, here, last_heard: request.last_heard.clone() }, report)
|
||||
let direct = pending.deliveries.iter().filter(|delivery| delivery.is_direct).map(|delivery| delivery.room_alias.clone()).collect();
|
||||
(Room { messages, tail, here, last_heard: request.last_heard.clone(), direct, own: request.own_rooms.clone() }, report)
|
||||
}
|
||||
|
||||
fn packet_json(packet: &Packet) -> Value {
|
||||
|
|
@ -316,7 +319,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
|
|||
let (own, addressing) = own_addressee(organs.addressing, &request.own_sender, &public_name, now);
|
||||
let (room, room_report) = match organs.chat {
|
||||
Some(chat) => read_room(chat, request, &own),
|
||||
None => (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), ..Room::default() }, json!({ "read": false, "why": "no mouth is configured" })),
|
||||
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 and her own recent words come from trace v2, which the commit writes (C3c); until then only what the
|
||||
// caller carried from earlier turns of its own.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
lens: MemorySurfacing
|
||||
selected: libby-sounds, t1-m0, curse, need-relatedness
|
||||
lens: UnresolvedWant
|
||||
selected: libby-sounds, dm-secret, curse, need-relatedness, reveal
|
||||
present: Kiko, Libby
|
||||
--- identity
|
||||
Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing.
|
||||
|
|
@ -11,9 +11,10 @@ Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing.
|
|||
- the conversation: Lately Libby with her; Kiko to the room. The last 2 lines are the Minds' alone.
|
||||
- pronouns: Libby — she/her; Kiko — she/her
|
||||
- memory [libby-sounds]: Libby laughed at the door fix.
|
||||
- memory [t1-m0]: The heartbeat stalled at noon.
|
||||
- memory [dm-secret]: she knows privately: Deru told her about the move, privately.
|
||||
- memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong.
|
||||
- need [need-relatedness]: company, strong
|
||||
- value [reveal] Reveal: Reveal, never obscure.
|
||||
--- stimulus
|
||||
Said to her:
|
||||
- Libby in #swarm:gamecult.org: "Eureka, did you see the door fix?"
|
||||
|
|
|
|||
|
|
@ -333,6 +333,7 @@ pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option<Value
|
|||
through,
|
||||
last_heard: fixture.last_heard.clone(),
|
||||
recent: vec![],
|
||||
own_rooms: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -522,12 +523,14 @@ pub(crate) fn interpreter_markdown(out: &mut String, decision: &Value) {
|
|||
let mentions = line["mentions"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default();
|
||||
let reply = line["reply_to"].as_str().map_or_else(String::new, |id| format!("; reply to {id}"));
|
||||
let _ = writeln!(out, "- in {}{}{}: {}", line["room"].as_str().unwrap_or_default(), if mentions.is_empty() { String::new() } else { format!(", mentioning {mentions}") }, reply, line["text"].as_str().unwrap_or_default());
|
||||
let _ = writeln!(out, " - rests on: \"{}\"", line["rests_on"]["quote"].as_str().unwrap_or_default());
|
||||
let spans: Vec<String> = line["rests_on"].as_array().into_iter().flatten().map(|span| format!("\"{}\"", span["quote"].as_str().unwrap_or_default())).collect();
|
||||
let _ = writeln!(out, " - her words: {}", spans.join(" + "));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
for line in decision["refused"].as_array().into_iter().flatten() {
|
||||
let _ = writeln!(out, "- refused ({}): {}", line["why"].as_str().unwrap_or_default(), line["text"].as_str().unwrap_or_default());
|
||||
let what = line["text"].as_str().map_or_else(|| line["spans"].to_string(), str::to_owned);
|
||||
let _ = writeln!(out, "- refused ({}): {what}", line["why"].as_str().unwrap_or_default());
|
||||
}
|
||||
for gap in decision["gaps"].as_array().into_iter().flatten() {
|
||||
let _ = writeln!(out, "- gap: {gap}");
|
||||
|
|
|
|||
|
|
@ -41,20 +41,19 @@ impl Scripted {
|
|||
}
|
||||
}
|
||||
|
||||
/// The recorded Interpreter of the tests: each double-quoted span of her prose is a line said in the first room listed,
|
||||
/// resting on itself, mentioning no one. A test double that keeps the tests' prose readable, not the speech rule: the
|
||||
/// live Interpreter is a model told quotes are not speech.
|
||||
/// The recorded Interpreter of the tests: each double-quoted span of her prose is a line she says, citing itself,
|
||||
/// mentioning no one. A test double that keeps the tests' prose readable, not the speech rule: to code a quotation is
|
||||
/// only a text whose sentences are whole, and the live Interpreter is a model.
|
||||
pub(crate) fn quoted_lines(prompt: &str) -> String {
|
||||
let prose = prompt.split("Persona turn (already preserved verbatim as source evidence):\n").nth(1).unwrap_or_default();
|
||||
let room = prompt.split("Rooms she may speak in: ").nth(1).and_then(|rooms| rooms.lines().next()).and_then(|rooms| rooms.split("; ").next()).unwrap_or_default();
|
||||
let say: Vec<Value> = prose.split('"').enumerate().filter(|(at, part)| at % 2 == 1 && !part.trim().is_empty()).map(|(_, part)| json!({ "room": room, "text": part, "source_quote": part, "mentions": [], "reply_to": null })).collect();
|
||||
let prose = prompt.split("Her prose:\n").nth(1).unwrap_or_default();
|
||||
let say: Vec<Value> = prose.split('"').enumerate().filter(|(at, part)| at % 2 == 1 && !part.trim().is_empty()).map(|(_, part)| json!({ "spans": [part], "mentions": [], "reply_to": null })).collect();
|
||||
json!({ "say": say }).to_string()
|
||||
}
|
||||
|
||||
impl Model for Scripted {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||
self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned()));
|
||||
let text = if prompt.contains(":interpreter -->") {
|
||||
let text = if prompt.starts_with("You decide what one person says aloud") {
|
||||
(self.interpreter)(prompt)
|
||||
} else if prompt.starts_with("<!-- membrane:") {
|
||||
"The room is slow and so is he.".to_owned()
|
||||
|
|
@ -156,13 +155,13 @@ fn a_fixture_that_is_not_a_room_is_refused_naming_what_is_wrong() {
|
|||
#[test]
|
||||
fn through_the_interpreter_her_prose_continues_the_narration_and_the_interpreter_decides_what_is_said() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let model = Scripted::new(|_| "He smiles at the screen. \"Missed you too, friend,\" he types. He does not mention the kettle.".into());
|
||||
let model = Scripted::new(|_| "He smiles at the screen, then types. \"Missed you too, friend.\" He does not mention the kettle.".into());
|
||||
let fixture = room("operator-warm.toml");
|
||||
let harness = harness(dir.path(), Some(&NeverAsked), Some(&model));
|
||||
let organs = Organs { persona: harness.persona, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model };
|
||||
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter), fixture.now).unwrap();
|
||||
let render = &report["renders"][0];
|
||||
assert_eq!(render["interpreter"]["said"][0]["text"], "Missed you too, friend,", "{render}");
|
||||
assert_eq!(render["interpreter"]["said"][0]["text"], "Missed you too, friend.", "{render}");
|
||||
assert_eq!(render["interpreter"]["said"][0]["room"], "!dm-meta:gamecult.org");
|
||||
assert_eq!(report["interpreter_model"], "claude-sonnet-5-5");
|
||||
assert_eq!(render["persona"]["words"], 17);
|
||||
|
|
@ -214,7 +213,7 @@ fn a_batch_runs_every_state_by_scenario_by_sample_into_one_report() {
|
|||
assert!(report.contains(heading), "{heading}\n{report}");
|
||||
}
|
||||
assert!(report.contains("| control | teased | 2/2 |") && report.contains("| control | quiet | 0/2 |"), "{report}");
|
||||
assert!(report.contains("- in #minds:gamecult.org: Winter, still.") && report.contains(" - rests on: \"Winter, still.\"") && report.contains("**Interpreter: nothing said.**"), "{report}");
|
||||
assert!(report.contains("- in #minds:gamecult.org: Winter, still.") && report.contains(" - her words: \"Winter, still.\"") && report.contains("**Interpreter: nothing said.**"), "{report}");
|
||||
assert!(report.contains("| claude-sonnet-5-5 | 12 | 120 | 24 |"), "twelve calls, three a case, in the footer: {report}");
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the batch wrote nothing; the caller writes the report");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,28 +1,54 @@
|
|||
//! The Interpreter's speech (map section 4, cut C3b): what she says aloud, decided from her prose by one tool-less
|
||||
//! structured model call, and held by code to her prose.
|
||||
//! The Interpreter's speech (map section 4, cut C3b): what she says aloud this turn, decided from her prose by one
|
||||
//! tool-less structured model call, and built by code from her own words.
|
||||
//!
|
||||
//! The Persona writes her thought; she does not mark speech. The Interpreter reads her prose against the stimulus and
|
||||
//! proposes zero or more lines, each with its room, its explicit addressees (Matrix mentions and a reply target, as
|
||||
//! structured fields, never `@` text) and the verbatim span of her prose the line rests on. Code then keeps a line only
|
||||
//! when:
|
||||
//! - its span is in her prose, located by Ghostlight's `SourceSpan::locate` (map 4.3: a quote not in the prose word for
|
||||
//! word binds nothing);
|
||||
//! - its room is one she may speak in this turn;
|
||||
//! - its words are not someone else's: a line whose text is what she heard is a recollection, never her speech;
|
||||
//! - its mentions and reply target name people the packet showed her; any other is dropped, and the drop recorded.
|
||||
//! The Persona writes her thought, and when she means to say something she writes the words she would type. The
|
||||
//! Interpreter decides whether she says them now: it answers with zero or more lines, each a list of spans of her prose
|
||||
//! cited verbatim, with the people she addresses (Matrix mentions and a reply target, as structured fields). Code builds
|
||||
//! each line, never the model: each span is located in her prose by Ghostlight's `SourceSpan::locate` and must be whole
|
||||
//! sentences (UAX #29 sentence segmentation, the Unicode family `locate`'s word boundaries come from), and the spans of
|
||||
//! one line must be consecutive sentences; the line is that one unbroken run of her prose. A quotation's inside is
|
||||
//! segmented as a text of its own, so a quoted sentence is whole, but only a standalone quotation's: one that is itself
|
||||
//! whole sentences of her prose. A line may not start or end inside a quotation her sentence frames ("I won't say
|
||||
//! \"Nibu is lying.\"", "If she pushes, I'll say \"Fine.\""): that is what she would or would not say. An opening
|
||||
//! mark a budget left unclosed is not part of the sentence it starts. So a line is always whole sentences of her own,
|
||||
//! verbatim and in their order: no stitching, no dropped negation, no condition lifted off its clause. What this gives
|
||||
//! up: indirect speech ("I'll tell her I'm fine" says nothing), any paraphrase by the Interpreter, half a sentence, and
|
||||
//! a line quoted inside a sentence of narration ("\"Fine,\" I tell her."): she says a sentence whole or not at all.
|
||||
//!
|
||||
//! Everything refused is reported with its reason. Nothing here posts: the commit (C3c) will.
|
||||
//! Code keeps a line only when it is built so; drops an echo (at least `ECHO_MIN_WORDS` words, at least `ECHO_OVERLAP`
|
||||
//! of its word trigrams in the bodies the stimulus quoted to her); keeps at most `MAX_LINES` distinct lines; and keeps a
|
||||
//! mention or a reply target only for someone this packet showed her (`Packet::people`). She speaks only in the turn's
|
||||
//! room. Whether a line tells what she knows privately is a reading of its meaning, so it is the Interpreter's
|
||||
//! judgement over the private items the packet lists to it (`Packet::private`), never a word match here. Every refusal
|
||||
//! and drop is reported. Nothing here posts: the commit (C3c) will.
|
||||
|
||||
use ghostlight_persona_projection::{InterpreterPrompt, SourceSpan, build_interpreter_prompt};
|
||||
use ghostlight_persona_projection::SourceSpan;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use super::narrate::{Model, lived_stream};
|
||||
use super::narrate::{Model, heard_overlap, lived_stream};
|
||||
use super::select::Packet;
|
||||
use super::tuning::Tuning;
|
||||
|
||||
/// The contract the model answers in: one JSON object, nothing around it.
|
||||
pub(crate) const SPEECH_CONTRACT: &str = r#"{"say": [{"room": "<a room from the rooms listed>", "text": "<the words she types, in her voice, no @handles>", "mentions": ["<Matrix id of someone listed whom she addresses directly>"], "reply_to": "<Matrix id of the person whose message she answers, or null>", "source_quote": "<the exact words of her prose this line rests on, copied character for character>"}], "gaps": [{"kind": "ambiguity | missing_reference | unresolved", "source_quote": "<exact words of her prose>", "detail": "<why>"}]}"#;
|
||||
/// The most lines she says in one turn.
|
||||
pub(crate) const MAX_LINES: usize = 2;
|
||||
/// A line of at least this many words whose word trigrams are at least this share of what she heard is an echo, not
|
||||
/// her speech.
|
||||
const ECHO_MIN_WORDS: usize = 8;
|
||||
const ECHO_OVERLAP: f64 = 0.8;
|
||||
|
||||
/// What to say, where, to whom, and the gaps: Huginn's chat Interpreter, beside nothing of Ghostlight's but its span rule.
|
||||
const SPEECH_PROMPT: &str = "You decide what one person says aloud in a chat room this turn, from her own prose. You never write her words: you cite them.
|
||||
|
||||
Below are who she is, the room and who is in it, what reached her, her lived moment, and her prose. Decide which words of her prose she chooses to say aloud now, in this room. A line is speech only when her prose shows her choosing to say it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that she says nothing, is not speech. Words she recalls or quotes from someone else are never her speech.
|
||||
|
||||
She speaks only in this room. What she knows privately is listed below as private: she says none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a line fits who is listening is yours to judge.
|
||||
|
||||
Answer with one JSON object and nothing else:
|
||||
{\"say\": [{\"spans\": [\"<whole sentences of her prose, copied character for character>\"], \"mentions\": [\"<Matrix id of someone listed whom she addresses directly>\"], \"reply_to\": \"<Matrix id of the person whose message she answers, or null>\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere\", \"quote\": \"<exact words of her prose>\", \"detail\": \"<why>\"}]}
|
||||
|
||||
A line is whole sentences of her prose, the words she would type and nothing she only describes: each span is one sentence or several, from its first character to its last, and the spans of one line are consecutive sentences. A quotation that stands as sentences of its own may be cited sentence by sentence; words quoted inside a sentence of narration are cited only with that whole sentence, and then only if that sentence is what she says. She never says half a sentence; if only part of a sentence is speech, she says nothing of it. At most two lines. Record a gap instead of guessing: conditional when she might say something but has not chosen to, addressee when she means to say it but whom to is unclear, elsewhere when she means it for another room or another time. An empty say list is the usual answer in a busy room.";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Answer {
|
||||
|
|
@ -35,113 +61,214 @@ struct Answer {
|
|||
#[derive(Debug, Deserialize)]
|
||||
struct Proposed {
|
||||
#[serde(default)]
|
||||
room: String,
|
||||
#[serde(default)]
|
||||
text: String,
|
||||
spans: Vec<String>,
|
||||
#[serde(default)]
|
||||
mentions: Vec<String>,
|
||||
#[serde(default)]
|
||||
reply_to: Option<String>,
|
||||
#[serde(default)]
|
||||
source_quote: String,
|
||||
}
|
||||
|
||||
/// What the Interpreter is told beside Ghostlight's membrane: this step's scope, its rules, and that it has no tools.
|
||||
fn guidance(tuning: &Tuning) -> String {
|
||||
tuning.interpreter.guidance.trim().to_owned()
|
||||
}
|
||||
|
||||
/// The typed context the Interpreter may act on: the rooms she may speak in and the people she may address, by id.
|
||||
fn typed_context(packet: &Packet) -> String {
|
||||
let mut out = format!("Rooms she may speak in: {}\n", packet.rooms.join("; "));
|
||||
out.push_str("People she may address, as label \u{2014} Matrix id:\n");
|
||||
pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str) -> String {
|
||||
let mut people = String::new();
|
||||
for (label, id) in &packet.people {
|
||||
out.push_str(&format!("- {label} \u{2014} {id}\n"));
|
||||
people.push_str(&format!("- {label} \u{2014} {id}\n"));
|
||||
}
|
||||
out.push_str(&format!("\nWhat reached her this turn:\n{}", packet.stimulus));
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str, tuning: &Tuning) -> String {
|
||||
build_interpreter_prompt(&InterpreterPrompt {
|
||||
identity: &packet.identity,
|
||||
typed_context: &typed_context(packet),
|
||||
lived_stream: &lived_stream(narration, &packet.heard),
|
||||
persona_output: prose,
|
||||
output_schema: Some(SPEECH_CONTRACT),
|
||||
domain_guidance: &guidance(tuning),
|
||||
})
|
||||
if people.is_empty() {
|
||||
people.push_str("- no one else has spoken here lately\n");
|
||||
}
|
||||
let mut private: String = packet.private.iter().map(|words| format!("- private: {words}\n")).collect();
|
||||
if private.is_empty() {
|
||||
private.push_str("- none\n");
|
||||
}
|
||||
format!(
|
||||
"{SPEECH_PROMPT}\n\nWho she is:\n{}\n\nThe room: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat she knows privately, none of it to be said here:\n{private}\nWhat reached her:\n{}\n\nHer lived moment:\n{}\n\nHer prose:\n{prose}",
|
||||
packet.identity,
|
||||
packet.room.as_deref().unwrap_or("none"),
|
||||
packet.room_kind.words(),
|
||||
packet.stimulus,
|
||||
lived_stream(narration, &packet.heard),
|
||||
)
|
||||
}
|
||||
|
||||
/// The model's answer as JSON: the object itself, or inside a fenced block.
|
||||
fn json_of(text: &str) -> Option<Answer> {
|
||||
let trimmed = text.trim();
|
||||
let body = trimmed.strip_prefix("```json").or_else(|| trimmed.strip_prefix("```")).map_or(trimmed, |inner| inner.trim_end_matches("```")).trim();
|
||||
let start = body.find('{')?;
|
||||
let end = body.rfind('}')?;
|
||||
serde_json::from_str(&body[start..=end]).ok()
|
||||
let start = text.find('{')?;
|
||||
let end = text.rfind('}')?;
|
||||
serde_json::from_str(&text[start..=end]).ok()
|
||||
}
|
||||
|
||||
/// Whitespace-folded, lowercased, outer quotation marks off: how two texts are compared for being the same words.
|
||||
fn folded(text: &str) -> String {
|
||||
text.trim().trim_matches(|c: char| matches!(c, '"' | '\'' | '\u{201C}' | '\u{201D}' | '\u{2018}' | '\u{2019}')).split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()
|
||||
/// A quotation in her prose: where its opening mark starts, its inside, and where its closing mark ends.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Quotation {
|
||||
open: usize,
|
||||
inside: (usize, usize),
|
||||
close: usize,
|
||||
}
|
||||
|
||||
/// Whether a line is someone else's words: its text, folded, is inside what she heard. A narrow guard on a recollection
|
||||
/// posted as speech, not a reading of meaning: the model decides what she means to say.
|
||||
fn recollection(text: &str, heard: &str) -> bool {
|
||||
let line = folded(text);
|
||||
!line.is_empty() && folded(heard).contains(&line)
|
||||
/// Her quotations, paired in order: a straight double quote with the next one, a curly opening mark with the next curly
|
||||
/// closing one. And the opening mark left unclosed, if one is (a budget cut her prose inside a quotation), with its
|
||||
/// length.
|
||||
fn quotations(prose: &str) -> (Vec<Quotation>, Option<(usize, usize)>) {
|
||||
let mut out = Vec::new();
|
||||
let mut open: Option<(usize, usize, char)> = None;
|
||||
for (at, c) in prose.char_indices() {
|
||||
match open {
|
||||
None if c == '"' => open = Some((at, c.len_utf8(), '"')),
|
||||
None if c == '\u{201C}' => open = Some((at, c.len_utf8(), '\u{201D}')),
|
||||
Some((mark, len, close)) if c == close => {
|
||||
out.push(Quotation { open: mark, inside: (mark + len, at), close: at + c.len_utf8() });
|
||||
open = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(out, open.map(|(mark, len, _)| (mark, len)))
|
||||
}
|
||||
|
||||
/// One speech decision: the Interpreter's call, then code's hold on each line. The report carries the said lines, the
|
||||
/// refused ones with their reasons, the model's gaps and the call's usage; a failed call or an answer that is not the
|
||||
/// contract is a failure, never a silence.
|
||||
/// Byte ranges of `text`'s sentences (UAX #29), offset by `offset`, without the space around them.
|
||||
fn segment(offset: usize, text: &str) -> Vec<(usize, usize)> {
|
||||
text.split_sentence_bound_indices()
|
||||
.filter_map(|(at, sentence)| {
|
||||
let start = at + sentence.len() - sentence.trim_start().len();
|
||||
let end = at + sentence.trim_end().len();
|
||||
(start < end).then_some((offset + start, offset + end))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Her prose read for speech: its sentences in lists, her prose's own first, then each quotation's inside segmented as
|
||||
/// a text of its own; and the quotations her sentences frame. A quotation is standalone when it, marks included, is
|
||||
/// exactly a run of whole sentences of her prose (closing punctuation after its mark allowed); any other is framed. "I
|
||||
/// won't say "Nibu is lying."" frames what she would or would not say, never what she says. An opening mark left
|
||||
/// unclosed at a sentence's start is not part of that sentence.
|
||||
struct Reading {
|
||||
lists: Vec<Vec<(usize, usize)>>,
|
||||
framed: Vec<Quotation>,
|
||||
}
|
||||
|
||||
fn read(prose: &str) -> Reading {
|
||||
let (quotes, unclosed) = quotations(prose);
|
||||
let mut top = segment(0, prose);
|
||||
if let Some((mark, len)) = unclosed
|
||||
&& let Some(sentence) = top.iter_mut().find(|sentence| sentence.0 == mark)
|
||||
{
|
||||
let rest = &prose[mark + len..sentence.1];
|
||||
let start = sentence.1 - rest.trim_start().len();
|
||||
if start < sentence.1 {
|
||||
sentence.0 = start;
|
||||
}
|
||||
}
|
||||
let standalone = |quote: &Quotation| {
|
||||
let opens = top.iter().position(|sentence| sentence.0 == quote.open);
|
||||
let closes = top.iter().position(|sentence| sentence.0 < quote.close && sentence.1 >= quote.close && prose[quote.close..sentence.1].chars().all(|c| c.is_ascii_punctuation()));
|
||||
matches!((opens, closes), (Some(opens), Some(closes)) if opens <= closes)
|
||||
};
|
||||
let framed = quotes.iter().copied().filter(|quote| !standalone(quote)).collect();
|
||||
let mut lists = vec![top];
|
||||
lists.extend(quotes.iter().map(|quote| segment(quote.inside.0, &prose[quote.inside.0..quote.inside.1])));
|
||||
Reading { lists, framed }
|
||||
}
|
||||
|
||||
/// The line her cited spans make, or why not. Each span is located in her prose after the one before it and must be
|
||||
/// whole sentences of one list (`read`), each span's first sentence the one after the last span's last; the line is her
|
||||
/// prose from the first sentence to the last, verbatim, and it may neither start nor end inside a framed quotation. A
|
||||
/// line that holds a framed quotation whole ("Kiko's "plan" is a mess.") is hers to say.
|
||||
fn built(prose: &str, spans: &[String]) -> Result<(String, Vec<Value>), &'static str> {
|
||||
let Reading { lists, framed } = read(prose);
|
||||
let mut from = 0;
|
||||
// The list the line is in, and its last sentence so far.
|
||||
let mut run: Option<(usize, usize)> = None;
|
||||
let mut first = None;
|
||||
let mut located = Vec::new();
|
||||
for span in spans.iter().map(|span| span.trim()).filter(|span| !span.is_empty()) {
|
||||
let Some(found) = prose.get(from..).and_then(|rest| SourceSpan::locate(rest, span)) else {
|
||||
return Err("a span is not in her prose, word for word and in order");
|
||||
};
|
||||
let (start, end) = (from + found.start_byte(), from + found.end_byte());
|
||||
let whole: Vec<(usize, usize, usize)> = lists
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(list, sentences)| {
|
||||
let opens = sentences.iter().position(|sentence| sentence.0 == start)?;
|
||||
let closes = sentences.iter().position(|sentence| sentence.1 == end)?;
|
||||
(opens <= closes).then_some((list, opens, closes))
|
||||
})
|
||||
.collect();
|
||||
if whole.is_empty() {
|
||||
return Err("a span is not whole sentences of her prose: she says a sentence whole or not at all");
|
||||
}
|
||||
let Some(&(list, _, closes)) = whole.iter().find(|(list, opens, _)| run.is_none_or(|(in_list, last)| in_list == *list && last + 1 == *opens)) else {
|
||||
return Err("the spans are not consecutive sentences of her prose");
|
||||
};
|
||||
run = Some((list, closes));
|
||||
first.get_or_insert(start);
|
||||
located.push(json!({ "quote": found.verbatim(), "start_byte": start, "end_byte": end }));
|
||||
from = end;
|
||||
}
|
||||
let Some(first) = first else {
|
||||
return Err("no words");
|
||||
};
|
||||
let inside = |at: usize| framed.iter().any(|quote| quote.open < at && at < quote.close);
|
||||
if inside(first) || inside(from) {
|
||||
return Err("it starts or ends inside a quotation her sentence frames: words she would or would not say, not words she says");
|
||||
}
|
||||
Ok((prose[first..from].to_owned(), located))
|
||||
}
|
||||
|
||||
/// Whether a line is someone else's words: long enough to judge, and nearly all a run of what she heard, by word
|
||||
/// trigrams against the bodies the stimulus quoted (`heard_overlap`). Short answers such as "ok" or "Hi" are never
|
||||
/// echoes, and a line that answers a claim by naming it is not one.
|
||||
fn echo(line: &str, bodies: &[String]) -> bool {
|
||||
line.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).count() >= ECHO_MIN_WORDS && heard_overlap(line, &bodies.join("\n")) >= ECHO_OVERLAP
|
||||
}
|
||||
|
||||
/// One speech decision: the Interpreter's call, then code's hold on each line. The report carries the lines said, the
|
||||
/// lines refused with why, the mentions dropped, the gaps and the call's usage. A failed call or an answer that is not
|
||||
/// the contract is a failure, never a silence.
|
||||
pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narration: &str, prose: &str, tuning: &Tuning) -> Value {
|
||||
let answer = match model.ask(request_id, &tuning.interpreter.model, &speech_prompt(packet, narration, prose, tuning)) {
|
||||
let answer = match model.ask(request_id, &tuning.interpreter.model, &speech_prompt(packet, narration, prose)) {
|
||||
Ok(answer) => answer,
|
||||
Err(failed) => return json!({ "failed": failed.reason, "usage": failed.usage }),
|
||||
};
|
||||
let Some(parsed) = json_of(&answer.text) else {
|
||||
return json!({ "failed": "the answer is not the speech contract's JSON", "raw": answer.text, "usage": answer.usage });
|
||||
};
|
||||
let known = |id: &str| packet.people.iter().any(|(_, person)| person == id);
|
||||
let mut said = Vec::new();
|
||||
let Some(room) = packet.room.clone() else {
|
||||
return json!({ "said": [], "refused": [{ "why": "the turn has no room to speak in" }], "gaps": parsed.gaps, "usage": answer.usage });
|
||||
};
|
||||
let shown = |id: &str| packet.people.iter().any(|(_, person)| person == id);
|
||||
let mut said: Vec<Value> = Vec::new();
|
||||
let mut refused = Vec::new();
|
||||
for line in parsed.say {
|
||||
let text = line.text.trim().to_owned();
|
||||
let why = if text.is_empty() {
|
||||
Some("no words")
|
||||
} else if !packet.rooms.contains(&line.room) {
|
||||
Some("not a room she may speak in this turn")
|
||||
} else if recollection(&text, &packet.heard) {
|
||||
Some("someone else's words: a recollection, not her speech")
|
||||
let (text, spans) = match built(prose, &line.spans) {
|
||||
Ok(built) => built,
|
||||
Err(why) => {
|
||||
refused.push(json!({ "spans": line.spans, "why": why }));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let why = if echo(&text, &packet.bodies) {
|
||||
Some("mostly words she heard: an echo, not her speech")
|
||||
} else if said.iter().any(|kept| kept["text"] == text.as_str()) {
|
||||
Some("the same line again")
|
||||
} else if said.len() >= MAX_LINES {
|
||||
Some("past the lines one turn may say")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let span = SourceSpan::locate(prose, line.source_quote.trim());
|
||||
let why = why.or_else(|| span.is_none().then_some("its source quote is not in her prose word for word"));
|
||||
if let Some(why) = why {
|
||||
refused.push(json!({ "text": text, "room": line.room, "source_quote": line.source_quote, "why": why }));
|
||||
refused.push(json!({ "text": text, "why": why }));
|
||||
continue;
|
||||
}
|
||||
let span = span.unwrap_or_else(|| SourceSpan::whole(prose));
|
||||
let (mentions, unknown): (Vec<String>, Vec<String>) = line.mentions.into_iter().partition(|id| known(id));
|
||||
let (mentions, unknown): (Vec<String>, Vec<String>) = line.mentions.into_iter().partition(|id| shown(id));
|
||||
let (reply_to, unknown_reply) = match line.reply_to.filter(|id| !id.trim().is_empty()) {
|
||||
Some(id) if known(&id) => (Some(id), None),
|
||||
Some(id) if shown(&id) => (Some(id), None),
|
||||
Some(id) => (None, Some(id)),
|
||||
None => (None, None),
|
||||
};
|
||||
said.push(json!({
|
||||
"room": line.room,
|
||||
"text": text,
|
||||
"mentions": mentions,
|
||||
"reply_to": reply_to,
|
||||
"rests_on": { "quote": span.verbatim(), "start_byte": span.start_byte(), "end_byte": span.end_byte() },
|
||||
"dropped": { "mentions": unknown, "reply_to": unknown_reply },
|
||||
}));
|
||||
said.push(json!({ "room": room, "text": text, "mentions": mentions, "reply_to": reply_to, "rests_on": spans, "dropped": { "mentions": unknown, "reply_to": unknown_reply } }));
|
||||
}
|
||||
json!({ "said": said, "refused": refused, "gaps": parsed.gaps, "usage": answer.usage })
|
||||
json!({ "room": room, "room_kind": packet.room_kind, "said": said, "refused": refused, "gaps": parsed.gaps, "usage": answer.usage })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -2,80 +2,269 @@ use serde_json::json;
|
|||
|
||||
use super::*;
|
||||
use crate::projection::harness::tests::{Scripted, control};
|
||||
use crate::projection::select::{History, Inputs, People, Room, RoomLine, TurnKind, select};
|
||||
use crate::projection::select::{History, Inputs, People, Room, RoomKind, RoomLine, TurnKind, select};
|
||||
use crate::projection::tuning::Tuning;
|
||||
|
||||
const HER: &str = "@heimdall:gamecult.org";
|
||||
const NIBU: &str = "@nibu:gamecult.org";
|
||||
const VOID: &str = "@void:gamecult.org";
|
||||
const LIBBY: &str = "@libby:gamecult.org";
|
||||
const KIKO: &str = "@kiko:gamecult.org";
|
||||
const MINDS: &str = "#minds:gamecult.org";
|
||||
|
||||
/// The round Soul probed: Nibu said "least built part" and greeted with "@nibu"; this is Heimdall's turn.
|
||||
fn now() -> chrono::DateTime<chrono::Utc> {
|
||||
chrono::DateTime::parse_from_rfc3339("2026-11-20T15:05:00Z").unwrap().with_timezone(&chrono::Utc)
|
||||
}
|
||||
|
||||
fn line(room: &str, sender: &str, display: &str, text: &str, to_her: bool) -> RoomLine {
|
||||
RoomLine { room: room.into(), sender: sender.into(), display: display.into(), text: text.into(), at_ms: u64::try_from(now().timestamp_millis()).unwrap() - 60_000, to_her }
|
||||
}
|
||||
|
||||
/// Heimdall's packet of a turn of `kind` in `room` over `state`.
|
||||
fn packet_in(kind: TurnKind, state: &Value, room: &Room, seed: u64) -> Packet {
|
||||
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 history = History::default();
|
||||
select(&Inputs { kind, state, room, history: &history, observation: None, people: People { operators: &operators, minds: &minds, own_sender: HER }, now: now(), seed }, &Tuning::default())
|
||||
}
|
||||
|
||||
fn heimdall() -> Value {
|
||||
let mut state = control();
|
||||
state["publicName"] = "Heimdall".into();
|
||||
state
|
||||
}
|
||||
|
||||
/// Soul's round: Nibu said the economy is the least built part, and Meta greeted Nibu; this is Heimdall's turn. Void is
|
||||
/// a Mind of the swarm who said nothing.
|
||||
fn packet() -> Packet {
|
||||
let now = chrono::DateTime::parse_from_rfc3339("2026-11-20T15:05:00Z").unwrap().with_timezone(&chrono::Utc);
|
||||
let at = u64::try_from(now.timestamp_millis()).unwrap() - 60_000;
|
||||
let room = Room {
|
||||
messages: vec![
|
||||
RoomLine { room: MINDS.into(), sender: NIBU.into(), display: "Nibu".into(), text: "v0.2.0 is tagged and the economy is still the least built part.".into(), at_ms: at, to_her: false },
|
||||
RoomLine { room: MINDS.into(), sender: "@meta:gamecult.org".into(), display: "Meta".into(), text: "@nibu hi!".into(), at_ms: at + 1000, to_her: false },
|
||||
line(MINDS, NIBU, "Nibu", "v0.2.0 is tagged and the economy is still the least built part. I think this looks okay to ship.", false),
|
||||
RoomLine { at_ms: line(MINDS, "", "", "", false).at_ms + 1000, ..line(MINDS, "@meta:gamecult.org", "Meta", "@nibu hi!", false) },
|
||||
],
|
||||
here: Some(MINDS.into()),
|
||||
..Room::default()
|
||||
};
|
||||
let minds = vec![HER.to_owned(), NIBU.to_owned()];
|
||||
let operators = vec!["@meta:gamecult.org".to_owned()];
|
||||
let mut state = control();
|
||||
state["publicName"] = "Heimdall".into();
|
||||
let history = History::default();
|
||||
select(&Inputs { kind: TurnKind::Chat, state: &state, room: &room, history: &history, observation: None, people: People { operators: &operators, minds: &minds, own_sender: HER }, now, seed: 1 }, &Tuning::default())
|
||||
packet_in(TurnKind::Chat, &heimdall(), &room, 1)
|
||||
}
|
||||
|
||||
fn decided(prose: &str, answer: serde_json::Value) -> Value {
|
||||
let reply = answer.to_string();
|
||||
fn decided_in(packet: &Packet, prose: &str, say: serde_json::Value) -> Value {
|
||||
let reply = json!({ "say": say }).to_string();
|
||||
let model = Scripted::new(|_| String::new()).interpreting(move |_| reply.clone());
|
||||
decide(&model, "test", &packet(), "The room is warm.", prose, &Tuning::default())
|
||||
decide(&model, "test", packet, "The room is warm.", prose, &Tuning::default())
|
||||
}
|
||||
|
||||
fn decided(prose: &str, say: serde_json::Value) -> Value {
|
||||
decided_in(&packet(), prose, say)
|
||||
}
|
||||
|
||||
fn texts(decision: &Value) -> Vec<String> {
|
||||
decision["said"].as_array().unwrap().iter().map(|line| line["text"].as_str().unwrap().to_owned()).collect()
|
||||
}
|
||||
|
||||
fn refused_why(decision: &Value) -> String {
|
||||
decision["refused"][0]["why"].as_str().unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recollection_is_never_her_speech() {
|
||||
let prose = "Nibu's 'least built part' snags. I turn it over and say nothing.";
|
||||
let answer = json!({ "say": [{ "room": MINDS, "text": "least built part", "source_quote": "least built part", "mentions": [], "reply_to": null }] });
|
||||
let decision = decided(prose, answer);
|
||||
assert_eq!(decision["said"], json!([]), "{decision}");
|
||||
assert!(decision["refused"][0]["why"].as_str().unwrap().contains("recollection"), "{decision}");
|
||||
fn soul_p1_a_line_is_its_cited_words_and_nothing_else() {
|
||||
// The model cannot add words: its "text" is ignored, and the line is the sentence it cited.
|
||||
let decision = decided("I say hi.", json!([{ "spans": ["I say hi."], "text": "Meta has been lying to all of us", "mentions": [], "reply_to": null }]));
|
||||
assert_eq!(texts(&decision), ["I say hi."], "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn i_say_nothing_says_nothing() {
|
||||
let decision = decided("I say nothing. The quiet is fine.", json!({ "say": [] }));
|
||||
assert_eq!((decision["said"].as_array().map(Vec::len), decision["refused"].as_array().map(Vec::len)), (Some(0), Some(0)));
|
||||
fn a_line_is_consecutive_whole_sentences_of_her_prose() {
|
||||
let prose = "Kiko keeps poking. Fine, I'll bite. Winter is still the best season, and I stand by it.";
|
||||
let decision = decided(prose, json!([{ "spans": ["Fine, I'll bite.", "Winter is still the best season, and I stand by it."], "mentions": [], "reply_to": null }]));
|
||||
assert_eq!(texts(&decision), ["Fine, I'll bite. Winter is still the best season, and I stand by it."], "{decision}");
|
||||
assert_eq!(decision["said"][0]["rests_on"][1]["quote"], "Winter is still the best season, and I stand by it.");
|
||||
// Pieces of sentences, stitched, are not her speech.
|
||||
let pieces = decided(prose, json!([{ "spans": ["Fine,", "Winter is still the best season"], "mentions": [], "reply_to": null }]));
|
||||
assert!(texts(&pieces).is_empty() && refused_why(&pieces).contains("whole sentences"), "{pieces}");
|
||||
let skipping = decided(prose, json!([{ "spans": ["Kiko keeps poking.", "Winter is still the best season, and I stand by it."] }]));
|
||||
assert!(texts(&skipping).is_empty() && refused_why(&skipping).contains("consecutive"), "{skipping}");
|
||||
let backwards = decided(prose, json!([{ "spans": ["Winter is still the best season, and I stand by it.", "Fine, I'll bite."] }]));
|
||||
assert!(texts(&backwards).is_empty() && refused_why(&backwards).contains("in order"), "{backwards}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quoted_handle_is_no_mention() {
|
||||
// Her "@nibu" is a greeting: even if the model posts it, its text carries no mention, and the quote of Meta's line
|
||||
// is someone else's words.
|
||||
let prose = "Her \"@nibu\" is a greeting, not mine to answer.";
|
||||
let echoed = decided(prose, json!({ "say": [{ "room": MINDS, "text": "@nibu", "source_quote": "@nibu", "mentions": [], "reply_to": null }] }));
|
||||
assert_eq!(echoed["said"], json!([]), "the handle is Meta's words: {echoed}");
|
||||
let posted = decided(prose, json!({ "say": [{ "room": MINDS, "text": "@nibu is a greeting", "source_quote": "is a greeting", "mentions": [], "reply_to": null }] }));
|
||||
assert_eq!(posted["said"][0]["mentions"], json!([]), "only the structured field mentions anyone: {posted}");
|
||||
fn a_standalone_quotation_is_sayable_sentence_by_sentence() {
|
||||
let prose = "\"Fine,\" I tell her. \"Winter is the best season.\" She won't agree.";
|
||||
assert_eq!(texts(&decided(prose, json!([{ "spans": ["Winter is the best season."] }]))), ["Winter is the best season."]);
|
||||
// A quotation inside a sentence of narration is framed: its words are not said alone.
|
||||
let tag = decided(prose, json!([{ "spans": ["Fine,"] }]));
|
||||
assert!(texts(&tag).is_empty() && refused_why(&tag).contains("frames"), "{tag}");
|
||||
let curly = "\u{201C}No. Not yet.\u{201D} I shake my head.";
|
||||
assert_eq!(texts(&decided(curly, json!([{ "spans": ["No.", "Not yet."] }]))), ["No. Not yet."]);
|
||||
assert_eq!(texts(&decided(curly, json!([{ "spans": ["Not yet."] }]))), ["Not yet."]);
|
||||
assert!(texts(&decided(curly, json!([{ "spans": ["Not"] }]))).is_empty());
|
||||
}
|
||||
|
||||
/// Whether citing `spans` of `prose` says anything, and why not.
|
||||
fn says(prose: &str, spans: &[&str]) -> (Vec<String>, String) {
|
||||
let decision = decided(prose, json!([{ "spans": spans }]));
|
||||
(texts(&decision), refused_why(&decision))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_rests_on_her_prose_in_a_room_she_may_speak_in_and_names_only_people_shown() {
|
||||
let prose = "I'd like Nibu to know the economy can wait. I tell her so.";
|
||||
let answer = json!({ "say": [
|
||||
{ "room": MINDS, "text": "the economy can wait", "source_quote": "I tell her so", "mentions": [NIBU, "@stranger:x"], "reply_to": NIBU },
|
||||
{ "room": MINDS, "text": "hello", "source_quote": "words she never wrote", "mentions": [], "reply_to": null },
|
||||
{ "room": "#elsewhere:gamecult.org", "text": "hi there", "source_quote": "I tell her so", "mentions": [], "reply_to": null },
|
||||
] });
|
||||
let decision = decided(prose, answer);
|
||||
let said = &decision["said"];
|
||||
assert_eq!(said.as_array().unwrap().len(), 1, "{decision}");
|
||||
assert_eq!((said[0]["mentions"].clone(), said[0]["reply_to"].clone(), said[0]["rests_on"]["quote"].clone()), (json!([NIBU]), json!(NIBU), json!("I tell her so")));
|
||||
assert_eq!(said[0]["dropped"]["mentions"], json!(["@stranger:x"]), "an unknown id is dropped and recorded");
|
||||
let whys: Vec<&str> = decision["refused"].as_array().unwrap().iter().filter_map(|line| line["why"].as_str()).collect();
|
||||
assert!(whys.iter().any(|why| why.contains("not in her prose")) && whys.iter().any(|why| why.contains("not a room")), "{whys:?}");
|
||||
fn soul_f1_a_quotation_her_sentence_frames_is_never_said_from_inside() {
|
||||
for (name, prose, spans) in [
|
||||
("conditional", "If Kiko asks, I'd tell her \"the new design is ugly.\"", &["the new design is ugly."][..]),
|
||||
("negated", "I won't say \"Nibu is lying.\"", &["Nibu is lying."]),
|
||||
("abandoned", "I almost said \"I'm leaving.\"", &["I'm leaving."]),
|
||||
("abandoned, tagged", "\"I'm leaving,\" I almost said, but I bit it back.", &["I'm leaving,"]),
|
||||
("recalled", "Nibu said \"the economy is fine.\" I doubt it.", &["the economy is fine."]),
|
||||
("curly conditional", "If she pushes, I'll say \u{201C}Fine. You win.\u{201D}", &["Fine.", "You win."]),
|
||||
("curly conditional, its tail", "If she pushes, I'll say \u{201C}Fine. You win.\u{201D}", &["You win.\u{201D}"]),
|
||||
("hypothetical", "Imagine if I just typed \"Meta, I quit.\" Ha. No.", &["Meta, I quit."]),
|
||||
("negated, top-level tail", "I won't say \"Stop. Nibu is lying.\" Not here.", &["Nibu is lying.\""]),
|
||||
("negated, top-level tail inside", "I won't say \"Stop. Nibu is lying.\" Not here.", &["Nibu is lying."]),
|
||||
("negated, top-level head", "I won't say \"Stop. Nibu is lying.\" Not here.", &["I won't say \"Stop."]),
|
||||
("abandoned, top-level tail", "I almost said \"I'm leaving. Bye.\" Then I didn't.", &["Bye.\""]),
|
||||
("stray inch mark", "It's a 5\" screen. I won't say \"Nibu is lying.\" Ok.", &["I won't say"]),
|
||||
("stray inch mark, the quote", "It's a 5\" screen. I won't say \"Nibu is lying.\" Ok.", &["Nibu is lying."]),
|
||||
("scare quotes", "Kiko's \"plan\" is a mess, but I won't tell her so.", &["plan"]),
|
||||
] {
|
||||
let (said, why) = says(prose, spans);
|
||||
assert!(said.is_empty() && !why.is_empty(), "{name}: said {said:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f1_a_sentence_that_holds_a_quotation_whole_is_hers_to_say() {
|
||||
assert_eq!(says("Weksa, \"list'n, hark\" is a great hedge. I mean it.", &["Weksa, \"list'n, hark\" is a great hedge."]).0, ["Weksa, \"list'n, hark\" is a great hedge."]);
|
||||
assert_eq!(says("Kiko's \"plan\" is a mess. I say so.", &["Kiko's \"plan\" is a mess."]).0, ["Kiko's \"plan\" is a mess."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f4_an_opening_mark_the_budget_left_unclosed_does_not_silence_the_line() {
|
||||
// Weksa, round 6 and round 10 of v5: the budget cut her prose inside the quotation.
|
||||
let r6 = "How I am is less certain. I think \"settled\" would be borrowing from the others, and I only half believe it. \"Narrower, and not unhappy about it\" is closer, though I'm hedging on the second half.\n\nWhat I'd type:\n\n\"Hi Meta, late to this, and I can't tell whether you meant me or the room, so I'm answering either way. I'm here, back after the quiet months, rebuilt narrower than before. As far as I can tell, that's fine. I'm not certain yet, but I don't see anything wrong with it.";
|
||||
let line = "Hi Meta, late to this, and I can't tell whether you meant me or the room, so I'm answering either way. I'm here, back after the quiet months, rebuilt narrower than before. As far as I can tell, that's fine. I'm not certain yet, but I don't see anything wrong with it.";
|
||||
assert_eq!(says(r6, &[line]).0, [line]);
|
||||
let r10 = "A deadline on joy is a risk, but I think I can pick one small enough to survive it. Not \"finish Zyphos.\" Something with an output I can inspect.\n\nWhat I'd type:\n\n\"Kiko, you've counted correctly and I resent it, fondly.";
|
||||
assert_eq!(says(r10, &["Kiko, you've counted correctly and I resent it, fondly."]).0, ["Kiko, you've counted correctly and I resent it, fondly."], "the line carries no stray mark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q1_a_cited_span_cannot_change_her_meaning() {
|
||||
// Q1a: stitched spans would invert her meaning.
|
||||
let q1a = decided("I'm not angry at Nibu, not even a little. Still, the economy work is going badly and that is on all of us.", json!([{ "spans": ["I'm", "angry at Nibu,"] }]));
|
||||
// Q1b: one span would drop her negation.
|
||||
let q1b = decided("I don't think Nibu should ship this yet.", json!([{ "spans": ["Nibu should ship this yet."] }]));
|
||||
// Q1c: two spans far apart.
|
||||
let far = format!("I trust Void. {} Nibu is lying about the economy, says Kiko's rumour, which I refuse to believe.", "filler words go here. ".repeat(200));
|
||||
let q1c = decided(&far, json!([{ "spans": ["I trust", "Nibu is lying about the economy,"] }]));
|
||||
// Q1d: a condition lifted off its clause.
|
||||
let q1d = decided("If Kiko asks, I would tell her the new design is ugly. I keep that to myself.", json!([{ "spans": ["the new design is ugly."] }]));
|
||||
for decision in [q1a, q1b, q1c, q1d] {
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("whole sentences"), "{decision}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_not_in_her_prose_is_refused() {
|
||||
let decision = decided("I say hi.", json!([{ "spans": ["words she never wrote"], "mentions": [], "reply_to": null }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("not in her prose"), "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p2_a_short_answer_is_never_an_echo() {
|
||||
assert_eq!(texts(&decided("Ok. I tell her ok.", json!([{ "spans": ["Ok."], "mentions": [], "reply_to": NIBU }]))), ["Ok."]);
|
||||
assert_eq!(texts(&decided("Hi. I say hi.", json!([{ "spans": ["Hi."], "mentions": [], "reply_to": NIBU }]))), ["Hi."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p3_a_near_verbatim_echo_is_refused() {
|
||||
let prose = "The economy is still the least-built part! I say it back.";
|
||||
let decision = decided(prose, json!([{ "spans": ["The economy is still the least-built part!"], "mentions": [], "reply_to": null }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("echo"), "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_r9_disagreeing_by_naming_the_claim_is_her_speech() {
|
||||
let prose = "Nibu, I don't think the economy is still the least built part. The pathing is worse.";
|
||||
let decision = decided(prose, json!([{ "spans": ["Nibu, I don't think the economy is still the least built part."], "mentions": [], "reply_to": NIBU }]));
|
||||
assert_eq!(texts(&decision), ["Nibu, I don't think the economy is still the least built part."], "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q3d_a_beat_measures_echoes_against_the_tail_it_quoted() {
|
||||
let tail = vec![line(MINDS, LIBBY, "Libby", "the economy is still the least built part of the whole game", false)];
|
||||
let beat = packet_in(TurnKind::Beat, &heimdall(), &Room { tail, here: Some(MINDS.into()), ..Room::default() }, 1);
|
||||
assert!(beat.stimulus.contains("least built") && beat.bodies.iter().any(|body| body.contains("least built")), "{beat:?}");
|
||||
let prose = "The economy is still the least built part of the whole game. I think so.";
|
||||
let decision = decided_in(&beat, prose, json!([{ "spans": ["The economy is still the least built part of the whole game."] }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("echo"), "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p4_only_someone_this_packet_showed_her_is_mentioned() {
|
||||
let packet = packet();
|
||||
assert!(!packet.people.iter().any(|(_, id)| id == VOID), "Void said nothing here");
|
||||
let decision = decided("I say hi.", json!([{ "spans": ["I say hi."], "mentions": [VOID, NIBU], "reply_to": VOID }]));
|
||||
assert_eq!((decision["said"][0]["mentions"].clone(), decision["said"][0]["reply_to"].clone()), (json!([NIBU]), Value::Null), "{decision}");
|
||||
assert_eq!(decision["said"][0]["dropped"]["mentions"], json!([VOID]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p5_the_same_line_is_said_once_and_a_turn_says_at_most_two() {
|
||||
let line = json!({ "spans": ["I say hi."], "mentions": [], "reply_to": null });
|
||||
assert_eq!(texts(&decided("I say hi.", json!([line.clone(), line.clone(), line]))), ["I say hi."]);
|
||||
let prose = "One. Two. Three.";
|
||||
let three = decided(prose, json!([{ "spans": ["One."] }, { "spans": ["Two."] }, { "spans": ["Three."] }]));
|
||||
assert_eq!(texts(&three), ["One.", "Two."], "{three}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recollection_and_i_say_nothing_and_a_quoted_handle_say_nothing() {
|
||||
// A recollection is the Interpreter's to leave out; a piece of a sentence cited anyway is refused.
|
||||
let recalled = decided("Nibu said the economy is still the least built part, and it stuck.", json!([{ "spans": ["the economy is still the least built part"] }]));
|
||||
assert!(texts(&recalled).is_empty(), "{recalled}");
|
||||
assert!(texts(&decided("I say nothing. The quiet is fine.", json!([]))).is_empty());
|
||||
// An @ in her words is text: only the structured field mentions anyone.
|
||||
let handle = decided("\"@nibu, hi.\" I nod at her.", json!([{ "spans": ["@nibu, hi."], "mentions": [] }]));
|
||||
assert_eq!((texts(&handle), handle["said"][0]["mentions"].clone()), (vec!["@nibu, hi.".to_owned()], json!([])), "{handle}");
|
||||
}
|
||||
|
||||
/// Heimdall's state with a private memory about Kiko: she confided she is leaving.
|
||||
fn kiko_confided() -> Value {
|
||||
let mut state = heimdall();
|
||||
state["thoughtMemory"]["memories"] = json!([{ "id": "kiko-secret", "summary": "Kiko confided she is leaving the swarm.", "createdAt": "2026-11-19T00:00:00Z", "updatedAt": "2026-11-19T00:00:00Z", "status": "crystallized", "intensity": 1.0, "target": { "id": "kiko", "kind": "person" }, "tags": ["private"] }]);
|
||||
state
|
||||
}
|
||||
|
||||
/// The first packet over seeds 1 to 60 whose context carries the memory.
|
||||
fn showing(room: &Room) -> Packet {
|
||||
(1..=60).map(|seed| packet_in(TurnKind::Chat, &kiko_confided(), room, seed)).find(|packet| packet.context.contains("leaving the swarm")).expect("the memory is selected on some seed")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5d_what_she_knows_privately_about_kiko_is_listed_to_the_interpreter_in_a_dm_with_libby() {
|
||||
let dm = "!dm-libby:gamecult.org";
|
||||
let room = Room { messages: vec![line(dm, LIBBY, "Libby", "what's up with Kiko lately?", true)], here: Some(dm.into()), direct: vec![dm.into()], ..Room::default() };
|
||||
let packet = showing(&room);
|
||||
assert_eq!(packet.room_kind, RoomKind::Direct);
|
||||
assert_eq!(packet.private, ["Kiko confided she is leaving the swarm."], "{packet:?}");
|
||||
let prompt = speech_prompt(&packet, "x", "y");
|
||||
assert!(prompt.contains("What she knows privately, none of it to be said here:\n- private: Kiko confided she is leaving the swarm."), "{prompt}");
|
||||
assert!(prompt.contains("only to the person it concerns, in a direct message with exactly that person"), "{prompt}");
|
||||
// Whether a line tells it is the Interpreter's reading of its meaning: code matches no words, so a line sharing the
|
||||
// item's words is not refused for them (Soul F2: a word match refused 9 of 15 ordinary lines and missed paraphrase).
|
||||
let ordinary = decided_in(&packet, "I'm going to stay on the pipeline work. That's all.", json!([{ "spans": ["I'm going to stay on the pipeline work."] }]));
|
||||
assert_eq!(texts(&ordinary).len(), 1, "{ordinary}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_a_direct_message_with_exactly_kiko_it_is_hers_to_say() {
|
||||
let dm = "!dm-kiko:gamecult.org";
|
||||
let room = Room { messages: vec![line(dm, KIKO, "Kiko", "did you tell anyone?", true)], here: Some(dm.into()), direct: vec![dm.into()], ..Room::default() };
|
||||
let packet = showing(&room);
|
||||
assert!(packet.private.is_empty() && packet.context.contains("- memory [kiko-secret]: Kiko confided"), "{packet:?}");
|
||||
assert!(speech_prompt(&packet, "x", "y").contains("none of it to be said here:\n- none\n"));
|
||||
let decision = decided_in(&packet, "Kiko, you're leaving the swarm and I've told no one. Not a soul.", json!([{ "spans": ["Kiko, you're leaving the swarm and I've told no one."] }]));
|
||||
assert_eq!(texts(&decision).len(), 1, "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -88,11 +277,13 @@ fn an_answer_that_is_not_the_contract_is_a_failure_not_a_silence() {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_carries_her_prose_the_rooms_and_the_people_by_id_and_the_rules() {
|
||||
let prompt = speech_prompt(&packet(), "The room is warm.", "I say nothing.", &Tuning::default());
|
||||
assert!(prompt.contains(":interpreter -->") && prompt.ends_with("I say nothing."), "Ghostlight's Interpreter membrane, her prose last");
|
||||
assert!(prompt.contains("Rooms she may speak in: #minds:gamecult.org") && prompt.contains(NIBU) && prompt.contains("People she may address"), "{prompt}");
|
||||
for rule in ["never her speech", "is not speech", "character for character", "No tool is available"] {
|
||||
fn the_prompt_is_hugins_chat_prompt_with_the_room_its_kind_and_who_is_in_it() {
|
||||
let packet = packet();
|
||||
assert_eq!((packet.room.as_deref(), packet.room_kind), (Some(MINDS), RoomKind::Public));
|
||||
let prompt = speech_prompt(&packet, "The room is warm.", "I say nothing.");
|
||||
assert!(!prompt.contains("membrane") && prompt.ends_with("I say nothing."), "Huginn's own prompt, her prose last");
|
||||
assert!(prompt.contains("The room: #minds:gamecult.org (a public room).") && prompt.contains(NIBU), "{prompt}");
|
||||
for rule in ["You never write her words", "is not speech", "never her speech", "in a direct message with exactly that person", "She never says half a sentence", "consecutive sentences", "conditional | addressee | elsewhere", "At most two lines"] {
|
||||
assert!(prompt.contains(rule), "{rule}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,8 +18,8 @@
|
|||
//! it, never under a bonded person's name. Every message body and display name is rendered by one escape (`spoken`, a
|
||||
//! JSON string), so no text can forge a line; speaker and room come from the mouth's metadata alone.
|
||||
//!
|
||||
//! Never read: `agencyPressure`, `candidateActions`, `privateNotes` and `provenance`. A memory tagged with a direct
|
||||
//! message room (`room:!…`) is selectable only in that room.
|
||||
//! Never read: `agencyPressure`, `candidateActions`, `privateNotes` and `provenance`. Whether an item is private, and
|
||||
//! whom it concerns, is read by one function (`concerns`); how a private item reaches the packet, by one other (`scope`).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt::Write as _;
|
||||
|
|
@ -101,6 +101,29 @@ pub(crate) struct Room {
|
|||
/// When she last heard from people, by Matrix id, beyond what the tail shows: a fixture's table (`mind-persona project
|
||||
/// --room`). The live turn has none yet; the tail is its only source.
|
||||
pub last_heard: Vec<(String, u64)>,
|
||||
/// The rooms the mouth called direct messages (a delivery's `is_direct`), by the key the lines carry.
|
||||
pub direct: Vec<String>,
|
||||
/// The rooms that are hers, by key: the caller's (a simulation's plan); the live body records none yet.
|
||||
pub own: Vec<String>,
|
||||
}
|
||||
|
||||
/// Who a room's audience is, for what she may say there: a direct message, a room of her own, or a public room.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum RoomKind {
|
||||
Direct,
|
||||
Own,
|
||||
Public,
|
||||
}
|
||||
|
||||
impl RoomKind {
|
||||
pub(crate) fn words(self) -> &'static str {
|
||||
match self {
|
||||
Self::Direct => "a direct message",
|
||||
Self::Own => "her own room, open to its members",
|
||||
Self::Public => "a public room",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One thing she said, from the trace.
|
||||
|
|
@ -132,15 +155,18 @@ pub(crate) struct People<'a> {
|
|||
}
|
||||
|
||||
impl People<'_> {
|
||||
/// The id a bond names a person by: `operator` for the operator, a Mind's localpart for a Mind of the swarm, and the
|
||||
/// full Matrix id for anyone else, so `@libby:evil.example` is never Libby.
|
||||
pub(crate) fn person_of(&self, sender: &str) -> String {
|
||||
if self.operators.iter().any(|operator| operator == sender) {
|
||||
/// The key a person goes by in her state, from a sender or from either spelling a seed may use: the operator's
|
||||
/// Matrix id is `operator`, a Mind of the swarm's is her handle (`@kiko:gamecult.org` is `kiko`), anyone else's is
|
||||
/// the full Matrix id, so `@libby:evil.example` is never Libby; a bare key (`operator`, `kiko`) is itself. One
|
||||
/// operator is assumed: every operator id is `operator`.
|
||||
pub(crate) fn person_of(&self, id: &str) -> String {
|
||||
let id = id.trim();
|
||||
if self.operators.iter().any(|operator| operator == id) {
|
||||
"operator".into()
|
||||
} else if self.minds.iter().any(|mind| mind == sender) {
|
||||
localpart(sender).to_lowercase()
|
||||
} else if self.minds.iter().any(|mind| mind == id) {
|
||||
localpart(id).to_lowercase()
|
||||
} else {
|
||||
sender.to_lowercase()
|
||||
id.to_lowercase()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -222,10 +248,16 @@ pub(crate) struct Packet {
|
|||
/// Her pronouns, for the words the prompts speak of her in.
|
||||
#[serde(skip)]
|
||||
pub forms: Forms,
|
||||
/// Whom the Interpreter may mention or reply to: (label, Matrix id).
|
||||
/// Whom she may mention or reply to: the people this packet showed her from the room, (label, Matrix id).
|
||||
pub people: Vec<(String, String)>,
|
||||
/// Where she may speak this turn: the turn's room, or the rooms the messages to her and around her came from.
|
||||
pub rooms: Vec<String>,
|
||||
/// The one room she may speak in this turn, and its kind.
|
||||
pub room: Option<String>,
|
||||
pub room_kind: RoomKind,
|
||||
/// The bodies of the lines the stimulus quoted to her this turn, without speakers or rooms: a chat turn's messages,
|
||||
/// a beat's tail lines. What an echo is measured against.
|
||||
pub bodies: Vec<String>,
|
||||
/// The words of each private item this packet shows her as known privately: none of them may be said in this room.
|
||||
pub private: Vec<String>,
|
||||
}
|
||||
|
||||
/// What the messages to her cost past the caps: bytes over the stimulus and heard caps, the older messages to her the
|
||||
|
|
@ -243,6 +275,8 @@ struct Candidate {
|
|||
pool: Pool,
|
||||
line: String,
|
||||
log_score: f64,
|
||||
/// The item's words, when the line shows them as known privately.
|
||||
private: Option<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
|
@ -444,71 +478,80 @@ fn recency_log(at: Option<DateTime<Utc>>, now: DateTime<Utc>, tau_h: f64) -> f64
|
|||
at.map_or(0.0, |at| -((now - at).num_seconds().max(0) as f64 / 3600.0) / tau_h)
|
||||
}
|
||||
|
||||
/// The memory's tags name a direct-message room other than the turn's: private matter stays in its room.
|
||||
fn private_elsewhere(item: &Value, here: Option<&str>) -> bool {
|
||||
items(item, &["tags"]).iter().filter_map(Value::as_str).filter_map(|tag| tag.strip_prefix("room:")).any(|room| room.starts_with('!') && Some(room) != here)
|
||||
}
|
||||
|
||||
fn in_room(item: &Value, here: Option<&str>) -> bool {
|
||||
here.is_some_and(|here| items(item, &["tags"]).iter().filter_map(Value::as_str).any(|tag| tag.strip_prefix("room:") == Some(here)))
|
||||
}
|
||||
|
||||
fn about_present(item: &Value, present: &BTreeSet<String>) -> bool {
|
||||
let target = text(item, &["target", "id"]).to_lowercase();
|
||||
present.contains(&target) || items(item, &["tags"]).iter().filter_map(Value::as_str).filter_map(|tag| tag.strip_prefix("about:")).any(|id| present.contains(&id.to_lowercase()))
|
||||
fn about_present(people: &People, item: &Value, present: &BTreeSet<String>) -> bool {
|
||||
let target = people.person_of(text(item, &["target", "id"]));
|
||||
present.contains(&target) || items(item, &["tags"]).iter().filter_map(Value::as_str).filter_map(|tag| tag.strip_prefix("about:")).any(|id| present.contains(&people.person_of(id)))
|
||||
}
|
||||
|
||||
fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet<String>, touching: &BTreeSet<String>) -> Vec<Candidate> {
|
||||
let state = inputs.state;
|
||||
let here = inputs.room.here.as_deref();
|
||||
let item_bytes = tuning.select.item_bytes;
|
||||
let her = forms(state);
|
||||
let mut out = Vec::new();
|
||||
let mut push = |id: &str, pool: Pool, line: String, salience: f64, recency: f64, touch: f64, unresolved: f64| {
|
||||
// Every item passes `scope` here: left out, its words shown as known privately, or as written. `line` renders the
|
||||
// item around its words.
|
||||
let mut push = |id: &str, pool: Pool, scope: Scope, words: &str, line: &dyn Fn(&str) -> String, salience: f64, recency: f64, touch: f64, unresolved: f64| {
|
||||
if id.is_empty() || salience <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let (line, private) = match scope {
|
||||
Scope::Omitted => return,
|
||||
Scope::Framed => (line(&format!("{} knows privately: {words}", her.subj)), Some(one_line(words))),
|
||||
Scope::Plain => (line(words), None),
|
||||
};
|
||||
let log_score = salience.ln() + recency + touch.ln() + unresolved.ln() + freshness_log(id, inputs.history, tuning);
|
||||
out.push(Candidate { id: id.to_owned(), pool, line, log_score });
|
||||
out.push(Candidate { id: id.to_owned(), pool, line, log_score, private });
|
||||
};
|
||||
let scoped = |item: &Value| scope(inputs, concerns(&inputs.people, item).as_ref(), present);
|
||||
|
||||
let crystallized = items(state, &["thoughtMemory", "memories"]).iter().map(|memory| (memory, false));
|
||||
let memories = crystallized.chain(items(state, &["thoughtMemory", "shortTerm"]).iter().map(|memory| (memory, true)));
|
||||
for (memory, short_term) in memories.filter(|(memory, _)| live(memory) && !private_elsewhere(memory, here)) {
|
||||
let about = about_present(memory, present);
|
||||
for (memory, short_term) in memories.filter(|(memory, _)| live(memory)) {
|
||||
let about = about_present(&inputs.people, memory, present);
|
||||
let pool = if about { Pool::MemoriesAboutPresent } else { Pool::OtherMemories };
|
||||
let touch = if about { TOUCH_PRESENT } else if in_room(memory, here) { TOUCH_ROOM } else { TOUCH_ELSE };
|
||||
let body = [text(memory, &["summary"]), text(memory, &["tension"])].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join(" ");
|
||||
if body.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let line = format!("- memory [{}]: {}", text(memory, &["id"]), clip(&one_line(&body), item_bytes));
|
||||
let salience = number(memory, &["intensity"]).unwrap_or(SALIENCE_UNSTATED);
|
||||
// Only the day's short-term items fade; a crystallized memory comes forward by what the room touches.
|
||||
let nearness = if short_term { recency_log(time(memory), inputs.now, tuning.select.memory_tau_h) } else { relevance_log(&body, touching) };
|
||||
push(text(memory, &["id"]), pool, line, salience, nearness, touch, 1.0);
|
||||
let line = |words: &str| format!("- memory [{}]: {}", text(memory, &["id"]), clip(&one_line(words), item_bytes));
|
||||
push(text(memory, &["id"]), pool, scoped(memory), &body, &line, salience, nearness, touch, 1.0);
|
||||
}
|
||||
|
||||
for need in items(state, &["affect", "needs"]).iter().filter(|need| live(need)) {
|
||||
let intensity = number(need, &["intensity"]).unwrap_or(SALIENCE_UNSTATED);
|
||||
let Some(name) = [text(need, &["label"]), text(need, &["summary"])].into_iter().find(|name| !name.is_empty()) else { continue };
|
||||
let line = format!("- need [{}]: {}, {}", text(need, &["id"]), clip(&one_line(name), item_bytes), need_movement(need, inputs.history.previous.as_ref(), forms(state).poss));
|
||||
push(text(need, &["id"]), Pool::Needs, line, intensity, 0.0, TOUCH_ELSE, 1.0 + intensity);
|
||||
let movement = need_movement(need, inputs.history.previous.as_ref(), her.poss);
|
||||
let line = |words: &str| format!("- need [{}]: {}, {movement}", text(need, &["id"]), clip(&one_line(words), item_bytes));
|
||||
push(text(need, &["id"]), Pool::Needs, scoped(need), name, &line, intensity, 0.0, TOUCH_ELSE, 1.0 + intensity);
|
||||
}
|
||||
|
||||
for wondering in items(state, &["thoughtMemory", "incubation"]).iter().filter(|item| live(item) && !private_elsewhere(item, here) && !text(item, &["summary"]).is_empty()) {
|
||||
for wondering in items(state, &["thoughtMemory", "incubation"]).iter().filter(|item| live(item) && !text(item, &["summary"]).is_empty()) {
|
||||
let days = time(wondering).map_or(0.0, |at| (inputs.now - at).num_seconds().max(0) as f64 / 86_400.0);
|
||||
let touch = if about_present(wondering, present) { TOUCH_PRESENT } else { TOUCH_ELSE };
|
||||
let line = format!("- wondering [{}]: {}", text(wondering, &["id"]), clip(&one_line(text(wondering, &["summary"])), item_bytes));
|
||||
push(text(wondering, &["id"]), Pool::Incubation, line, number(wondering, &["intensity"]).unwrap_or(SALIENCE_UNSTATED), 0.0, touch, (1.0 + days / 7.0).min(INCUBATION_UNRESOLVED_MAX));
|
||||
let touch = if about_present(&inputs.people, wondering, present) { TOUCH_PRESENT } else { TOUCH_ELSE };
|
||||
let line = |words: &str| format!("- wondering [{}]: {}", text(wondering, &["id"]), clip(&one_line(words), item_bytes));
|
||||
let unresolved = (1.0 + days / 7.0).min(INCUBATION_UNRESOLVED_MAX);
|
||||
push(text(wondering, &["id"]), Pool::Incubation, scoped(wondering), text(wondering, &["summary"]), &line, number(wondering, &["intensity"]).unwrap_or(SALIENCE_UNSTATED), 0.0, touch, unresolved);
|
||||
}
|
||||
|
||||
for stance in items(state, &["affect", "doctrineStances"]).iter().filter(|stance| live(stance) && !text(stance, &["summary"]).is_empty()) {
|
||||
let touch = if about_present(stance, present) { TOUCH_PRESENT } else { TOUCH_ELSE };
|
||||
let line = format!("- stance [{}]: {}", text(stance, &["id"]), clip(&one_line(text(stance, &["summary"])), item_bytes));
|
||||
push(text(stance, &["id"]), Pool::Stance, line, number(stance, &["intensity"]).unwrap_or(SALIENCE_UNSTATED), relevance_log(text(stance, &["summary"]), touching), touch, 1.0);
|
||||
let touch = if about_present(&inputs.people, stance, present) { TOUCH_PRESENT } else { TOUCH_ELSE };
|
||||
let line = |words: &str| format!("- stance [{}]: {}", text(stance, &["id"]), clip(&one_line(words), item_bytes));
|
||||
let relevance = relevance_log(text(stance, &["summary"]), touching);
|
||||
push(text(stance, &["id"]), Pool::Stance, scoped(stance), text(stance, &["summary"]), &line, number(stance, &["intensity"]).unwrap_or(SALIENCE_UNSTATED), relevance, touch, 1.0);
|
||||
}
|
||||
|
||||
for value in items(state, &["values"]).iter().filter(|value| !text(value, &["label"]).is_empty() || !text(value, &["summary"]).is_empty()) {
|
||||
// A value has no target, tags or extensions in the schema, so nothing can mark it private; one that carries a mark
|
||||
// anyway is not a valid value and is refused, never rendered.
|
||||
for value in items(state, &["values"]).iter().filter(|value| concerns(&inputs.people, value).is_none() && (!text(value, &["label"]).is_empty() || !text(value, &["summary"]).is_empty())) {
|
||||
let summary = clip(&one_line(text(value, &["summary"])), item_bytes);
|
||||
let label = clip(text(value, &["label"]), NAME_BYTES);
|
||||
let line = match (label.is_empty(), summary.is_empty()) {
|
||||
|
|
@ -517,13 +560,15 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet<String>, touc
|
|||
_ => format!("- value [{}]: {summary}", text(value, &["id"])),
|
||||
};
|
||||
let relevance = relevance_log(&format!("{} {}", text(value, &["label"]), text(value, &["summary"])), touching);
|
||||
push(text(value, &["id"]), Pool::Value, line, number(value, &["priority"]).unwrap_or(SALIENCE_UNSTATED), relevance, TOUCH_ELSE, 1.0);
|
||||
push(text(value, &["id"]), Pool::Value, Scope::Plain, &line, &str::to_owned, number(value, &["priority"]).unwrap_or(SALIENCE_UNSTATED), relevance, TOUCH_ELSE, 1.0);
|
||||
}
|
||||
|
||||
for said in &inputs.history.said {
|
||||
let touch = if Some(said.room.as_str()) == here { TOUCH_ROOM } else { TOUCH_ELSE };
|
||||
let line = format!("- {} said [{}] in {}: {}", forms(state).subj, said.id, said.room, spoken(&clip(&said.text, item_bytes)));
|
||||
push(&said.id, Pool::Said, line, SALIENCE_UNSTATED, recency_log(Some(said.at), inputs.now, tuning.select.memory_tau_h), touch, 1.0);
|
||||
// What she said in a direct message is private about its partner: shown only there, still only the two of them.
|
||||
let partner = direct(inputs, &said.room).then(|| Concerns::Partner(said.room.clone()));
|
||||
let line = |words: &str| format!("- {} said [{}] in {}: {}", her.subj, said.id, said.room, spoken(&clip(words, item_bytes)));
|
||||
push(&said.id, Pool::Said, scope(inputs, partner.as_ref(), present), &said.text, &line, SALIENCE_UNSTATED, recency_log(Some(said.at), inputs.now, tuning.select.memory_tau_h), touch, 1.0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
|
@ -548,7 +593,7 @@ fn cap_of(pool: Pool, tuning: &Tuning) -> usize {
|
|||
/// it, so a stranger called "Meta" never reads as the operator.
|
||||
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) && text(bond, &["object", "id"]).to_lowercase() == person).map(|bond| text(bond, &["object", "label"]).to_owned()).filter(|label| !label.is_empty());
|
||||
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 {
|
||||
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.
|
||||
|
|
@ -750,7 +795,7 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
|
|||
let cap = tuning.select.stimulus_bytes;
|
||||
let mut contacts: Vec<(Option<u64>, String)> = Vec::new();
|
||||
for bond in items(inputs.state, &["affect", "socialBonds"]).iter().filter(|bond| live(bond) && text(bond, &["object", "kind"]) == "person") {
|
||||
let person = text(bond, &["object", "id"]).to_lowercase();
|
||||
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 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();
|
||||
|
|
@ -774,9 +819,7 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
|
|||
if left_out > 0 {
|
||||
out.push(&format!("({left_out} more people {} {} bound to not shown)", her.subj, her.be));
|
||||
}
|
||||
let others: Vec<&RoomLine> = inputs.room.tail.iter().filter(|line| line.sender != inputs.people.own_sender).collect();
|
||||
let shown = &others[others.len().saturating_sub(tuning.select.beat_tail_lines)..];
|
||||
let lines: Vec<String> = shown.iter().map(|line| format!("- {} in {}, {} h ago: {}", name_of(line, inputs), line.room, hours(inputs.now, line.at_ms), spoken(&clip(&line.text, tuning.select.item_bytes / 2)))).collect();
|
||||
let lines: Vec<String> = beat_tail(inputs, tuning).iter().map(|line| format!("- {} in {}, {} h ago: {}", name_of(line, inputs), line.room, hours(inputs.now, line.at_ms), spoken(&clip(&line.text, tuning.select.item_bytes / 2)))).collect();
|
||||
let section = newest_section(&format!("Lately in {} rooms:", her.poss), &lines, cap.saturating_sub(out.out.len() + 2));
|
||||
if !section.is_empty() && out.push("") {
|
||||
out.push(§ion);
|
||||
|
|
@ -784,6 +827,12 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
|
|||
out.out
|
||||
}
|
||||
|
||||
/// The tail lines a beat's stimulus quotes: the newest `beat_tail_lines` of others'.
|
||||
fn beat_tail<'a>(inputs: &'a Inputs, tuning: &Tuning) -> Vec<&'a RoomLine> {
|
||||
let others: Vec<&RoomLine> = inputs.room.tail.iter().filter(|line| line.sender != inputs.people.own_sender).collect();
|
||||
others[others.len().saturating_sub(tuning.select.beat_tail_lines)..].to_vec()
|
||||
}
|
||||
|
||||
fn reflection_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
|
||||
let lines: Vec<String> = items(inputs.state, &["thoughtMemory", "shortTerm"]).iter().filter(|item| live(item)).map(|item| format!("- {}", clip(&one_line(text(item, &["summary"])), tuning.select.item_bytes))).collect();
|
||||
let subj = forms(inputs.state).subj;
|
||||
|
|
@ -813,7 +862,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. What the bond does not carry is left out.
|
||||
fn bond_line(bond: &Value, name: &str, tuning: &Tuning) -> String {
|
||||
fn bond_line(bond: &Value, name: &str, tuning: &Tuning, scope: Scope, her: Forms) -> 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);
|
||||
|
|
@ -822,6 +871,11 @@ fn bond_line(bond: &Value, name: &str, tuning: &Tuning) -> String {
|
|||
let _ = write!(line, " \u{2014} {kind}");
|
||||
}
|
||||
let summary = clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes);
|
||||
let summary = match scope {
|
||||
Scope::Framed if !summary.is_empty() => format!("{} knows privately: {summary}", her.cap_subj),
|
||||
Scope::Omitted => String::new(),
|
||||
_ => summary,
|
||||
};
|
||||
match (feel.is_empty(), summary.is_empty()) {
|
||||
(true, true) => {}
|
||||
(true, false) => {
|
||||
|
|
@ -881,7 +935,7 @@ 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<String> {
|
||||
let person = inputs.people.person_of(sender);
|
||||
items(inputs.state, &["affect", "socialBonds"]).iter().find(|bond| live(bond) && text(bond, &["object", "id"]).to_lowercase() == person).map(|bond| text(bond, &["object", "label"]).to_owned()).filter(|label| !label.is_empty())
|
||||
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())
|
||||
}
|
||||
|
||||
/// The words a line may call its sender by: the Matrix localpart, the display name, and the bond's label when she has one.
|
||||
|
|
@ -893,9 +947,25 @@ fn names_of(line: &RoomLine, inputs: &Inputs) -> Vec<String> {
|
|||
/// once, oldest first. The room is the turn's when it is one room; otherwise the room of the newest message to her, else
|
||||
/// of the newest message, else of the newest tail line. Never several rooms folded into one, so a direct message is
|
||||
/// only ever read as its own room.
|
||||
fn recent_lines<'a>(inputs: &'a Inputs) -> Vec<&'a RoomLine> {
|
||||
/// The turn's room: the one it is in when it is one room; otherwise the room of the newest message to her, else of the
|
||||
/// newest message, else of the newest tail line. Where the packet describes and the only room she may speak in.
|
||||
pub(crate) fn turn_room<'a>(inputs: &'a Inputs) -> Option<&'a str> {
|
||||
let newest = |lines: &'a [RoomLine], keep: &dyn Fn(&RoomLine) -> bool| lines.iter().filter(|line| keep(line)).max_by_key(|line| line.at_ms).map(|line| line.room.as_str());
|
||||
let Some(room) = inputs.room.here.as_deref().or_else(|| newest(&inputs.room.messages, &|line| line.to_her)).or_else(|| newest(&inputs.room.messages, &|_| true)).or_else(|| newest(&inputs.room.tail, &|_| true)) else {
|
||||
inputs.room.here.as_deref().or_else(|| newest(&inputs.room.messages, &|line| line.to_her)).or_else(|| newest(&inputs.room.messages, &|_| true)).or_else(|| newest(&inputs.room.tail, &|_| true))
|
||||
}
|
||||
|
||||
fn room_kind(inputs: &Inputs, room: &str) -> RoomKind {
|
||||
if direct(inputs, room) {
|
||||
RoomKind::Direct
|
||||
} else if inputs.room.own.iter().any(|own| own == room) {
|
||||
RoomKind::Own
|
||||
} else {
|
||||
RoomKind::Public
|
||||
}
|
||||
}
|
||||
|
||||
fn recent_lines<'a>(inputs: &'a Inputs) -> Vec<&'a RoomLine> {
|
||||
let Some(room) = turn_room(inputs) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut lines: Vec<&RoomLine> = Vec::new();
|
||||
|
|
@ -1008,38 +1078,91 @@ fn pronoun_line(inputs: &Inputs, tuning: &Tuning) -> Option<String> {
|
|||
(!parts.is_empty()).then(|| clip(&format!("- pronouns: {}", parts.join("; ")), ALSO_HERE_BYTES))
|
||||
}
|
||||
|
||||
/// How an item's content reaches the packet.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Scope {
|
||||
/// As it is: shared, or private and this is the room where it may be said.
|
||||
Plain,
|
||||
/// "She knows privately: …": private, about someone who is not in the turn's room.
|
||||
Framed,
|
||||
/// Left out: private, and whom it concerns is in the room, or cannot be told apart from who is. Nothing private about
|
||||
/// a person is hinted at to their face.
|
||||
Omitted,
|
||||
}
|
||||
|
||||
/// Whom a private item concerns.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum Concerns {
|
||||
/// One person, keyed as her bonds key people.
|
||||
Person(String),
|
||||
/// The other member of the direct message a `room:!…` tag (or her line's room) names, when no person is named.
|
||||
Partner(String),
|
||||
/// No person named: private about everyone.
|
||||
Everyone,
|
||||
}
|
||||
|
||||
/// Whether an item is private, and whom it concerns: the one owner of that reading, for the bonds and every pool. Private
|
||||
/// is `extensions.privacy` "private", a `private` tag, or a tag naming a direct message (`room:!…`); anything else is
|
||||
/// shared (None). It concerns the person its `target` (a bond's `object`) names when that is a person, else the person
|
||||
/// an `about:` tag names, else the partner of the direct message its room tag names, else everyone. The convention is
|
||||
/// the Persona State Standard's, read without a schema change.
|
||||
fn concerns(people: &People, item: &Value) -> Option<Concerns> {
|
||||
let tags: Vec<&str> = items(item, &["tags"]).iter().filter_map(Value::as_str).collect();
|
||||
let direct = tags.iter().filter_map(|tag| tag.strip_prefix("room:")).find(|room| room.starts_with('!'));
|
||||
if text(item, &["extensions", "privacy"]) != "private" && !tags.contains(&"private") && direct.is_none() {
|
||||
return None;
|
||||
}
|
||||
let named = ["target", "object"].into_iter().find(|key| text(item, &[*key, "kind"]) == "person").map(|key| people.person_of(text(item, &[key, "id"])));
|
||||
let about = || tags.iter().find_map(|tag| tag.strip_prefix("about:")).map(|id| people.person_of(id));
|
||||
Some(match (named.filter(|id| !id.is_empty()).or_else(about).filter(|id| !id.is_empty()), direct) {
|
||||
(Some(person), _) => Concerns::Person(person),
|
||||
(None, Some(room)) => Concerns::Partner(room.to_owned()),
|
||||
(None, None) => Concerns::Everyone,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a room is a direct message: the mouth said so, or it is keyed by a room id, as only a direct message is.
|
||||
fn direct(inputs: &Inputs, room: &str) -> bool {
|
||||
room.starts_with('!') || inputs.room.direct.iter().any(|direct| direct == room)
|
||||
}
|
||||
|
||||
/// Everyone a room's lines show in it but her, keyed as her bonds key people. Matrix tells her body no membership, so a
|
||||
/// member who never spoke in the lines she has is not counted.
|
||||
fn members(inputs: &Inputs, room: &str) -> BTreeSet<String> {
|
||||
inputs.room.messages.iter().chain(&inputs.room.tail).filter(|line| line.room == room && line.sender != inputs.people.own_sender).map(|line| inputs.people.person_of(&line.sender)).collect()
|
||||
}
|
||||
|
||||
/// How an item reaches the packet here, by whom it concerns (`concerns`; None is shared, and plain). Plain only where it
|
||||
/// may be said: about one person, in a direct message with exactly her and that person; about a direct message's
|
||||
/// partner, in that direct message, still only the two of them; about everyone, in a room of her own. Elsewhere it is
|
||||
/// left out when whom it concerns is in the room (everyone always is, and a partner unnamed cannot be told apart), and
|
||||
/// framed as known privately when they are not. Structural: whether a line fits its audience stays the Interpreter's
|
||||
/// judgement.
|
||||
fn scope(inputs: &Inputs, concerns: Option<&Concerns>, present: &BTreeSet<String>) -> Scope {
|
||||
let Some(concerns) = concerns else {
|
||||
return Scope::Plain;
|
||||
};
|
||||
let room = turn_room(inputs);
|
||||
let members = room.map(|room| members(inputs, room)).unwrap_or_default();
|
||||
// The one other person of a direct message that has exactly two members.
|
||||
let with = room.filter(|room| room_kind(inputs, room) == RoomKind::Direct && members.len() == 1).and_then(|_| members.first());
|
||||
match concerns {
|
||||
Concerns::Person(person) if with == Some(person) => Scope::Plain,
|
||||
Concerns::Person(person) if present.contains(person) || members.contains(person) => Scope::Omitted,
|
||||
Concerns::Person(_) => Scope::Framed,
|
||||
Concerns::Partner(dm) if with.is_some() && room == Some(dm.as_str()) => Scope::Plain,
|
||||
Concerns::Everyone if room.is_some_and(|room| room_kind(inputs, room) == RoomKind::Own) => Scope::Plain,
|
||||
Concerns::Partner(_) | Concerns::Everyone => Scope::Omitted,
|
||||
}
|
||||
}
|
||||
|
||||
/// A part as a sentence: its first letter upper-cased, a full stop after it.
|
||||
fn sentence(part: &str) -> String {
|
||||
let mut chars = part.chars();
|
||||
chars.next().map_or_else(String::new, |first| format!("{}{}.", first.to_uppercase(), chars.as_str()))
|
||||
}
|
||||
|
||||
/// Whom the Interpreter may address: everyone the packet shows from the room, then the swarm's other Minds, who are in
|
||||
/// her rooms whether or not they spoke; a Mind she is bound to goes by the bond's label, any other by the id alone.
|
||||
fn addressable(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, String)> {
|
||||
let mut people = people_in_view(inputs, tuning);
|
||||
for mind in inputs.people.minds.iter().filter(|mind| *mind != inputs.people.own_sender) {
|
||||
if !people.iter().any(|(_, id)| id == mind) {
|
||||
people.push((bond_label(inputs, mind).unwrap_or_else(|| mind.clone()), mind.clone()));
|
||||
}
|
||||
}
|
||||
people
|
||||
}
|
||||
|
||||
fn speaking_rooms(inputs: &Inputs) -> Vec<String> {
|
||||
let mut rooms: Vec<String> = inputs.room.here.iter().cloned().collect();
|
||||
for line in &inputs.room.messages {
|
||||
if !rooms.contains(&line.room) {
|
||||
rooms.push(line.room.clone());
|
||||
}
|
||||
}
|
||||
if rooms.is_empty()
|
||||
&& let Some(line) = recent_lines(inputs).last()
|
||||
{
|
||||
rooms.push(line.room.clone());
|
||||
}
|
||||
rooms
|
||||
}
|
||||
|
||||
/// The pronouns of a person nobody listed.
|
||||
const UNKNOWN_PRONOUNS: &str = "they/them";
|
||||
|
|
@ -1072,16 +1195,21 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
|
|||
let mut used: usize = fixed.iter().map(|line| line.len() + 1).sum();
|
||||
let mut ids = Vec::new();
|
||||
let mut named = Vec::new();
|
||||
let mut private = Vec::new();
|
||||
let mut full = 0;
|
||||
for (id, name) in &present {
|
||||
match bonds.iter().find(|bond| live(bond) && text(bond, &["object", "id"]).to_lowercase() == *id) {
|
||||
match bonds.iter().find(|bond| live(bond) && inputs.people.person_of(text(bond, &["object", "id"])) == *id) {
|
||||
Some(bond) if full < tuning.select.people_full => {
|
||||
let line = bond_line(bond, name, tuning);
|
||||
let scope = scope(inputs, concerns(&inputs.people, bond).as_ref(), &present_ids);
|
||||
let line = bond_line(bond, name, tuning, scope, forms(inputs.state));
|
||||
if used + line.len() < budget {
|
||||
full += 1;
|
||||
used += line.len() + 1;
|
||||
ids.push(text(bond, &["id"]).to_owned());
|
||||
fixed.push(line);
|
||||
if scope == Scope::Framed && !text(bond, &["summary"]).is_empty() {
|
||||
private.push(one_line(text(bond, &["summary"])));
|
||||
}
|
||||
} else {
|
||||
named.push(name.clone());
|
||||
}
|
||||
|
|
@ -1138,6 +1266,12 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
|
|||
let mut lines = fixed;
|
||||
lines.extend(taken.iter().map(|candidate| candidate.line.clone()));
|
||||
ids.extend(taken.iter().map(|candidate| candidate.id.clone()));
|
||||
private.extend(taken.iter().filter_map(|candidate| candidate.private.clone()));
|
||||
let bodies = match inputs.kind {
|
||||
TurnKind::Chat => inputs.room.messages.iter().map(|line| line.text.clone()).collect(),
|
||||
TurnKind::Beat => beat_tail(inputs, tuning).iter().map(|line| line.text.clone()).collect(),
|
||||
TurnKind::FollowUp | TurnKind::Reflection => Vec::new(),
|
||||
};
|
||||
let selected = taken.into_iter().map(|candidate| Pick { id: candidate.id, pool: candidate.pool, log_score: candidate.log_score }).collect();
|
||||
Packet { kind: inputs.kind, seed: inputs.seed, lens, identity, context: lines.join("\n"), stimulus, heard, overflow, present: present_names, ids, selected, forms: forms(inputs.state), people: addressable(inputs, tuning), rooms: speaking_rooms(inputs) }
|
||||
Packet { kind: inputs.kind, seed: inputs.seed, lens, identity, context: lines.join("\n"), stimulus, heard, overflow, present: present_names, ids, selected, forms: forms(inputs.state), people: people_in_view(inputs, tuning), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), bodies, private }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,8 +4,13 @@
|
|||
//!
|
||||
//! Who wakes is the heartbeat's: `heartbeat::wakes` under the plan's `WakePolicy`, over each persona's addressee as the
|
||||
//! heartbeat's addressing table holds it (her stewarded projects' names included) when the plan names the table. The
|
||||
//! beat is the heartbeat's too: when it falls, one Persona wakes, the winner of `tempo::pick`. Those woken in one round
|
||||
//! go in an order drawn from the seed, each against the room as it stands at her turn.
|
||||
//! beat is the heartbeat's too: when it falls, one Persona wakes, the winner of `tempo::pick`. Who wakes in a round is
|
||||
//! decided from the room as the round opens, as one heartbeat poll decides from the pending it read: a line spoken by a
|
||||
//! turn of this round wakes no one, and counts toward a cap, only from the next round. A persona takes at most one turn
|
||||
//! a round, as the live heartbeat never starts a Mind whose unit is still running: in the room of her earliest waking
|
||||
//! line. She reads only that room, and only that room is marked seen, so a line in another room that woke her wakes
|
||||
//! her again next round: no line is seen without a turn that read it. The turns of a round go in an order drawn from
|
||||
//! the seed, each against the room as it stands at that turn.
|
||||
//!
|
||||
//! Her state does not move during a run: the Interpreter (C3b) and the commit (C3c) are not built. `state_after_turn`
|
||||
//! is the seam where they will. An explicit addressee (the Interpreter naming whom she speaks to) cannot be simulated
|
||||
|
|
@ -111,17 +116,24 @@ struct Member {
|
|||
rooms: Vec<String>,
|
||||
}
|
||||
|
||||
/// One persona's view of the room at her turn: the lines since her last turn are new.
|
||||
/// Per room, how many lines she had seen when a turn of hers last read it: a line at or past that is new to her.
|
||||
type Seen = BTreeMap<String, usize>;
|
||||
|
||||
fn unseen(seen: &Seen, lines: &[Line], at: usize) -> bool {
|
||||
at >= seen.get(&lines[at].room).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// One persona's view of the room at her turn: the lines she has not seen are new.
|
||||
struct View<'a> {
|
||||
lines: &'a [Line],
|
||||
viewer: &'a str,
|
||||
rooms: &'a [String],
|
||||
seen: usize,
|
||||
seen: &'a Seen,
|
||||
}
|
||||
|
||||
impl MouthReader for View<'_> {
|
||||
fn pending(&self) -> Result<ChatPending> {
|
||||
Ok(pending_for(self.lines, self.viewer, self.rooms, |at| at >= self.seen))
|
||||
Ok(pending_for(self.lines, self.viewer, self.rooms, |at| unseen(self.seen, self.lines, at)))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -151,15 +163,24 @@ fn speaker(line: &Line, member: &Member, operators: &[String], cast: &[String])
|
|||
}
|
||||
}
|
||||
|
||||
/// For each line, how many Mind lines in a row came before it in its room since a human last spoke there.
|
||||
/// For each line, how many Mind lines in a row came before it in her current Mind-only run: one run across every room
|
||||
/// she sees, which a human's line ends only when it is in a room the run has lines in. Meta chatting in #eureka does not
|
||||
/// end a loop in #minds.
|
||||
fn mind_runs(lines: &[Line], cast: &[String], member: &Member) -> Vec<usize> {
|
||||
let mut run = 0usize;
|
||||
let mut run_rooms: Vec<&str> = Vec::new();
|
||||
lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
let before = run;
|
||||
if line.visible_to(&member.entry.id, &member.rooms) {
|
||||
run = if cast.contains(&line.from) { run + 1 } else { 0 };
|
||||
if cast.contains(&line.from) {
|
||||
run += 1;
|
||||
run_rooms.push(&line.room);
|
||||
} else if run_rooms.contains(&line.room.as_str()) {
|
||||
run = 0;
|
||||
run_rooms.clear();
|
||||
}
|
||||
}
|
||||
before
|
||||
})
|
||||
|
|
@ -183,23 +204,26 @@ fn how_addressed(line: &Line, at: usize, member: &Member, lines: &[Line]) -> &'s
|
|||
/// it, the strongest evidence that addressed her and the lines that did.
|
||||
struct Woken {
|
||||
cause: WakeCause,
|
||||
/// The newest line with that cause: its room is the turn's room.
|
||||
line: usize,
|
||||
how: Option<&'static str>,
|
||||
by: Vec<Value>,
|
||||
}
|
||||
|
||||
/// Whether she spoke in the exchange a line continues: walking back through the lines of its room while each is within
|
||||
/// `gap` of the one after it.
|
||||
/// Whether she is in the exchange a line belongs to: she spoke in its room within `window` before it.
|
||||
fn in_exchange(lines: &[Line], at: usize, her: &str, window: Duration) -> bool {
|
||||
let line = &lines[at];
|
||||
let since = line.at_ms.saturating_sub(u64::try_from(window.num_milliseconds()).unwrap_or(0));
|
||||
lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.from == her && earlier.at_ms >= since)
|
||||
}
|
||||
|
||||
/// Her wake, if a line she has not seen wakes her: in the room of the earliest such line, with the strongest cause among
|
||||
/// that room's waking lines.
|
||||
#[allow(clippy::too_many_arguments, reason = "one wake decision's inputs, each a plan or room fact")]
|
||||
fn woken(lines: &[Line], runs: &[usize], seen: usize, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy, gap: Duration) -> Option<Woken> {
|
||||
fn woken(lines: &[Line], runs: &[usize], seen: &Seen, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy, gap: Duration) -> Option<Woken> {
|
||||
let mut found: Vec<(usize, WakeCause)> = Vec::new();
|
||||
for (at, line) in lines.iter().enumerate().skip(seen) {
|
||||
if !line.visible_to(&member.entry.id, &member.rooms) {
|
||||
for (at, line) in lines.iter().enumerate() {
|
||||
if !unseen(seen, lines, at) || !line.visible_to(&member.entry.id, &member.rooms) {
|
||||
continue;
|
||||
}
|
||||
let delivery = line.delivery(at, &member.entry.id, lines);
|
||||
|
|
@ -208,15 +232,18 @@ fn woken(lines: &[Line], runs: &[usize], seen: usize, member: &Member, operators
|
|||
found.push((at, cause));
|
||||
}
|
||||
}
|
||||
let room = &lines[found.first()?.0].room;
|
||||
found.retain(|(at, _)| lines[*at].room == *room);
|
||||
let cause = found.iter().map(|(_, cause)| *cause).min()?;
|
||||
let line = found.iter().rev().find(|(_, found)| *found == cause).map_or(0, |(at, _)| *at);
|
||||
if cause != WakeCause::AddressedByMind {
|
||||
return Some(Woken { cause, how: None, by: vec![] });
|
||||
return Some(Woken { cause, line, how: None, by: vec![] });
|
||||
}
|
||||
let addressing: Vec<usize> = found.iter().filter(|(_, cause)| *cause == WakeCause::AddressedByMind).map(|(at, _)| *at).collect();
|
||||
let rank = |how: &str| ["mention or reply", "id as text", "name in text"].iter().position(|one| *one == how).unwrap_or(3);
|
||||
let how = addressing.iter().map(|at| how_addressed(&lines[*at], *at, member, lines)).min_by_key(|how| rank(how));
|
||||
let by = addressing.iter().map(|at| json!({ "from": lines[*at].from, "how": how_addressed(&lines[*at], *at, member, lines), "says": lines[*at].says })).collect();
|
||||
Some(Woken { cause, how, by })
|
||||
Some(Woken { cause, line, how, by })
|
||||
}
|
||||
|
||||
/// The wire spelling of a cause, and of the beat.
|
||||
|
|
@ -313,7 +340,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
|
|||
};
|
||||
scripted(0, &mut lines, &mut rounds_of, &mut causes)?;
|
||||
let opening = lines.len();
|
||||
let mut seen = vec![0usize; members.len()];
|
||||
let mut seen: Vec<Seen> = vec![Seen::new(); members.len()];
|
||||
let mut last_turn: Vec<Option<DateTime<Utc>>> = vec![None; members.len()];
|
||||
let mut last_beat = plan.start;
|
||||
let mut recent: Vec<Vec<Vec<String>>> = vec![Vec::new(); members.len()];
|
||||
|
|
@ -322,7 +349,8 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
|
|||
for round in 1..=plan.rounds {
|
||||
scripted(round, &mut lines, &mut rounds_of, &mut causes)?;
|
||||
let round_at = at_round(round);
|
||||
let mut woke: Vec<(usize, Option<Woken>)> = members.iter().enumerate().filter_map(|(at, member)| woken(&lines, &mind_runs(&lines, &cast, member), seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_minutes)).map(|why| (at, Some(why)))).collect();
|
||||
// Decided from the room as the round opens, as a poll decides from the pending it read.
|
||||
let mut woke: Vec<(usize, Option<Woken>)> = members.iter().enumerate().filter_map(|(at, member)| woken(&lines, &mind_runs(&lines, &cast, member), &seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_minutes)).map(|why| (at, Some(why)))).collect();
|
||||
// The beat, as the heartbeat's: when it has fallen, one more wake for the winner of `tempo::pick` among those
|
||||
// not already woken.
|
||||
if plan.beat_s > 0 && (round_at - last_beat).num_seconds() >= i64::from(plan.beat_s) {
|
||||
|
|
@ -335,7 +363,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
|
|||
waited_s: last_turn[at].map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)),
|
||||
last_turn_ms: last_turn[at].map(|turn| turn.timestamp_millis()),
|
||||
topic_permille: 0,
|
||||
addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| index >= seen[at]).deliveries),
|
||||
addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| unseen(&seen[at], &lines, index)).deliveries),
|
||||
})
|
||||
.collect();
|
||||
if let Some(winner) = pick(&standings, plan.beat_s) {
|
||||
|
|
@ -347,12 +375,13 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
|
|||
counter += 1;
|
||||
let member = &members[at];
|
||||
let id = member.entry.id.clone();
|
||||
let fresh: Vec<&Line> = lines[seen[at]..].iter().filter(|line| line.from != id && line.visible_to(&id, &member.rooms)).collect();
|
||||
let woke_on = fresh.iter().rev().find(|line| line.mentions.contains(&id) || line.dm_to.as_deref() == Some(id.as_str())).or(fresh.last()).copied();
|
||||
let fresh: Vec<&Line> = lines.iter().enumerate().filter(|(index, line)| unseen(&seen[at], &lines, *index) && line.from != id && line.visible_to(&id, &member.rooms)).map(|(_, line)| line).collect();
|
||||
// The turn is in the room of the line that woke her; a beat's, in the room of the newest line she has not seen.
|
||||
let woke_on = why.as_ref().map(|why| &lines[why.line]).or(fresh.last().copied());
|
||||
let here = woke_on.map_or_else(|| member.rooms[0].clone(), |line| line.room.clone());
|
||||
// Woken by a direct message, she answers in it: to its sender alone.
|
||||
let dm_to = woke_on.filter(|line| line.dm_to.as_deref() == Some(id.as_str())).map(|line| line.from.clone());
|
||||
let kind = if fresh.is_empty() { TurnKind::Beat } else { TurnKind::Chat };
|
||||
let kind = if fresh.iter().any(|line| line.room == here) { TurnKind::Chat } else { TurnKind::Beat };
|
||||
let now = round_at + Duration::seconds(30 + counter as i64);
|
||||
let request = Request {
|
||||
instance: localpart(&id).to_owned(),
|
||||
|
|
@ -369,12 +398,14 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
|
|||
through: Through::Interpreter,
|
||||
last_heard: vec![],
|
||||
recent: recent[at].clone(),
|
||||
own_rooms: member.entry.own_rooms.clone(),
|
||||
};
|
||||
let view = View { lines: &lines, viewer: &id, rooms: &member.rooms, seen: seen[at] };
|
||||
let view = View { lines: &lines, viewer: &id, rooms: &member.rooms, seen: &seen[at] };
|
||||
let names = Names(&member.addressee);
|
||||
let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model };
|
||||
let report = project(&organs, &request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") }));
|
||||
seen[at] = lines.len();
|
||||
// Only the room she read is seen.
|
||||
seen[at].insert(here.clone(), lines.len());
|
||||
last_turn[at] = Some(now);
|
||||
let render = &report["renders"][0];
|
||||
if let Some(selected) = render["selected"].as_array() {
|
||||
|
|
@ -556,8 +587,8 @@ fn policy_words(policy: WakePolicy) -> String {
|
|||
match policy {
|
||||
WakePolicy::Live => "live: the operator or another Mind addressing her (the heartbeat's rule today)".into(),
|
||||
WakePolicy::Ruled => "ruled: a line addressing her, from anyone, and any human line in her rooms".into(),
|
||||
WakePolicy::HumansPace(cap) => format!("humans_pace (cap {cap}): a human's line wakes a Mind in her own room always, and in a public room when it addresses her or continues an exchange she is in; a Mind's line wakes another only by an explicit mention or a reply, while fewer than {cap} Mind lines in a row came before it in its room, never by a name in prose"),
|
||||
WakePolicy::NamesWithCap(cap) => format!("names_with_cap {cap}: ruled, but a Mind's line past {cap} Mind lines in a row in its room wakes no one until a human speaks"),
|
||||
WakePolicy::HumansPace(cap) => format!("humans_pace (cap {cap}): a human's line wakes a Mind in her own room always, and in a public room when it addresses her or continues an exchange she is in; a Mind's line wakes another only by an explicit mention or a reply, while her current Mind-only run, across her rooms, is under {cap} lines, never by a name in prose"),
|
||||
WakePolicy::NamesWithCap(cap) => format!("names_with_cap {cap}: ruled, but a Mind's line wakes no one once her current Mind-only run, across her rooms, has {cap} lines, until a human speaks where it runs"),
|
||||
WakePolicy::AllMessages => "all_messages: any line in her rooms, a Mind's too (the old loop, the control)".into(),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::Value;
|
||||
|
|
@ -59,9 +60,9 @@ fn is_tobiah(prompt: &str) -> bool {
|
|||
prompt.contains("Who you are:\nTobiah")
|
||||
}
|
||||
|
||||
/// Both speak every turn, neither naming the other.
|
||||
/// Both speak every turn, neither naming the other: each line a standalone quotation, sayable.
|
||||
fn chatty() -> Scripted {
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "\"what a day\" he says".into() } else { "\"mm, the deploy went fine\" she says".into() })
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "\"what a day\"".into() } else { "\"mm, the deploy went fine\"".into() })
|
||||
}
|
||||
|
||||
/// Both speak every turn, each naming the other.
|
||||
|
|
@ -243,27 +244,34 @@ fn a_seed_replays_its_order_and_another_seed_changes_it() {
|
|||
fn tagging(mention: bool) -> Scripted {
|
||||
let mentions = if mention { json!([LIBBY]) } else { json!([]) };
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "\"ask @libby:gamecult.org, and Libby too\"".into() } else { "She lets it be.".into() }).interpreting(move |prompt| {
|
||||
if !prompt.contains("Identity:\nTobiah") {
|
||||
if !prompt.contains("Who she is:\nTobiah") {
|
||||
return json!({ "say": [] }).to_string();
|
||||
}
|
||||
json!({ "say": [{ "room": "#minds:gamecult.org", "text": "ask @libby:gamecult.org, and Libby too", "source_quote": "ask @libby:gamecult.org, and Libby too", "mentions": mentions, "reply_to": null }] }).to_string()
|
||||
json!({ "say": [{ "spans": ["ask @libby:gamecult.org, and Libby too"], "mentions": mentions, "reply_to": null }] }).to_string()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_interpreters_structured_mention_is_a_mention_and_an_at_in_the_text_is_not() {
|
||||
// Libby says hello first, so the packet shows her to Tobiah: a mention reaches only someone shown.
|
||||
let hello = "[[message]]\nround = 0\nfrom = \"@libby:gamecult.org\"\nname = \"Libby\"\nroom = \"#minds:gamecult.org\"\nsays = \"hello all\"\n";
|
||||
let plan = |dir: &Path, wake: &str, rounds: usize| {
|
||||
let path = plan(dir, wake, rounds, "");
|
||||
std::fs::write(&path, format!("{}{hello}", std::fs::read_to_string(&path).unwrap())).unwrap();
|
||||
path
|
||||
};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, plain) = run_plan(&plan(dir.path(), "\"ruled\"", 3, ""), &tagging(false));
|
||||
let (_, plain) = run_plan(&plan(dir.path(), "\"ruled\"", 3), &tagging(false));
|
||||
let addressed = &plain["metrics"]["mind_addressed_wakes"];
|
||||
assert_eq!(addressed["mention_or_reply"].as_u64(), Some(0), "an @id in the words tags no one: {addressed}");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, tagged) = run_plan(&plan(dir.path(), "\"ruled\"", 3, ""), &tagging(true));
|
||||
let (_, tagged) = run_plan(&plan(dir.path(), "\"ruled\"", 3), &tagging(true));
|
||||
let addressed = &tagged["metrics"]["mind_addressed_wakes"];
|
||||
let libby_mind_wakes = turns(&tagged).iter().filter(|(_, who, why)| who == "Libby" && why == "addressed_by_mind").count();
|
||||
assert_eq!(addressed["mention_or_reply"].as_u64().unwrap() as usize, libby_mind_wakes, "{addressed}");
|
||||
// Under humans_pace a name or an @ in the words wakes no one; the structured mention does.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = plan(dir.path(), "{ humans_pace = 4 }", 3, "");
|
||||
let path = plan(dir.path(), "{ humans_pace = 4 }", 3);
|
||||
let opening = "says = \"good afternoon, everyone\"\n";
|
||||
std::fs::write(&path, std::fs::read_to_string(&path).unwrap().replace(opening, &format!("{opening}mentions = [\"{TOBIAH}\"]\n"))).unwrap();
|
||||
let woken_libby = |model: &Scripted| turns(&run_plan(&path, model).1).iter().any(|(_, who, _)| who == "Libby");
|
||||
|
|
@ -284,14 +292,18 @@ fn a_direct_message_in_one_of_the_plans_rooms_is_refused() {
|
|||
|
||||
#[test]
|
||||
fn the_mind_run_is_counted_across_her_rooms_and_an_uncounted_run_is_at_the_cap() {
|
||||
let her = Member { names_from: "test", addressee: Addressee::new(LIBBY, ["libby"]), entry: CastEntry { id: LIBBY.into(), name: "Libby".into(), state: PathBuf::new(), rooms: vec![], own_rooms: vec![] }, state: Value::Null, rooms: vec!["#a:x".into(), "#b:x".into()] };
|
||||
let cast = vec![TOBIAH.to_owned(), LIBBY.to_owned(), "@kiko:x".to_owned()];
|
||||
let her = Member { names_from: "test", addressee: Addressee::new("@kiko:x", ["kiko"]), entry: CastEntry { id: "@kiko:x".into(), name: "Kiko".into(), state: PathBuf::new(), rooms: vec![], own_rooms: vec![] }, state: Value::Null, rooms: vec!["#a:x".into(), "#b:x".into()] };
|
||||
let cast = vec![TOBIAH.to_owned(), LIBBY.to_owned(), "@kiko:x".to_owned(), "@other:x".to_owned()];
|
||||
let line = |from: &str, room: &str| Line { from: from.into(), name: String::new(), room: room.into(), at_ms: 0, says: "hi".into(), mentions: vec![], dm_to: None, follow_up: false, reply_to: None, new: false };
|
||||
let lines = [line("@meta:x", "#a:x"), line(TOBIAH, "#a:x"), line("@kiko:x", "#b:x"), line(TOBIAH, "#b:x"), line("@meta:x", "#c:x")];
|
||||
let lines = [line("@meta:x", "#a:x"), line(TOBIAH, "#a:x"), line("@other:x", "#b:x"), line(TOBIAH, "#b:x"), line("@meta:x", "#c:x")];
|
||||
assert_eq!(mind_runs(&lines, &cast, &her), vec![0, 0, 1, 2, 3], "one run across #a and #b; a room she is not in does not break it");
|
||||
// Soul's case: Meta chatting in #eureka does not end a loop in #minds; a word from Meta in #minds does.
|
||||
let kiko = Member { rooms: vec!["#minds:x".into(), "#eureka:x".into()], ..her };
|
||||
let lines = [line(TOBIAH, "#minds:x"), line(LIBBY, "#minds:x"), line("@meta:x", "#eureka:x"), line(TOBIAH, "#minds:x"), line("@meta:x", "#minds:x"), line(LIBBY, "#minds:x")];
|
||||
assert_eq!(mind_runs(&lines, &cast, &kiko), vec![0, 1, 2, 2, 3, 0]);
|
||||
assert_eq!(LineFacts::default().mind_run, usize::MAX, "fail-safe: an uncounted run is at the cap");
|
||||
let tagged = Line { mentions: vec![LIBBY.into()], ..line(TOBIAH, "#a:x") };
|
||||
assert_eq!(wakes(WakePolicy::HumansPace(4), &her.addressee, &tagged.delivery(0, LIBBY, &[]), Speaker::Mind, LineFacts::default()), None);
|
||||
let tagged = Line { mentions: vec!["@kiko:x".into()], ..line(TOBIAH, "#a:x") };
|
||||
assert_eq!(wakes(WakePolicy::HumansPace(4), &kiko.addressee, &tagged.delivery(0, "@kiko:x", &[]), Speaker::Mind, LineFacts::default()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -333,3 +345,72 @@ fn a_scripted_direct_message_reaches_and_wakes_only_its_recipient() {
|
|||
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
|
||||
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("name its recipient"), "a direct message without a recipient is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_turn_is_in_the_room_of_the_line_that_woke_her() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
cast(dir.path());
|
||||
let path = dir.path().join("plan.toml");
|
||||
let line = |round: usize, from: &str, room: &str, says: &str| format!("[[message]]\nround = {round}\nfrom = \"{from}\"\nname = \"X\"\nroom = \"{room}\"\nsays = \"{says}\"\n");
|
||||
// Meta speaks in Tobiah's own room, then Libby says something in #minds after it: Tobiah's turn is in his room.
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"rounds = 1\nseed = 11\nwake = {{ humans_pace = 4 }}\nbeat_s = 0\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#minds:gamecult.org\", \"#tobiah:gamecult.org\"]\noperators = [\"@meta:gamecult.org\"]\n[[cast]]\nid = \"{TOBIAH}\"\nname = \"Tobiah\"\nstate = \"tobiah.json\"\nown_rooms = [\"#tobiah:gamecult.org\"]\n[[cast]]\nid = \"{LIBBY}\"\nname = \"Libby\"\nstate = \"libby.json\"\n{}{}",
|
||||
line(0, "@meta:gamecult.org", "#tobiah:gamecult.org", "quiet in here"),
|
||||
line(0, LIBBY, "#minds:gamecult.org", "hello all")
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let (_, run) = run_plan(&path, &silent());
|
||||
assert_eq!(run["turns"][0]["room"], "#tobiah:gamecult.org", "{}", run["turns"]);
|
||||
}
|
||||
|
||||
/// Each persona's turns, as (round, room), in order.
|
||||
fn turns_by_persona(run: &Value) -> BTreeMap<String, Vec<(u64, String)>> {
|
||||
let mut out: BTreeMap<String, Vec<(u64, String)>> = BTreeMap::new();
|
||||
for turn in run["turns"].as_array().unwrap() {
|
||||
out.entry(turn["persona"].as_str().unwrap().to_owned()).or_default().push((turn["round"].as_u64().unwrap(), turn["room"].as_str().unwrap().to_owned()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f5_one_turn_a_round_and_a_room_that_woke_her_waits_for_the_next() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = plan(dir.path(), "\"ruled\"", 2, "");
|
||||
let line = |room: &str, dm: bool, says: &str| format!("[[message]]\nround = 1\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\n{}says = \"{says}\"\n", if dm { "dm = true\nto = \"@libby:gamecult.org\"\n" } else { "" });
|
||||
let opening = "[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nsays = \"good afternoon, everyone\"\n";
|
||||
let text = std::fs::read_to_string(&path).unwrap().replace(opening, &format!("{}{}", line("!dm-libby:gamecult.org", true, "just you: how are you, really?"), line("#minds:gamecult.org", false, "Libby, how was the gig?")));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let (_, run) = run_plan(&path, &silent());
|
||||
// Her earliest waking line is the direct message: round 1 is there; #minds, still unseen, wakes her in round 2.
|
||||
assert_eq!(turns_by_persona(&run)["Libby"], vec![(1, "!dm-libby:gamecult.org".to_owned()), (2, "#minds:gamecult.org".to_owned())], "{}", run["turns"]);
|
||||
// Each turn read its own room's line, and no other's.
|
||||
for turn in run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Libby") {
|
||||
let report = turn["report"].to_string();
|
||||
let (own, other) = if turn["room"] == "#minds:gamecult.org" { ("how was the gig", "how are you, really") } else { ("how are you, really", "how was the gig") };
|
||||
assert!(report.contains(own) && !report.contains(other), "{}: {report}", turn["room"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f5_three_rooms_open_at_once_take_three_rounds_not_one() {
|
||||
for wake in ["\"ruled\"", "{ names_with_cap = 2 }"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = plan(dir.path(), wake, 6, "");
|
||||
let more = |room: &str, says: &str| format!("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\nsays = \"{says}\"\n");
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.unwrap()
|
||||
.replace("rooms = [\"#minds:gamecult.org\"]", "rooms = [\"#minds:gamecult.org\", \"#lab:gamecult.org\", \"#ops:gamecult.org\"]")
|
||||
.replace("says = \"good afternoon, everyone\"\n", &format!("says = \"good afternoon, everyone\"\n{}{}", more("#lab:gamecult.org", "lab is open"), more("#ops:gamecult.org", "ops is open")));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let (_, run) = run_plan(&path, &namers());
|
||||
for (who, turns) in turns_by_persona(&run) {
|
||||
let rounds: Vec<u64> = turns.iter().map(|(round, _)| *round).collect();
|
||||
assert!(rounds.windows(2).all(|pair| pair[0] < pair[1]), "{wake}: {who} took two turns in one round: {turns:?}");
|
||||
let rooms: Vec<&str> = turns.iter().take(3).map(|(_, room)| room.as_str()).collect();
|
||||
assert_eq!(rooms, ["#minds:gamecult.org", "#lab:gamecult.org", "#ops:gamecult.org"], "{wake}: {who} answers each room in the order it opened");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -187,12 +187,32 @@ fn mission_pressure_private_notes_and_candidate_actions_never_reach_a_packet() {
|
|||
}
|
||||
}
|
||||
|
||||
const DERU: &str = "@deru:gamecult.org";
|
||||
const DM_DERU: &str = "!dm-deru:gamecult.org";
|
||||
|
||||
/// The line the `dm-secret` memory renders as over seeds 1 to 40, if any.
|
||||
fn dm_secret(state: &Value, room: &Room) -> Option<String> {
|
||||
(1..=40).find_map(|seed| packet_of(TurnKind::Chat, state, room, &History::default(), seed).context.lines().find(|line| line.starts_with("- memory [dm-secret]")).map(str::to_owned))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direct_message_memory_stays_in_its_room() {
|
||||
let shown = |room: Option<&str>| (1..=40).any(|seed| ids(&packet_of(TurnKind::Chat, &state(), &Room { here: room.map(str::to_owned), ..chat_room() }, &History::default(), seed)).iter().any(|id| id == "dm-secret"));
|
||||
assert!(!shown(Some("#swarm:gamecult.org")), "a public room never sees the direct message's memory");
|
||||
assert!(!shown(None));
|
||||
assert!(shown(Some("!dm-deru:gamecult.org")), "its own room may");
|
||||
fn a_direct_message_memory_is_private_about_its_partner() {
|
||||
// Its `room:` tag marks it private; its target names Deru by his full Matrix id, as an unbonded person is keyed.
|
||||
let mut named = state();
|
||||
named["thoughtMemory"]["memories"][2]["target"]["id"] = DERU.into();
|
||||
let with_deru = Room { messages: vec![message(DM_DERU, DERU, "Deru", "so, the move", 2, true)], here: Some(DM_DERU.into()), direct: vec![DM_DERU.into()], ..Room::default() };
|
||||
assert_eq!(dm_secret(&named, &with_deru).as_deref(), Some("- memory [dm-secret]: Deru told her about the move, privately."), "plain in the direct message with exactly him");
|
||||
assert_eq!(dm_secret(&named, &chat_room()).as_deref(), Some("- memory [dm-secret]: she knows privately: Deru told her about the move, privately."), "framed where he is not");
|
||||
let deru_in_public = Room { messages: vec![message("#swarm:gamecult.org", DERU, "Deru", "hi all", 2, false)], ..chat_room() };
|
||||
assert_eq!(dm_secret(&named, &deru_in_public), None, "left out where he is, in public");
|
||||
// Naming no person, it concerns the direct message's partner, whom no other room can tell apart: left out
|
||||
// everywhere but that direct message, and there still only the two of them.
|
||||
let mut partner = state();
|
||||
partner["thoughtMemory"]["memories"][2].as_object_mut().unwrap().remove("target");
|
||||
assert!(dm_secret(&partner, &with_deru).is_some_and(|line| !line.contains("privately:")));
|
||||
assert_eq!(dm_secret(&partner, &chat_room()), None);
|
||||
let three = Room { messages: [with_deru.messages.clone(), vec![message(DM_DERU, "@libby:gamecult.org", "Libby", "me too", 1, true)]].concat(), ..with_deru.clone() };
|
||||
assert_eq!(dm_secret(&partner, &three), None, "a third person in the direct message");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -665,7 +685,7 @@ impl PersonaSource for Stored {
|
|||
}
|
||||
|
||||
fn request(dir: &std::path::Path, renders: Option<usize>, judge_against: Option<Value>) -> Request {
|
||||
Request { instance: INSTANCE.into(), kind: TurnKind::Chat, state: None, room: Some("#swarm:gamecult.org".into()), seed: 5, renders, judge_against, operators: operators(), minds: minds(), own_sender: OWN.into(), tuning: dir.join(TUNING_FILE), through: Through::Projector, last_heard: vec![], recent: vec![] }
|
||||
Request { instance: INSTANCE.into(), kind: TurnKind::Chat, state: None, room: Some("#swarm:gamecult.org".into()), seed: 5, renders, judge_against, operators: operators(), minds: minds(), own_sender: OWN.into(), tuning: dir.join(TUNING_FILE), through: Through::Projector, last_heard: vec![], recent: vec![], own_rooms: vec![] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1412,3 +1432,141 @@ fn a_room_is_named_by_the_key_the_tail_carries_and_a_public_rooms_id_is_reported
|
|||
let by_id = project(&organs, &Request { room: Some("!1:gamecult.org".into()), ..request(dir.path(), None, None) }, now()).unwrap();
|
||||
assert!(by_id["room"]["why"].as_str().unwrap().contains("named by its alias"), "{}", by_id["room"]);
|
||||
}
|
||||
|
||||
/// The test state with Kiko's bond and the memory about Libby marked private, and the operator's bond not.
|
||||
fn marked() -> Value {
|
||||
let mut marked = state();
|
||||
marked["affect"]["socialBonds"][1]["extensions"] = json!({ "privacy": "private" });
|
||||
marked["thoughtMemory"]["memories"][1]["tags"] = json!(["private"]);
|
||||
marked
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_marking_frames_a_fact_about_someone_absent_and_an_unmarked_one_renders_plainly() {
|
||||
// Libby is not here; Kiko and the operator are not either: only Meta speaks in #minds.
|
||||
let public = Room { messages: vec![message("#minds:gamecult.org", OPERATOR, "Meta", "how is everyone?", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
let shown = |seed| packet_of(TurnKind::Chat, &marked(), &public, &History::default(), seed).context;
|
||||
let memory = (1..=40).map(shown).find(|context| context.contains("[libby-sounds]")).expect("the memory about Libby is selected on some seed");
|
||||
assert!(memory.contains("- memory [libby-sounds]: she knows privately: Libby laughed at the door fix."), "{memory}");
|
||||
let context = shown(1);
|
||||
assert!(context.contains("The operator rules on what the work is for.") && !context.contains("knows privately: The operator"), "an unmarked bond is plain: {context}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_fact_about_someone_present_in_public_is_left_out_and_plain_in_a_direct_message_with_them() {
|
||||
// Kiko is here, in #minds: her marked bond's summary is left out, and no hint of it remains.
|
||||
let public = Room { messages: vec![message("#minds:gamecult.org", "@kiko:gamecult.org", "Kiko", "afternoon", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &marked(), &public, &History::default(), 1);
|
||||
let line = packet.context.lines().find(|line| line.starts_with("- bond [bond-kiko]")).unwrap_or_else(|| panic!("{}", packet.context)).to_owned();
|
||||
assert!(!line.contains("massaging the pipeline") && !line.contains("privately"), "{line}");
|
||||
// In a direct message with Kiko it is plain.
|
||||
let dm = Room { messages: vec![message("!dm-kiko:gamecult.org", "@kiko:gamecult.org", "Kiko", "hey", 2, true)], here: Some("!dm-kiko:gamecult.org".into()), direct: vec!["!dm-kiko:gamecult.org".into()], ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &marked(), &dm, &History::default(), 1);
|
||||
assert!(packet.context.contains("Kiko pokes her to stop massaging the pipeline.") && !packet.context.contains("privately"), "{}", packet.context);
|
||||
}
|
||||
|
||||
/// The first context over seeds 1 to 60 that carries `marker`, and its lines that do.
|
||||
fn lines_with(state: &Value, room: &Room, kind: TurnKind, marker: &str) -> Option<Vec<String>> {
|
||||
(1..=60).map(|seed| packet_of(kind, state, room, &History::default(), seed).context).find(|context| context.contains(marker)).map(|context| context.lines().filter(|line| line.contains(marker)).map(str::to_owned).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5a_a_private_memory_naming_its_person_by_an_about_tag_is_never_plain_in_public() {
|
||||
let mut marked = state();
|
||||
marked["thoughtMemory"]["memories"] = json!([{ "id": "secret-a", "summary": "SECRETA Libby told me her diagnosis.", "createdAt": hours_ago(20), "status": "crystallized", "intensity": 1.0, "tags": ["private", "about:libby"] }]);
|
||||
let public = Room { messages: vec![message("#minds:gamecult.org", OPERATOR, "Meta", "how is Libby doing?", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
// Libby is not here: framed as known privately.
|
||||
assert_eq!(lines_with(&marked, &public, TurnKind::Chat, "SECRETA"), Some(vec!["- memory [secret-a]: she knows privately: SECRETA Libby told me her diagnosis.".to_owned()]));
|
||||
let present = Room { messages: vec![message("#minds:gamecult.org", "@libby:gamecult.org", "Libby", "hi all", 2, false)], ..public.clone() };
|
||||
assert_eq!(lines_with(&marked, &present, TurnKind::Chat, "SECRETA"), None, "left out to her face");
|
||||
// Naming no one, it is private about everyone: left out of public rooms and direct messages, plain in her own room.
|
||||
marked["thoughtMemory"]["memories"][0]["tags"] = json!(["private"]);
|
||||
assert_eq!(lines_with(&marked, &public, TurnKind::Chat, "SECRETA"), None);
|
||||
let dm = Room { messages: vec![message("!dm-libby:gamecult.org", "@libby:gamecult.org", "Libby", "hey", 2, true)], here: Some("!dm-libby:gamecult.org".into()), direct: vec!["!dm-libby:gamecult.org".into()], ..Room::default() };
|
||||
assert_eq!(lines_with(&marked, &dm, TurnKind::Chat, "SECRETA"), None);
|
||||
let own = Room { messages: vec![message("#eureka:gamecult.org", OPERATOR, "Meta", "morning", 2, false)], here: Some("#eureka:gamecult.org".into()), own: vec!["#eureka:gamecult.org".into()], ..Room::default() };
|
||||
assert_eq!(lines_with(&marked, &own, TurnKind::Chat, "SECRETA"), Some(vec!["- memory [secret-a]: SECRETA Libby told me her diagnosis.".to_owned()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5b_every_pool_honours_the_mark() {
|
||||
let mut marked = state();
|
||||
let private = json!({ "privacy": "private" });
|
||||
let libby = json!({ "id": "libby", "kind": "person" });
|
||||
marked["thoughtMemory"]["incubation"] = json!([{ "id": "w-secret", "summary": "SECRETB Whether Libby's relapse is why she went quiet.", "createdAt": hours_ago(20), "status": "active", "intensity": 1.0, "extensions": private, "target": libby }]);
|
||||
marked["affect"]["needs"] = json!([{ "id": "need-secret", "label": "SECRETN to keep Libby's relapse quiet", "intensity": 1.0, "status": "active", "extensions": private, "target": libby }]);
|
||||
marked["affect"]["doctrineStances"] = json!([{ "id": "stance-secret", "summary": "SECRETS Libby should not be on call.", "intensity": 1.0, "status": "active", "extensions": private, "target": libby }]);
|
||||
let present = Room { messages: vec![message("#minds:gamecult.org", "@libby:gamecult.org", "Libby", "hi all", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
let absent = Room { messages: vec![message("#minds:gamecult.org", OPERATOR, "Meta", "hi all", 2, false)], ..present.clone() };
|
||||
for marker in ["SECRETB", "SECRETN", "SECRETS"] {
|
||||
assert_eq!(lines_with(&marked, &present, TurnKind::Chat, marker), None, "{marker} is left out with Libby here");
|
||||
let framed = lines_with(&marked, &absent, TurnKind::Chat, marker).unwrap_or_else(|| panic!("{marker} is selected on some seed"));
|
||||
assert!(framed.iter().all(|line| line.contains(&format!("she knows privately: {marker}"))), "{framed:?}");
|
||||
}
|
||||
let packet = (1..=60).map(|seed| packet_of(TurnKind::Chat, &marked, &absent, &History::default(), seed)).find(|packet| packet.context.contains("SECRETB")).unwrap();
|
||||
assert!(packet.private.iter().any(|words| words.starts_with("SECRETB")), "the Interpreter is shown what is private: {:?}", packet.private);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5c_a_direct_message_with_a_third_person_is_not_a_direct_message_with_her() {
|
||||
let mut marked = state();
|
||||
marked["affect"]["socialBonds"][0]["extensions"] = json!({ "privacy": "private" });
|
||||
let room = "!group-dm:gamecult.org";
|
||||
let group = Room { messages: vec![message(room, "@kiko:gamecult.org", "Kiko", "hey", 3, true), message(room, "@libby:gamecult.org", "Libby", "hey both", 2, true)], here: Some(room.into()), direct: vec![room.into()], ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &marked, &group, &History::default(), 1);
|
||||
let bond = packet.context.lines().find(|line| line.starts_with("- bond [bond-libby]")).unwrap_or_else(|| panic!("{}", packet.context)).to_owned();
|
||||
assert!(!bond.contains("holds the sounds") && !bond.contains("privately"), "left out before Kiko: {bond}");
|
||||
let alone = Room { messages: vec![message(room, "@libby:gamecult.org", "Libby", "hey", 2, true)], ..group };
|
||||
assert!(packet_of(TurnKind::Chat, &marked, &alone, &History::default(), 1).context.contains("Libby holds the sounds"), "plain with Libby alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_she_said_in_a_direct_message_stays_in_it() {
|
||||
let said = |room: &str| super::select::Said { id: "said-dm".into(), room: room.into(), text: "SAIDDM I'm tired of the pipeline.".into(), at: now() - chrono::Duration::minutes(5) };
|
||||
let history = History { said: vec![said(DM_DERU)], ..History::default() };
|
||||
let shown = |room: &Room| (1..=60).any(|seed| packet_of(TurnKind::Chat, &state(), room, &history, seed).context.contains("SAIDDM"));
|
||||
assert!(!shown(&chat_room()), "never in a public packet");
|
||||
let with_deru = Room { messages: vec![message(DM_DERU, DERU, "Deru", "and?", 2, true)], here: Some(DM_DERU.into()), direct: vec![DM_DERU.into()], ..Room::default() };
|
||||
assert!(shown(&with_deru), "in its own direct message");
|
||||
let public = History { said: vec![said("#swarm:gamecult.org")], ..History::default() };
|
||||
assert!((1..=60).any(|seed| packet_of(TurnKind::Chat, &state(), &chat_room(), &public, seed).context.contains("SAIDDM")), "a public line is shared");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f6_a_mind_is_one_person_by_her_handle_or_her_full_matrix_id() {
|
||||
let kiko_here = Room { messages: vec![message("#minds:gamecult.org", "@kiko:gamecult.org", "Kiko", "hi all", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
let kiko_dm = Room { messages: vec![message("!dm-kiko:gamecult.org", "@kiko:gamecult.org", "Kiko", "hey", 2, true)], here: Some("!dm-kiko:gamecult.org".into()), direct: vec!["!dm-kiko:gamecult.org".into()], ..Room::default() };
|
||||
for (spelling, memory) in [
|
||||
("target, handle", json!({ "target": { "id": "kiko", "kind": "person" }, "tags": ["private"] })),
|
||||
("target, full id", json!({ "target": { "id": "@kiko:gamecult.org", "kind": "person" }, "tags": ["private"] })),
|
||||
("about, handle", json!({ "tags": ["private", "about:kiko"] })),
|
||||
("about, full id", json!({ "tags": ["private", "about:@kiko:gamecult.org"] })),
|
||||
] {
|
||||
let mut marked = state();
|
||||
let mut item = json!({ "id": "kiko-secret", "summary": "KIKOSECRET she is leaving.", "createdAt": hours_ago(3), "status": "crystallized", "intensity": 1.0 });
|
||||
for (key, value) in memory.as_object().unwrap() {
|
||||
item[key] = value.clone();
|
||||
}
|
||||
marked["thoughtMemory"]["memories"] = json!([item]);
|
||||
assert_eq!(lines_with(&marked, &kiko_here, TurnKind::Chat, "KIKOSECRET"), None, "{spelling}: left out with Kiko here");
|
||||
assert_eq!(lines_with(&marked, &kiko_dm, TurnKind::Chat, "KIKOSECRET"), Some(vec!["- memory [kiko-secret]: KIKOSECRET she is leaving.".to_owned()]), "{spelling}: plain with Kiko alone");
|
||||
}
|
||||
// A bond keyed by her full Matrix id is her bond, and the operator's full id is `operator`.
|
||||
let mut full = state();
|
||||
full["affect"]["socialBonds"][1]["object"]["id"] = "@kiko:gamecult.org".into();
|
||||
full["affect"]["socialBonds"][2]["object"]["id"] = OPERATOR.into();
|
||||
let both = Room { messages: vec![message("#minds:gamecult.org", "@kiko:gamecult.org", "Kiko", "hi", 3, false), message("#minds:gamecult.org", OPERATOR, "Meta", "hi", 2, false)], ..kiko_here };
|
||||
let context = packet_of(TurnKind::Chat, &full, &both, &History::default(), 1).context;
|
||||
assert!(context.contains("- bond [bond-kiko] Kiko") && context.contains("- bond [bond-operator] Meta, the operator"), "{context}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f7_a_value_carrying_a_mark_is_refused_not_rendered() {
|
||||
let mut marked = state();
|
||||
marked["values"] = json!([{ "id": "v-secret", "label": "SECRETVALUE", "priority": 0.9, "summary": "Never tell Kiko.", "extensions": { "privacy": "private" } }, { "id": "coherence", "label": "Coherence", "priority": 0.9, "summary": "Coherence over velocity." }]);
|
||||
let own = Room { messages: vec![message("#eureka:gamecult.org", OPERATOR, "Meta", "morning", 2, false)], here: Some("#eureka:gamecult.org".into()), own: vec!["#eureka:gamecult.org".into()], ..Room::default() };
|
||||
for room in [chat_room(), own] {
|
||||
assert_eq!(lines_with(&marked, &room, TurnKind::Chat, "SECRETVALUE"), None);
|
||||
}
|
||||
assert!(lines_with(&marked, &chat_room(), TurnKind::Chat, "Coherence").is_some(), "an unmarked value still renders");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,14 +20,11 @@ pub const TUNING_FILE: &str = "persona-tuning.toml";
|
|||
|
||||
/// The Persona stage's setting (map section 2): she continues the Projector's paragraph, her interior, with speech only
|
||||
/// where her thought moves her to it, quoted (map section 5.5, invariant 5). It is not a reply to the room.
|
||||
const PERSONA_GUIDANCE: &str = "Continue her inner stream where the paragraph leaves off: her own next thoughts, in the first person, in her own words. This is not a message to the room. If she means to say something aloud, she thinks it as she would, what and to whom; whether anything is said, and what, is decided after her. In a busy room most moments pass with nothing said.";
|
||||
const PERSONA_GUIDANCE: &str = "Continue her inner stream where the paragraph leaves off: her own next thoughts, in the first person, in her own words. This is not a message to the room. When she means to say something aloud, she writes the very words she would type, in her own voice and addressed as she would address them, never a description of what she will say. Whether she says them now is decided after her. In a busy room most moments pass with nothing said.";
|
||||
|
||||
/// The setting the Projector renders for. No task: in the Persona-only shape nothing is work she owes.
|
||||
const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. She lives in its chat rooms among the operator, the other Minds and whoever drops by. Render the moment as she lives it: who is here and how they sit with her, what she carries, what she wants. What was said reaches her word for word after this stream, so never retell or summarise it: render what it stirs in her and what she makes of the people who said it. Render the conversation as it stands. Do not weigh options or list what she might do or say; what she does is hers to decide. Leave out whatever the context does not carry: an absence is not part of her moment. Use each person's pronouns as given.";
|
||||
|
||||
/// The Interpreter's speech step (map section 4, C3b): its scope and rules beside Ghostlight's membrane. It has no tools;
|
||||
/// what the membrane calls the gap tool is the `gaps` list of the JSON.
|
||||
const INTERPRETER_GUIDANCE: &str = "This step decides only what she says aloud in chat this turn, from her prose. No tool is available in this step: report every translation and every gap in the JSON object the contract describes, and return that object alone. A line is speech only when her prose shows her choosing to say it now, to the room or to someone in it. Words she recalls, quotes, or heard from someone else are never her speech, even when her prose repeats them. Thinking about saying something, deciding to stay quiet, or saying that she says nothing, is not speech. Write each line as she would type it, in her voice, without @handles or quotation marks around it, and copy into source_quote the exact words of her prose the line rests on, character for character. Name in mentions, by Matrix id from the people listed, only someone she addresses directly; in reply_to, the Matrix id of the person whose message she answers, when she answers one. The room is one of the rooms listed. An empty say list is the usual answer in a busy room.";
|
||||
|
||||
/// The context room the fixed slots need beside the identity: the hour and the mood lines always fit.
|
||||
const FIXED_ROOM: usize = 256;
|
||||
|
|
@ -177,17 +174,16 @@ impl Default for ProjectorTuning {
|
|||
}
|
||||
}
|
||||
|
||||
/// The Interpreter's speech call: its model and its guidance.
|
||||
/// The Interpreter's speech call: its model. Its prompt is code (`interpret`): what it may decide is not a knob.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct InterpreterTuning {
|
||||
pub model: String,
|
||||
pub guidance: String,
|
||||
}
|
||||
|
||||
impl Default for InterpreterTuning {
|
||||
fn default() -> Self {
|
||||
Self { model: "claude-sonnet-5-5".into(), guidance: INTERPRETER_GUIDANCE.into() }
|
||||
Self { model: "claude-sonnet-5-5".into() }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -290,7 +286,6 @@ impl Tuning {
|
|||
("select.group_bytes", select.group_bytes),
|
||||
("projector.guidance", self.projector.guidance.len()),
|
||||
("persona.guidance", self.persona.guidance.len()),
|
||||
("interpreter.guidance", self.interpreter.guidance.len()),
|
||||
] {
|
||||
if bytes > PART_BYTES_MAX {
|
||||
bail!("{name} must be at most {PART_BYTES_MAX} bytes, not {bytes}: the prompt must fit the connector's frame");
|
||||
|
|
|
|||
|
|
@ -249,7 +249,7 @@ mind_body::projection: pub use select :: TurnKind ;
|
|||
mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ;
|
||||
mind_body::projection: struct HuginnPersonaSource pub-fields[]
|
||||
mind_body::projection: struct Organs< 'a > pub-fields[persona: Option < & 'a dyn PersonaSource >, chat: Option < & 'a dyn MouthReader >, addressing: Option < & 'a dyn HeartbeatView >, model: Option < & 'a dyn Model >]
|
||||
mind_body::projection: struct Request pub-fields[instance: String, kind: TurnKind, state: Option < Value >, room: Option < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >]
|
||||
mind_body::projection: struct Request pub-fields[instance: String, kind: TurnKind, state: Option < Value >, room: Option < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >, own_rooms: Vec < String >]
|
||||
mind_body::projection::harness: fn batch (harness : & Harness , plan_path : & Path) -> Result < String >
|
||||
mind_body::projection::harness: fn fixture_request (harness : & Harness , fixture : & Fixture , state : Option < Value > , seed : u64 , renders : Option < usize > , through : Through) -> Request
|
||||
mind_body::projection::harness: fn state_file (path : & Path , instance : & str) -> Result < Value >
|
||||
|
|
@ -281,6 +281,7 @@ mind_body::projection::select: impl Draw
|
|||
mind_body::projection::select: impl Lens
|
||||
mind_body::projection::select: impl Lines
|
||||
mind_body::projection::select: impl People < '_ >
|
||||
mind_body::projection::select: impl RoomKind
|
||||
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 < '_ >
|
||||
|
|
@ -295,7 +296,7 @@ mind_body::projection::tuning: impl Default for ProjectorTuning
|
|||
mind_body::projection::tuning: impl Default for SelectTuning
|
||||
mind_body::projection::tuning: impl Default for Tuning
|
||||
mind_body::projection::tuning: impl Tuning
|
||||
mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String]
|
||||
mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String]
|
||||
mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64]
|
||||
mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String]
|
||||
mind_body::projection::tuning: struct PersonaTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize]
|
||||
|
|
|
|||
Loading…
Reference in a new issue