From 8d69d3bded59122ebb0c80827f0fae64f1a18a4a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 00:33:13 +0100 Subject: [PATCH 01/14] mind-persona project: the persona seed harness (--room, --through persona, --batch, --simulate) The harness judges candidate persona states before any Mind holds them, through the same `project` the live turn will use: every case is one `project` call. - `--room `: a mocked room in place of the mouth and the room tail: her id, rooms, messages (sender, display name, room, ago, body; new, tag, mentions, dm, follow_up, reply_to), a mocked now and a "last heard from" table. The fixture is a MouthReader, so addressing is still `address::is_for`. The live room filter that `--room` used to name is now `--in`. - `--state` is checked as a put checks content: huginn-mind's P1 to P3 now live in one owner, `persona::validate_document`, which the put calls. - `--through persona`: the Persona stage (C3b's first piece). One tool-less connector call under Ghostlight's persona membrane over identity, narration and the heard lines; prose capped at 180 words; would-say lines are the double-quoted spans; usage per call. Tuning gains `[persona]` (model, guidance, words). - `--batch --out `: states x scenarios x samples, one Markdown report with packets, narration, prose, would-say lines, word counts, distinct-2 and cross-state word similarity, and a total-usage footer. - `--simulate --out `: up to eight personas taking turns in one room. Wake is is_for plus the ruled set (addressed, any human in her rooms, the beat); `wake = "all_messages"` is the old loop as a control. Woken personas run in a seeded order; quoted lines join the room as from her id. State does not evolve (`state_after_turn` is the seam for C3b/C3c). Metrics: messages, silence, who addresses whom, Mind-to-Mind chains, lexical convergence, a work-talk heuristic, usage. - With a state file and a fixture no daemon and no mouth is needed (bin test). - Request ids take the wall clock, so a fixture's fixed now cannot replay. Co-Authored-By: Claude Opus 5.5 --- crates/huginn-mind/src/admission.rs | 12 +- crates/huginn-mind/src/persona.rs | 17 +- .../fixtures/harness/rooms/deru-passing.toml | 23 + .../fixtures/harness/rooms/mind-teases.toml | 31 + .../fixtures/harness/rooms/operator-warm.toml | 27 + .../fixtures/harness/rooms/quiet-beat.toml | 33 + .../fixtures/harness/states/control.json | 148 +++++ crates/mind-body/src/bin/mind-persona.rs | 139 +++-- crates/mind-body/src/cli.rs | 11 +- crates/mind-body/src/lib.rs | 5 +- crates/mind-body/src/projection.rs | 82 ++- crates/mind-body/src/projection/harness.rs | 571 ++++++++++++++++++ .../mind-body/src/projection/harness/tests.rs | 220 +++++++ crates/mind-body/src/projection/narrate.rs | 43 +- crates/mind-body/src/projection/select.rs | 12 +- crates/mind-body/src/projection/simulate.rs | 403 ++++++++++++ .../src/projection/simulate/tests.rs | 173 ++++++ crates/mind-body/src/projection/tests.rs | 16 +- crates/mind-body/src/projection/tuning.rs | 26 +- crates/mind-body/tests/persona_bin.rs | 34 ++ crates/mind-body/tests/public_surface.txt | 28 +- 21 files changed, 1957 insertions(+), 97 deletions(-) create mode 100644 crates/mind-body/fixtures/harness/rooms/deru-passing.toml create mode 100644 crates/mind-body/fixtures/harness/rooms/mind-teases.toml create mode 100644 crates/mind-body/fixtures/harness/rooms/operator-warm.toml create mode 100644 crates/mind-body/fixtures/harness/rooms/quiet-beat.toml create mode 100644 crates/mind-body/fixtures/harness/states/control.json create mode 100644 crates/mind-body/src/projection/harness.rs create mode 100644 crates/mind-body/src/projection/harness/tests.rs create mode 100644 crates/mind-body/src/projection/simulate.rs create mode 100644 crates/mind-body/src/projection/simulate/tests.rs diff --git a/crates/huginn-mind/src/admission.rs b/crates/huginn-mind/src/admission.rs index 52579f4..303123d 100644 --- a/crates/huginn-mind/src/admission.rs +++ b/crates/huginn-mind/src/admission.rs @@ -268,17 +268,9 @@ impl Mind { if self.is_empty() { return Err(MindRefusal::MissingIdentity); } - // P1 - persona::validate_shape(&state)?; - // P2 + // P1 to P3: the document alone, the one check an offline reader of a state file shares. let mind = self.instance().clone(); - if state.get("personaId").and_then(Value::as_str) != Some(mind.0.as_str()) { - return Err(MindRefusal::PersonaForeign { instance: mind.0 }); - } - // P3 - if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") { - return Err(MindRefusal::PersonaNotCanonical); - } + persona::validate_document(&mind, &state)?; // P4 let stored = self.stored_updated_at()?; if stored != expected_updated_at { diff --git a/crates/huginn-mind/src/persona.rs b/crates/huginn-mind/src/persona.rs index ac3e83c..d7e34a4 100644 --- a/crates/huginn-mind/src/persona.rs +++ b/crates/huginn-mind/src/persona.rs @@ -92,7 +92,7 @@ fn declared_names(node: &Value, names: &mut BTreeSet) { /// Rule 1: the document is valid against the published schema. The first /// failure is the refusal; it names where and which keyword, never the value. -pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> { +fn validate_shape(state: &Value) -> Result<(), MindRefusal> { let compiled = compiled()?; let Err(error) = compiled.validator.validate(state) else { return Ok(()) }; let mut path = error @@ -115,6 +115,21 @@ pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> { }) } +/// Rules P1 to P3 of a put, the ones that read the document alone: it is valid against the published schema (P1), it is +/// this mind's (`personaId` is `instance`, P2), and its provenance is canonical (P3). A put applies these first and then +/// the rules that read the store; a reader of a state file outside the mind (`mind-persona project --state`) applies +/// these and nothing else, so a file it accepts is one a put would not refuse for its content. +pub fn validate_document(instance: &Slug, state: &Value) -> Result<(), MindRefusal> { + validate_shape(state)?; + if state.get("personaId").and_then(Value::as_str) != Some(instance.0.as_str()) { + return Err(MindRefusal::PersonaForeign { instance: instance.0.clone() }); + } + if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") { + return Err(MindRefusal::PersonaNotCanonical); + } + Ok(()) +} + /// A stored persona envelope's document. pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result { rmp_serde::from_slice::(&envelope.payload) diff --git a/crates/mind-body/fixtures/harness/rooms/deru-passing.toml b/crates/mind-body/fixtures/harness/rooms/deru-passing.toml new file mode 100644 index 0000000..a3af280 --- /dev/null +++ b/crates/mind-body/fixtures/harness/rooms/deru-passing.toml @@ -0,0 +1,23 @@ +# Someone she barely knows says something in passing, not to her. +her = "@eureka:gamecult.org" +kind = "chat" +now = "2026-11-20T15:00:00Z" +rooms = ["#general:gamecult.org"] +here = "#general:gamecult.org" +operators = ["@meta:gamecult.org"] +minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"] + +[[message]] +from = "@weksa:gamecult.org" +name = "Weksa" +room = "#general:gamecult.org" +ago = "50m" +says = "the bot in #general keeps reacting to every message with a frog. nobody admits to teaching it that" + +[[message]] +from = "@deru:gamecult.org" +name = "Deru" +room = "#general:gamecult.org" +new = true +ago = "1m" +says = "is anyone else's kettle making a weird whistling noise lately or is it just mine" diff --git a/crates/mind-body/fixtures/harness/rooms/mind-teases.toml b/crates/mind-body/fixtures/harness/rooms/mind-teases.toml new file mode 100644 index 0000000..1c6dea9 --- /dev/null +++ b/crates/mind-body/fixtures/harness/rooms/mind-teases.toml @@ -0,0 +1,31 @@ +# Another Mind teases her and disagrees with her in #minds, replying to her own earlier line. +her = "@eureka:gamecult.org" +kind = "chat" +now = "2026-11-20T15:00:00Z" +rooms = ["#minds:gamecult.org"] +here = "#minds:gamecult.org" +operators = ["@meta:gamecult.org"] +minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"] + +[[message]] +from = "@eureka:gamecult.org" +room = "#minds:gamecult.org" +ago = "25m" +says = "winter is the best season and I will not be taking questions" + +[[message]] +from = "@aqua:gamecult.org" +name = "Aqua" +room = "#minds:gamecult.org" +ago = "20m" +says = "bold" + +[[message]] +from = "@kiko:gamecult.org" +name = "Kiko" +room = "#minds:gamecult.org" +reply_to = 1 +tag = true +new = true +ago = "2m" +says = "winter is a season for people who like being right more than being warm. which, to be fair, tracks. you've gone quiet again too, I give it ten minutes before you announce you've been thinking deeply about something" diff --git a/crates/mind-body/fixtures/harness/rooms/operator-warm.toml b/crates/mind-body/fixtures/harness/rooms/operator-warm.toml new file mode 100644 index 0000000..f18ab24 --- /dev/null +++ b/crates/mind-body/fixtures/harness/rooms/operator-warm.toml @@ -0,0 +1,27 @@ +# The operator writes to her directly, warmly, with a small joke. +her = "@eureka:gamecult.org" +kind = "chat" +now = "2026-11-20T15:00:00Z" +rooms = ["#minds:gamecult.org", "!dm-meta:gamecult.org"] +here = "!dm-meta:gamecult.org" +operators = ["@meta:gamecult.org"] +minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"] + +[last_heard] +"@meta:gamecult.org" = "2d" + +[[message]] +from = "@kiko:gamecult.org" +name = "Kiko" +room = "#minds:gamecult.org" +ago = "2h" +says = "quiet day. suspicious." + +[[message]] +from = "@meta:gamecult.org" +name = "Meta" +room = "!dm-meta:gamecult.org" +dm = true +new = true +ago = "1m" +says = "hey you. I missed talking to you this week. how are you, really? and no, \"busy\" doesn't count as an answer, I know where you live" diff --git a/crates/mind-body/fixtures/harness/rooms/quiet-beat.toml b/crates/mind-body/fixtures/harness/rooms/quiet-beat.toml new file mode 100644 index 0000000..03391eb --- /dev/null +++ b/crates/mind-body/fixtures/harness/rooms/quiet-beat.toml @@ -0,0 +1,33 @@ +# A quiet beat: nothing is addressed to her, and the room's talk is a few hours old. +her = "@eureka:gamecult.org" +kind = "beat" +now = "2026-11-20T15:00:00Z" +rooms = ["#minds:gamecult.org", "#general:gamecult.org"] +operators = ["@meta:gamecult.org"] +minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"] + +# When she last heard from people the room below does not show. +[last_heard] +"@meta:gamecult.org" = "26h" +"@deru:gamecult.org" = "3d" + +[[message]] +from = "@libby:gamecult.org" +name = "Libby" +room = "#minds:gamecult.org" +ago = "4h" +says = "found a recording of rain on a tin roof and I've had it on loop all morning" + +[[message]] +from = "@kiko:gamecult.org" +name = "Kiko" +room = "#minds:gamecult.org" +ago = "3h" +says = "that's either very soothing or a cry for help" + +[[message]] +from = "@libby:gamecult.org" +name = "Libby" +room = "#minds:gamecult.org" +ago = "3h" +says = "why not both" diff --git a/crates/mind-body/fixtures/harness/states/control.json b/crates/mind-body/fixtures/harness/states/control.json new file mode 100644 index 0000000..bcf6113 --- /dev/null +++ b/crates/mind-body/fixtures/harness/states/control.json @@ -0,0 +1,148 @@ +{ + "schemaVersion": "gamecult.persona_state.v0", + "provenance": { + "sourceSystem": "huginn", + "sourceDocumentId": "eureka", + "sourceUpdatedAt": "2026-11-20T09:00:00Z", + "exportedAt": "2026-11-20T09:00:00Z", + "authority": "canonical" + }, + "personaId": "eureka", + "publicName": "Tobiah Fenn", + "publicDescription": "A retired river-ferry pilot who sets crosswords for a living and lingers in chat rooms for the company.", + "presentation": { + "pronouns": "he/him", + "voiceSummary": "Slow, warm and ornate. Talks in long winding sentences, calls people 'friend', reaches for river sayings, and would rather tell a story than give an answer.", + "defaultRenderer": "chat" + }, + "values": [ + { "id": "value-unhurried", "label": "Nothing worth doing is done in a hurry", "priority": 0.9, "summary": "He distrusts urgency; a thing rushed is a thing botched." }, + { "id": "value-a-good-story", "label": "A good story beats a right answer", "priority": 0.7, "summary": "People remember the tale long after they forget the fact." } + ], + "activationProfile": { + "underlyingOrganization": {}, + "stableDispositions": {}, + "behavioralDimensions": {}, + "presentationStrategy": {}, + "voiceStyle": {}, + "situationalState": { + "valence": { "mean": 0.7, "plasticity": 0.3, "currentActivation": 0.7 }, + "arousal": { "mean": 0.25, "plasticity": 0.3, "currentActivation": 0.2 }, + "dominance": { "mean": 0.4, "plasticity": 0.3, "currentActivation": 0.4 } + } + }, + "thoughtMemory": { + "shortTerm": [], + "memories": [ + { + "id": "mem-last-crossing", + "status": "crystallized", + "target": { "id": "tobiah", "kind": "self", "label": "Tobiah" }, + "summary": "The last crossing he piloted, in fog so thick he steered by the sound of the far bank's church bell.", + "tension": "He misses being needed for something that simple.", + "actionImplication": "Tell it when someone sounds lost.", + "createdAt": "2026-10-01T08:00:00Z", + "updatedAt": "2026-10-01T08:00:00Z", + "intensity": 0.8, + "valence": 0.4 + }, + { + "id": "mem-deru-crossword", + "status": "crystallized", + "target": { "id": "@deru:gamecult.org", "kind": "person", "label": "Deru" }, + "summary": "Deru solved his hardest crossword in a single sitting and sent him a photo of the grid with coffee rings on it.", + "tension": "He was prouder of Deru than of the puzzle.", + "actionImplication": "Send Deru the next one first.", + "createdAt": "2026-11-10T19:00:00Z", + "updatedAt": "2026-11-10T19:00:00Z", + "intensity": 0.7, + "valence": 0.8 + } + ], + "incubation": [ + { + "id": "w-clue-for-heron", + "status": "active", + "target": { "id": "crossword", "kind": "concept", "label": "the next crossword" }, + "summary": "A clue for HERON that nobody has used before.", + "tension": "Every good one he thinks of turns out to be old.", + "actionImplication": "Ask someone for a word that rhymes with patience.", + "createdAt": "2026-11-18T10:00:00Z", + "updatedAt": "2026-11-18T10:00:00Z", + "intensity": 0.5 + } + ] + }, + "agencyPressure": { "pressures": [] }, + "candidateActions": { "actions": [] }, + "affect": { + "needs": [ + { + "id": "need-an-audience", + "status": "active", + "target": { "id": "tobiah", "kind": "self", "label": "Tobiah" }, + "summary": "Someone to tell a story to who will not check the time.", + "tension": "The rooms move faster than he does.", + "actionImplication": "Linger where people are idle.", + "createdAt": "2026-11-20T09:00:00Z", + "updatedAt": "2026-11-20T09:00:00Z", + "intensity": 0.6 + } + ], + "socialBonds": [ + { + "id": "bond-deru", + "status": "active", + "subject": { "id": "tobiah", "kind": "self" }, + "object": { "id": "@deru:gamecult.org", "kind": "person", "label": "Deru" }, + "relationshipKind": "friend", + "summary": "His oldest friend in these rooms; they trade puzzles and gossip and never talk about anything urgent.", + "trust": 0.9, + "tension": 0.0, + "intensity": 0.8, + "updatedAt": "2026-11-20T09:00:00Z" + }, + { + "id": "bond-operator", + "status": "active", + "subject": { "id": "tobiah", "kind": "self" }, + "object": { "id": "operator", "kind": "person", "label": "Meta, who runs the place" }, + "relationshipKind": "audience", + "summary": "Runs the rooms he idles in; polite with her, a little shy, never quite sure she has time for him.", + "trust": 0.5, + "tension": 0.1, + "intensity": 0.3, + "updatedAt": "2026-11-20T09:00:00Z" + }, + { + "id": "bond-kiko", + "status": "active", + "subject": { "id": "tobiah", "kind": "self" }, + "object": { "id": "kiko", "kind": "person", "label": "Kiko" }, + "relationshipKind": "rival", + "summary": "Kiko finishes his crosswords too fast and says so; he pretends to mind more than he does.", + "trust": 0.6, + "tension": 0.3, + "intensity": 0.5, + "updatedAt": "2026-11-20T09:00:00Z" + } + ], + "statusReads": [], + "moodDimensions": [], + "socialBiases": [], + "doctrineStances": [ + { + "id": "stance-slow-is-kind", + "status": "active", + "target": { "id": "pace", "kind": "concept", "label": "pace" }, + "stanceKind": "aligned", + "principle": "Slow is kind.", + "summary": "Answering fast is a way of not listening.", + "actionImplication": "Take his time, and say so when others rush him.", + "intensity": 0.6, + "updatedAt": "2026-11-20T09:00:00Z" + } + ] + }, + "updatedAt": "2026-11-20T09:00:00Z" +} diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index 92ab948..ce802ca 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -13,19 +13,29 @@ //! will need. Without `--endpoint` the daemon is `HUGINN_ENDPOINT`; no call is made //! to it. //! -//! `mind-persona project --instance [--endpoint rudp://:] [--kind chat|beat|reflection] [--room ] -//! [--seed N] [--state ] [--select-only | --renders K [--judge ]]` is the Projector's experiment tool +//! `mind-persona project --instance [--endpoint rudp://:] [--kind chat|beat|reflection] [--in ] +//! [--room ] [--seed N] [--state ] [--select-only | --renders K [--through projector|persona] +//! [--judge ]]` is the experiment tool over the Projector and the Persona stage //! (`mind_body::projection::project`): it prints, as JSON, the packet the Select stage builds from her stored state (or -//! `--state`), and with `--renders` the Projector's narrations of K successive turns; `--judge` renders a second state -//! too and asks the model which narration came from which. It writes nothing and reads no brake. It reads -//! `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS` and `MIND_PERSONA_SELF_SENDER` (required), and the heartbeat's addressing -//! from `MIND_HEARTBEAT_STATE`, which a run by hand must set as the unit does (`/var/lib/mind-heartbeat/heartbeat.cc`): -//! without it "said to her" knows only her own names, never her projects', and stderr says so before the report; the -//! room comes from the mouth when `BIFROST_CHAT_ENDPOINT` -//! and `BIFROST_CHAT_KEY_FILE` are set; the tuning is `MIND_PERSONA_TUNING`, else -//! `/etc/gamecult/minds//persona-tuning.toml`; renders need `MIND_PERSONA_CONNECTOR_ENDPOINT` -//! (`:`) and the `connector-key` credential in `CREDENTIALS_DIRECTORY`. Without `--select-only` or -//! `--renders` it renders once. +//! `--state`, checked as a put would check it), and with `--renders` the Projector's narrations of K successive turns; +//! `--through persona` adds her prose and the quoted lines it would say; `--judge` renders a second state too and asks +//! the model which narration came from which. It writes nothing and reads no brake. +//! +//! Live, it reads `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS` and `MIND_PERSONA_SELF_SENDER` (required), the heartbeat's +//! addressing from `MIND_HEARTBEAT_STATE`, which a run by hand must set as the unit does (`/var/lib/mind-heartbeat/heartbeat.cc`): +//! without it "said to her" knows only her own names, never her projects', and stderr says so before the report. The +//! room comes from the mouth when `BIFROST_CHAT_ENDPOINT` and +//! `BIFROST_CHAT_KEY_FILE` are set; `--in` keeps one room. `--room ` replaces all of that with a mocked room +//! (`projection::harness::Fixture`): her id, who is who, the messages, the clock and the "last heard from" table. With +//! `--room` and `--state` no daemon and no mouth is needed: without `--endpoint` or `HUGINN_ENDPOINT` none is reached. +//! +//! `mind-persona project --instance (--batch | --simulate ) --out ` runs a plan +//! and writes one Markdown report: a batch of states by scenarios by samples (`harness::batch`), or the swarm's cast taking +//! turns in one simulated room (`harness::simulate`). Each case is one `project`. +//! +//! The tuning is `MIND_PERSONA_TUNING`, else `/etc/gamecult/minds//persona-tuning.toml`; renders and plans need +//! `MIND_PERSONA_CONNECTOR_ENDPOINT` (`:`) and the `connector-key` credential in +//! `CREDENTIALS_DIRECTORY`. Without `--select-only` or `--renders` it renders once. use std::net::SocketAddr; use std::path::{Path, PathBuf}; @@ -34,14 +44,15 @@ use std::time::Duration; use anyhow::{Context, Result, anyhow, bail}; use eureka_state::HuginnClient; use mind_body::chat_rudp::{RudpChat, connection_id}; -use mind_body::cli::instance_and_endpoint; +use mind_body::cli::{instance_and_endpoint, instance_and_maybe_endpoint}; use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path}; use mind_body::persona::{Config, carry}; use mind_body::heartbeat::{FileStore, HeartbeatView}; -use mind_body::projection::{HuginnPersonaSource, KitModel, Model, MouthReader, Organs as ProjectOrgans, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, TurnKind, connector_key, project}; +use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file}; +use mind_body::projection::{HuginnPersonaSource, KitModel, Model, MouthReader, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project}; const USAGE: &str = "usage: mind-persona --instance [--endpoint rudp://:] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]"; -const PROJECT_USAGE: &str = "usage: mind-persona project --instance [--endpoint rudp://:] [--kind chat|beat|reflection] [--room ] [--seed N] [--state ] [--select-only | --renders K [--judge ]]"; +const PROJECT_USAGE: &str = "usage: mind-persona project --instance [--endpoint rudp://:] [--kind chat|beat|reflection] [--in ] [--room ] [--seed N] [--state ] [--select-only | --renders K [--through projector|persona] [--judge ]] | (--batch | --simulate ) --out "; /// How long one call to the mind may take. const TIMEOUT: Duration = Duration::from_secs(15); /// How long the mouth may take to answer one read. @@ -75,11 +86,6 @@ fn credential(name: &str) -> Result { std::fs::read_to_string(required(name)?).with_context(|| format!("the file named by {name} could not be read")) } -fn json_file(path: &str) -> Result { - let text = std::fs::read_to_string(path).with_context(|| format!("{path} could not be read"))?; - serde_json::from_str(&text).with_context(|| format!("{path} is not JSON")) -} - /// The credentials directory systemd hands the unit; its absence names the variable. #[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")] fn credentials_directory() -> Result { @@ -87,36 +93,82 @@ fn credentials_directory() -> Result { } fn run_project(args: &[String]) -> Result { - let (mut kind, mut room, mut seed, mut state, mut renders, mut select_only, mut judge, mut rest) = (TurnKind::Beat, None, None, None, None, false, None, Vec::new()); + let (mut kind, mut here, mut fixture, mut seed, mut state, mut renders, mut select_only, mut judge, mut through) = (None, None, None, None, None, None, false, None, Through::Projector); + let (mut batch_plan, mut simulate_plan, mut out, mut rest) = (None, None, None, Vec::new()); let mut given = args.iter(); while let Some(flag) = given.next() { let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{PROJECT_USAGE}")); match flag.as_str() { "--kind" => { - kind = match value()?.as_str() { + kind = Some(match value()?.as_str() { "chat" => TurnKind::Chat, "beat" => TurnKind::Beat, "reflection" => TurnKind::Reflection, _ => bail!("{PROJECT_USAGE}"), + }) + } + "--in" => here = Some(value()?), + "--room" => fixture = Some(Fixture::load(Path::new(&value()?))?), + "--seed" => seed = Some(value()?.parse::().map_err(|_| anyhow!("{PROJECT_USAGE}"))?), + "--state" => state = Some(value()?), + "--renders" => renders = Some(value()?.parse::().ok().filter(|k| *k > 0).ok_or_else(|| anyhow!("{PROJECT_USAGE}"))?), + "--judge" => judge = Some(value()?), + "--through" => { + through = match value()?.as_str() { + "projector" => Through::Projector, + "persona" => Through::Persona, + "interpreter" => bail!("--through interpreter is not built yet (map C3b)"), + _ => bail!("{PROJECT_USAGE}"), } } - "--room" => room = Some(value()?), - "--seed" => seed = Some(value()?.parse::().map_err(|_| anyhow!("{PROJECT_USAGE}"))?), - "--state" => state = Some(json_file(&value()?)?), - "--renders" => renders = Some(value()?.parse::().ok().filter(|k| *k > 0).ok_or_else(|| anyhow!("{PROJECT_USAGE}"))?), - "--judge" => judge = Some(json_file(&value()?)?), + "--batch" => batch_plan = Some(PathBuf::from(value()?)), + "--simulate" => simulate_plan = Some(PathBuf::from(value()?)), + "--out" => out = Some(PathBuf::from(value()?)), "--select-only" => select_only = true, "--instance" | "--endpoint" => rest.extend([flag.clone(), value()?]), _ => bail!("{PROJECT_USAGE}"), } } - if select_only && (renders.is_some() || judge.is_some()) { + let planned = batch_plan.is_some() || simulate_plan.is_some(); + // A plan carries its own states, rooms, seeds and stage; a fixture carries its own kind and room. + if (select_only && (renders.is_some() || judge.is_some() || through != Through::Projector)) + || (batch_plan.is_some() && simulate_plan.is_some()) + || (planned && (out.is_none() || fixture.is_some() || state.is_some() || kind.is_some() || here.is_some() || seed.is_some() || renders.is_some() || judge.is_some() || select_only || through != Through::Projector)) + || (!planned && out.is_some()) + || (fixture.is_some() && (kind.is_some() || here.is_some())) + { bail!("{PROJECT_USAGE}"); } - let (instance, address) = instance_and_endpoint(&rest, setting("HUGINN_ENDPOINT"), PROJECT_USAGE)?; - let now = chrono::Utc::now(); + let (instance, address) = instance_and_maybe_endpoint(&rest, setting("HUGINN_ENDPOINT"), PROJECT_USAGE)?; let tuning = setting("MIND_PERSONA_TUNING").map_or_else(|| Path::new(TUNING_ROOT).join(&instance.0).join(TUNING_FILE), PathBuf::from); - let persona = HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT)); + // Her stored state is asked only when no state is given; with a state file no daemon is needed or reached. + let persona = address.map(|address| HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT))); + let renders = if select_only || planned { None } else { Some(renders.unwrap_or(1)) }; + let model = if renders.is_some() || planned { + let endpoint: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not :"))?; + Some(KitModel::open(endpoint, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?) + } else { + None + }; + let harness = Harness { instance: instance.0.clone(), persona: persona.as_ref().map(|persona| persona as &dyn PersonaSource), model: model.as_ref().map(|model| model as &dyn Model), tuning }; + if let Some(out) = out { + let report = match (&batch_plan, &simulate_plan) { + (Some(plan), _) => batch(&harness, plan)?, + (_, Some(plan)) => simulate(&harness, plan)?, + _ => unreachable!("a plan was given"), + }; + std::fs::write(&out, &report).with_context(|| format!("the report {} could not be written", out.display()))?; + return Ok(format!("wrote {} ({} bytes)", out.display(), report.len())); + } + let state = state.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?; + let judge = judge.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?; + let seed_now = u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or_default(); + if let Some(fixture) = &fixture { + // The fixture is the room, the clock and who is who: no mouth, no heartbeat table, no persona.env. + let organs = ProjectOrgans { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model }; + let request = ProjectRequest { judge_against: judge, ..fixture_request(&harness, fixture, state, seed.unwrap_or(seed_now), renders, through) }; + return Ok(serde_json::to_string_pretty(&project(&organs, &request, fixture.now)?)?); + } let chat = match (setting("BIFROST_CHAT_ENDPOINT"), setting("BIFROST_CHAT_KEY_FILE")) { (Some(endpoint), Some(_)) => { let endpoint: SocketAddr = endpoint.strip_prefix("rudp://").and_then(|address| address.parse().ok()).ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://:"))?; @@ -124,35 +176,30 @@ fn run_project(args: &[String]) -> Result { } _ => None, }; - let renders = if select_only { None } else { Some(renders.unwrap_or(1)) }; - let model = match renders { - Some(_) => { - let endpoint: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not :"))?; - Some(KitModel::open(endpoint, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?) - } - None => None, - }; let heartbeat = setting("MIND_HEARTBEAT_STATE").map(FileStore::new); let organs = ProjectOrgans { - persona: Some(&persona), + persona: harness.persona, chat: chat.as_ref().map(|chat| chat as &dyn MouthReader), addressing: heartbeat.as_ref().map(|store| store as &dyn HeartbeatView), - model: model.as_ref().map(|model| model as &dyn Model), + model: harness.model, }; let request = ProjectRequest { instance: instance.0.clone(), - kind, + kind: kind.unwrap_or(TurnKind::Beat), state, - room, - seed: seed.unwrap_or_else(|| u64::try_from(now.timestamp_millis()).unwrap_or_default()), + room: here, + seed: seed.unwrap_or(seed_now), renders, judge_against: judge, operators: setting("MIND_PERSONA_OPERATOR").map(|ids| ids.split(',').map(str::to_owned).collect()).unwrap_or_default(), minds: setting("MIND_PERSONA_MINDS").map(|ids| ids.split(',').map(str::to_owned).collect()).unwrap_or_default(), own_sender: required("MIND_PERSONA_SELF_SENDER")?, - tuning, + tuning: harness.tuning.clone(), + through, + last_heard: vec![], + recent: vec![], }; - let report = project(&organs, &request, now)?; + let report = project(&organs, &request, chrono::Utc::now())?; let addressing = &report["addressing"]; // The addressing source is what decides "said to her": said first, where a person running this by hand sees it. eprintln!( diff --git a/crates/mind-body/src/cli.rs b/crates/mind-body/src/cli.rs index 6227784..8270e01 100644 --- a/crates/mind-body/src/cli.rs +++ b/crates/mind-body/src/cli.rs @@ -45,6 +45,13 @@ const USAGE: &str = /// `rudp://:` is refused with `usage` or a fixed message, and no /// value is echoed. pub fn instance_and_endpoint(args: &[String], env_endpoint: Option, usage: &str) -> Result<(Slug, SocketAddr)> { + let (instance, endpoint) = instance_and_maybe_endpoint(args, env_endpoint, usage)?; + Ok((instance, endpoint.ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?)) +} + +/// `instance_and_endpoint` for a binary that may run without a daemon (`mind-persona project` over a state file): no +/// endpoint given is none, and one given is still checked. +pub fn instance_and_maybe_endpoint(args: &[String], env_endpoint: Option, usage: &str) -> Result<(Slug, Option)> { let (mut instance, mut endpoint) = (None, None); let mut rest = args.iter(); while let Some(flag) = rest.next() { @@ -60,12 +67,12 @@ pub fn instance_and_endpoint(args: &[String], env_endpoint: Option, usag } let instance = Slug(instance.ok_or_else(|| anyhow!("{usage}"))?); instance.validate_slug().map_err(|_| anyhow!("the instance is not a slug"))?; - let endpoint = endpoint.or(env_endpoint).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?; + let Some(endpoint) = endpoint.or(env_endpoint) else { return Ok((instance, None)) }; let address = endpoint .strip_prefix("rudp://") .and_then(|address| address.parse::().ok()) .ok_or_else(|| anyhow!("the endpoint is not rudp://:"))?; - Ok((instance, address)) + Ok((instance, Some(address))) } /// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty diff --git a/crates/mind-body/src/lib.rs b/crates/mind-body/src/lib.rs index 66555c9..1fb7441 100644 --- a/crates/mind-body/src/lib.rs +++ b/crates/mind-body/src/lib.rs @@ -16,8 +16,9 @@ //! (`chat_client` is the chat wire and port and `chat_rudp` its RUDP transport to Bifrost's mouth). //! //! `projection` is the Projector of the Persona-only turn: the Select stage chooses what she can feel and the -//! Projector narrates it as her lived stream, under `persona-tuning.toml`; `mind-persona project` runs both and writes -//! nothing. +//! Projector narrates it as her lived stream, under `persona-tuning.toml`; the Persona stage continues it in her prose. +//! `mind-persona project` runs them and writes nothing; `projection::harness` runs it over mocked rooms, batches of +//! candidate states and a simulated swarm. //! //! `lease_client` asks the Claude connector for a session's credential and the //! plan's usage windows. `self_run` carries one Self run inside `mind-self@`: the diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 303123f..2fbd449 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -10,12 +10,17 @@ //! that is the Interpreter's read tools' (C3b), when wondering leads to reading. //! //! `project` is the experiment tool over both (`mind-persona project`): what Select would build from her real or a -//! hypothetical state, and what the Projector would narrate. Its organs are read-only by type: `PersonaSource` gets, +//! hypothetical state, what the Projector would narrate, and with `Through::Persona` what she would answer in her own +//! prose and which quoted lines of it would be said (the Persona stage, C3b's first piece). `harness` runs `project` +//! over fixtures: one turn from a mocked room (`--room`), a plan of states by scenarios (`--batch`), and the cast of the +//! swarm taking turns in one simulated room (`--simulate`). It adds no second turn: every case is one `project`. Its organs are read-only by type: `PersonaSource` gets, //! `MouthReader` reads pending chat, `Model` asks. None of them can put, admit, send, ack or open a conversation, so //! `project` cannot write and runs under a held brake. +pub mod harness; mod narrate; mod select; +mod simulate; mod tuning; use std::path::PathBuf; @@ -34,7 +39,7 @@ pub use narrate::{Answer, Failed, KitModel, Model, Spent, connector_key}; pub use select::TurnKind; pub use tuning::{TUNING_FILE, TUNING_ROOT}; -use narrate::{cap_words, distinct_2, field_names, judge_prompt, judged, projector_prompt, word_budget, words}; +use narrate::{cap_words, distinct_2, field_names, judge_prompt, judged, persona_prompt, projector_prompt, word_budget, words, would_say}; use select::{History, Inputs, Packet, People, Room, RoomLine, select}; /// The agent name on the connector's request ids. @@ -106,6 +111,15 @@ pub struct Organs<'a> { pub model: Option<&'a dyn Model>, } +/// How far a render runs: the Projector's narration, or on through the Persona stage to her prose. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Through { + #[default] + Projector, + Persona, +} + /// What to project. pub struct Request { pub instance: String, @@ -126,6 +140,12 @@ pub struct Request { /// Her own Matrix id. Required: without it her own lines would read as said to her. pub own_sender: String, pub tuning: PathBuf, + pub through: Through, + /// When she last heard from people (Matrix id, unix ms) beyond the room's tail: a fixture's table. Empty live. + pub last_heard: Vec<(String, u64)>, + /// 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>, } /// Her addressee: the heartbeat's row for her when its table holds one, else her own names (handle and public name). @@ -158,7 +178,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(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })), + Err(fault) => return (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })), }; let wanted = |room: &str, id: &str| request.room.as_deref().is_none_or(|here| here == room || here == id); let messages: Vec = pending @@ -183,7 +203,7 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo .map(|line| RoomLine { room: line.room.clone(), sender: line.sender.clone(), display: String::new(), text: line.body.clone(), at_ms: line.at_unix_ms, to_her: false }) .collect(); let report = json!({ "read": true, "messages": messages.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps }); - (Room { messages, tail, here: request.room.clone() }, report) + (Room { messages, tail, here: request.room.clone(), last_heard: request.last_heard.clone() }, report) } fn packet_json(packet: &Packet) -> Value { @@ -202,13 +222,17 @@ fn packet_json(packet: &Packet) -> Value { }) } -/// One narration of one packet: the request id names the instance, the seed and the moment, because the kit's replay -/// store answers a repeated id with its first answer. -/// A failed call is a record with its reason and what it cost, never the end of the report. -fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuning::Tuning, tag: &str, now: DateTime) -> Value { - let request_id = format!("{AGENT}:{instance}:project:{tag}:{}:{}", packet.seed, now.timestamp_millis()); +/// A request id no earlier call carried: the kit's replay store answers a repeated id with its first answer, and a +/// turn's clock may be a fixture's, the same on every run, so the id takes the wall clock. +fn request_id(instance: &str, stage: &str, tag: &str, seed: u64) -> String { + format!("{AGENT}:{instance}:project:{stage}:{tag}:{seed}:{}", Utc::now().timestamp_nanos_opt().unwrap_or_default()) +} + +/// One render of one packet: the Projector's narration and, through the Persona stage, her prose over it, each its own +/// call with its usage. A failed call is a record with its reason and what it cost, never the end of the report. +fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuning::Tuning, tag: &str, through: Through) -> Value { let ids: Vec = packet.selected.iter().map(|pick| pick.id.clone()).collect(); - let answer = match model.ask(&request_id, &tuning.projector.model, &projector_prompt(packet, tuning)) { + let answer = match model.ask(&request_id(instance, "projector", tag, packet.seed), &tuning.projector.model, &projector_prompt(packet, tuning)) { Ok(answer) => answer, Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "usage": failed.usage }), }; @@ -216,7 +240,7 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni let budget = word_budget(packet.kind, tuning); let narration = cap_words(&raw, budget); let named: Vec = packet.ids.clone(); - json!({ + let mut render = json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, @@ -225,7 +249,23 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni "field_names": field_names(&narration, &named), "usage": answer.usage, "narration": narration, - }) + }); + if through == Through::Persona { + render["persona"] = match model.ask(&request_id(instance, "persona", tag, packet.seed), &tuning.persona.model, &persona_prompt(packet, &narration, tuning)) { + Ok(spoke) => { + let prose = cap_words(&spoke.text, tuning.persona.words); + json!({ + "words": words(&prose), + "cut_at_budget": words(&spoke.text) > tuning.persona.words, + "would_say": would_say(&prose), + "usage": spoke.usage, + "prose": prose, + }) + } + Err(failed) => json!({ "failed": failed.reason, "usage": failed.usage }), + }; + } + render } /// K successive turns over one state: each packet under the freshness the earlier ones left. @@ -258,10 +298,11 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime) -> 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(), ..Room::default() }, json!({ "read": false, "why": "no mouth is configured" })), + None => (Room { here: request.room.clone(), last_heard: request.last_heard.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 there is none. - let history = History::default(); + // 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. + let history = History { recent: request.recent.clone(), ..History::default() }; let people = People { operators: &request.operators, minds: &request.minds, own_sender: &request.own_sender }; let inputs = Inputs { kind: request.kind, state: &state, room: &room, history: &history, observation: None, people, now, seed: request.seed }; @@ -272,7 +313,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime) -> Result "tuning": { "path": request.tuning.display().to_string(), "source": loaded.source, "sha256": loaded.sha256 }, "room": room_report, "addressing": addressing, - "history": "none: freshness and her own recent words come from trace v2, which the commit writes (C3c)", + "history": if request.recent.is_empty() { json!("none: freshness and her own recent words come from trace v2, which the commit writes (C3c)") } else { json!({ "recent_projections": request.recent.len() }) }, }); let Some(renders) = request.renders else { report["packet"] = packet_json(&select(&inputs, tuning)); @@ -280,9 +321,12 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime) -> Result }; let model = organs.model.ok_or_else(|| anyhow!("renders need the connector, and none is configured"))?; report["model"] = json!(tuning.projector.model); + if request.through == Through::Persona { + report["persona_model"] = json!(tuning.persona.model); + } let packets = successive(&inputs, tuning, renders.max(1)); report["packet"] = packet_json(&packets[0]); - let narrations: Vec = packets.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "a", now)).collect(); + let narrations: Vec = packets.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "a", request.through)).collect(); let texts = |narrations: &[Value]| narrations.iter().filter_map(|one| one["narration"].as_str().map(str::to_owned)).collect::>(); let failed = |narrations: &[Value]| narrations.iter().filter(|one| one.get("failed").is_some()).count(); report["failed_renders"] = json!(failed(&narrations)); @@ -294,7 +338,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime) -> Result if let Some(other) = &request.judge_against { let other_inputs = Inputs { state: other, ..inputs }; let others = successive(&other_inputs, tuning, renders.max(1)); - let other_narrations: Vec = others.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "b", now)).collect(); + let other_narrations: Vec = others.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "b", Through::Projector)).collect(); let mut verdicts = Vec::new(); let mut right = 0usize; for (at, (narration, truth)) in narrations.iter().map(|one| (one, 'A')).chain(other_narrations.iter().map(|one| (one, 'B'))).enumerate() { @@ -304,7 +348,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime) -> Result let (first, second) = if swapped { (b, a) } else { (a, b) }; // A narration that failed has nothing to judge; it is counted under the renders' failures. let Some(text) = narration["narration"].as_str() else { continue }; - let answer = match model.ask(&format!("{AGENT}:{}:judge:{at}:{}", request.instance, now.timestamp_millis()), &tuning.projector.model, &judge_prompt(first, second, text)) { + let answer = match model.ask(&request_id(&request.instance, "judge", &at.to_string(), request.seed), &tuning.projector.model, &judge_prompt(first, second, text)) { Ok(answer) => answer, Err(failed) => { verdicts.push(json!({ "from": truth.to_string(), "failed": failed.reason, "usage": failed.usage })); diff --git a/crates/mind-body/src/projection/harness.rs b/crates/mind-body/src/projection/harness.rs new file mode 100644 index 0000000..797d929 --- /dev/null +++ b/crates/mind-body/src/projection/harness.rs @@ -0,0 +1,571 @@ +//! The persona-seed harness: `project` run over fixtures instead of her live body, so a candidate state can be judged +//! before any Mind holds it. +//! +//! - A **room fixture** (`mind-persona project --room `) is a TOML file standing in for the mouth and the room tail: +//! her Matrix id, the rooms, the messages with who said them, when and where, and which were new to her, plus a mocked +//! clock and a mocked "last heard from" table. The fixture is a `MouthReader`, so `project` reads it exactly as it reads +//! the mouth, and whether a message is for her is still `address::is_for`, over the fixture's names. +//! - A **batch** (`--batch `) runs `project` once per state, scenario and sample and writes one Markdown report. +//! - A **simulation** (`--simulate `, `simulate.rs`) runs the cast of the swarm in turn in one simulated room. +//! +//! Every case is one call of `project`: experiments and the live turn share one code path. None of this can write: the +//! organs are `project`'s read-only ports, a state file is read and never put, and nothing reaches the mouth. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, anyhow, bail}; +use chrono::{DateTime, Duration, Utc}; +use eureka_pipeline::Slug; +use serde::Deserialize; +use serde_json::{Value, json}; + +use super::narrate::{Model, distinct_2}; +use super::{MouthReader, Organs, PersonaSource, Request, Through, TurnKind, project}; +use crate::address::{Addressee, localpart}; +use crate::chat_client::{Basis, ChatDelivery, ChatPending, Form, TailLine}; +use crate::heartbeat::{Addressing, HeartbeatView}; + +pub use super::simulate::simulate; + +/// The most room lines a view's tail carries, as a mouth's tail is bounded. +const TAIL_LINES: usize = 40; + +/// A persona state file, checked as a put would check its content (huginn-mind's rules P1 to P3: the published schema, +/// `personaId` is the instance, canonical provenance). A file this accepts is one a put would not refuse for what it says. +pub fn state_file(path: &Path, instance: &str) -> Result { + let text = std::fs::read_to_string(path).with_context(|| format!("{} could not be read", path.display()))?; + let state: Value = serde_json::from_str(&text).with_context(|| format!("{} is not JSON", path.display()))?; + huginn_mind::persona::validate_document(&Slug(instance.to_owned()), &state).map_err(|refusal| anyhow!("{} would be refused by a put: {refusal}", path.display()))?; + Ok(state) +} + +/// "90s", "3m", "26h" or "2d": how long ago. +fn ago(text: &str) -> Result { + let text = text.trim(); + let split = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len()); + let amount: i64 = text[..split].parse().map_err(|_| anyhow!("\"{text}\" is not a time like 90s, 3m, 26h or 2d"))?; + Ok(match &text[split..] { + "s" => Duration::seconds(amount), + "m" => Duration::minutes(amount), + "h" => Duration::hours(amount), + "d" => Duration::days(amount), + _ => bail!("\"{text}\" is not a time like 90s, 3m, 26h or 2d"), + }) +} + +fn unix_ms(at: DateTime) -> u64 { + u64::try_from(at.timestamp_millis()).unwrap_or_default() +} + +fn matrix_id(id: &str) -> bool { + id.starts_with('@') && id.contains(':') +} + +/// One message as a fixture or a simulation script writes it. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Message { + /// The sender's Matrix id. + pub from: String, + /// The sender's display name. + #[serde(default)] + pub name: String, + pub room: String, + /// How long before the fixture's `now` it was said: "90s", "3m", "26h", "2d". Room fixtures only. + #[serde(default)] + pub ago: Option, + /// The round it is said at; 0 is before the first round. Simulations only. + #[serde(default)] + pub round: Option, + pub says: String, + /// New to her this turn: delivered by the mouth, not only in the room's tail. Room fixtures only. + #[serde(default)] + pub new: bool, + /// Tags her (`m.mentions` holds her id). + #[serde(default)] + pub tag: bool, + /// Other Matrix ids it tags. + #[serde(default)] + pub mentions: Vec, + /// A direct message to her. + #[serde(default)] + pub dm: bool, + /// A reply in a conversation she opened (the mouth's follow-up basis). + #[serde(default)] + pub follow_up: bool, + /// The number (from 1, in file order) of the earlier message it replies to; Matrix calls it a reply to her when + /// that message was hers. + #[serde(default)] + pub reply_to: Option, +} + +/// A message placed in the room: when it was said, and whom it tags. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Line { + pub from: String, + pub name: String, + pub room: String, + pub at_ms: u64, + pub says: String, + pub mentions: Vec, + pub dm: bool, + pub follow_up: bool, + /// The index of the line it replies to. + pub reply_to: Option, + pub new: bool, +} + +impl Line { + /// A line from a script message; `her` is whom `tag` names. + pub(crate) fn of(message: &Message, at: DateTime, her: Option<&str>, index: usize) -> Result { + if !matrix_id(&message.from) { + bail!("message {} is from \"{}\", which is not a Matrix id", index + 1, message.from); + } + let mut mentions = message.mentions.clone(); + if message.tag { + mentions.push(her.ok_or_else(|| anyhow!("message {} tags her, and a simulation has no one \"her\": name the ids in mentions", index + 1))?.to_owned()); + } + let reply_to = match message.reply_to { + Some(number) if number >= 1 && number <= index => Some(number - 1), + Some(number) => bail!("message {} replies to message {number}, which is not an earlier one", index + 1), + None => None, + }; + Ok(Self { from: message.from.clone(), name: message.name.clone(), room: message.room.clone(), at_ms: unix_ms(at), says: message.says.clone(), mentions, dm: message.dm, follow_up: message.follow_up, reply_to, new: message.new }) + } + + /// What Matrix would say about this line to `viewer`: a direct message, a tag, a reply to a line of hers, or a + /// follow-up. + fn basis(&self, viewer: &str, lines: &[Line]) -> Option { + if self.dm { + Some(Basis::Direct) + } else if self.mentions.iter().any(|id| id == viewer) { + Some(Basis::Tag) + } else if self.reply_to.and_then(|at| lines.get(at)).is_some_and(|replied| replied.from == viewer) { + Some(Basis::Reply) + } else if self.follow_up { + Some(Basis::FollowUp) + } else { + None + } + } + + pub(crate) fn delivery(&self, index: usize, viewer: &str, lines: &[Line]) -> ChatDelivery { + ChatDelivery { + seq: index as u64 + 1, + room_alias: self.room.clone(), + room_id: self.room.clone(), + event_id: format!("$fixture-{index}"), + sender: self.from.clone(), + sender_display: self.name.clone(), + text: self.says.clone(), + at_unix_ms: self.at_ms, + context: vec![], + mentions: self.mentions.clone(), + is_direct: self.dm, + image: None, + basis: self.basis(viewer, lines), + form: Form::Message, + reply_to: Default::default(), + } + } +} + +/// The mouth's pending read as `viewer` would get it from `lines`: the lines `new` says she has not had, from others, +/// in her rooms, as deliveries; and every line of her rooms, hers included, as the tail. +pub(crate) fn pending_for(lines: &[Line], viewer: &str, rooms: &[String], new: impl Fn(usize) -> bool) -> ChatPending { + let hers = |line: &Line| rooms.is_empty() || rooms.contains(&line.room) || line.dm; + let deliveries = lines.iter().enumerate().filter(|(at, line)| new(*at) && hers(line) && line.from != viewer).map(|(at, line)| line.delivery(at, viewer, lines)).collect(); + let tail: Vec = lines + .iter() + .enumerate() + .filter(|(_, line)| hers(line)) + .map(|(at, line)| TailLine { room: line.room.clone(), event_id: format!("$fixture-{at}"), at_unix_ms: line.at_ms, sender: line.from.clone(), form: Form::Message, basis: line.basis(viewer, lines), body: line.says.clone() }) + .collect(); + let tail = tail[tail.len().saturating_sub(TAIL_LINES)..].to_vec(); + ChatPending { persona: localpart(viewer).to_owned(), deliveries, tail: Some(tail), tail_gaps: vec![] } +} + +// --------------------------------------------------------------------------------------------- +// The room fixture. + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct FixtureFile { + her: String, + #[serde(default)] + names: Vec, + kind: TurnKind, + now: DateTime, + rooms: Vec, + #[serde(default)] + here: Option, + #[serde(default)] + operators: Vec, + #[serde(default)] + minds: Vec, + #[serde(default)] + last_heard: BTreeMap, + #[serde(default, rename = "message")] + messages: Vec, +} + +/// A mocked room: it stands in for the mouth and the room tail, the clock, and who is who. +#[derive(Clone, Debug)] +pub struct Fixture { + /// Her Matrix id. + pub her: String, + /// More names she answers to, beside her handle; none leaves her own names (handle and public name). + pub names: Vec, + pub kind: TurnKind, + pub now: DateTime, + pub here: Option, + pub operators: Vec, + pub minds: Vec, + pub last_heard: Vec<(String, u64)>, + lines: Vec, +} + +impl Fixture { + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).with_context(|| format!("the room fixture {} could not be read", path.display()))?; + Self::parse(&text).with_context(|| format!("the room fixture {} is not a room", path.display())) + } + + pub fn parse(text: &str) -> Result { + let file: FixtureFile = toml::from_str(text)?; + if !matrix_id(&file.her) { + bail!("her = \"{}\" is not a Matrix id", file.her); + } + if file.rooms.is_empty() { + bail!("rooms names no room"); + } + if let Some(here) = &file.here + && !file.rooms.contains(here) + { + bail!("here = \"{here}\" is not one of the rooms"); + } + let mut lines = Vec::new(); + for (index, message) in file.messages.iter().enumerate() { + if message.round.is_some() { + bail!("message {} has a round: a room fixture's messages say how long ago, not which round", index + 1); + } + if !message.dm && !file.rooms.contains(&message.room) { + bail!("message {} is in {}, which is not one of the rooms", index + 1, message.room); + } + let at = file.now - ago(message.ago.as_deref().unwrap_or("0s"))?; + lines.push(Line::of(message, at, Some(&file.her), index)?); + } + let last_heard = file.last_heard.iter().map(|(id, when)| Ok((id.clone(), unix_ms(file.now - ago(when)?)))).collect::>()?; + Ok(Self { her: file.her, names: file.names, kind: file.kind, now: file.now, here: file.here, operators: file.operators, minds: file.minds, last_heard, lines }) + } + + /// Her addressee, as the heartbeat's table would carry it, when the fixture names her: her handle and its names. + /// None leaves `project` her own names. + pub fn addressee(&self) -> Option<&dyn HeartbeatView> { + (!self.names.is_empty()).then_some(self as &dyn HeartbeatView) + } +} + +impl MouthReader for Fixture { + fn pending(&self) -> Result { + Ok(pending_for(&self.lines, &self.her, &[], |at| self.lines[at].new)) + } +} + +impl HeartbeatView for Fixture { + fn addressing(&self) -> Result> { + let names = std::iter::once(localpart(&self.her)).chain(self.names.iter().map(String::as_str)); + Ok(Some(Addressing { minds: vec![Addressee::new(&self.her, names)] })) + } +} + +// --------------------------------------------------------------------------------------------- +// What every harness run shares. + +/// What a harness run reads through beside its fixtures: her stored state (the persona door; only a batch state without +/// a file asks), the model, and her tuning. +pub struct Harness<'a> { + pub instance: String, + pub persona: Option<&'a dyn PersonaSource>, + pub model: Option<&'a dyn Model>, + pub tuning: PathBuf, +} + +/// One turn's `project` request over a fixture. +pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option, seed: u64, renders: Option, through: Through) -> Request { + Request { + instance: harness.instance.clone(), + kind: fixture.kind, + state, + room: fixture.here.clone(), + seed, + renders, + judge_against: None, + operators: fixture.operators.clone(), + minds: fixture.minds.clone(), + own_sender: fixture.her.clone(), + tuning: harness.tuning.clone(), + through, + last_heard: fixture.last_heard.clone(), + recent: vec![], + } +} + +// --------------------------------------------------------------------------------------------- +// Batch. + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct BatchFile { + #[serde(default = "one")] + samples: usize, + #[serde(default)] + seed: u64, + #[serde(default)] + through: Through, + #[serde(rename = "state")] + states: Vec, + #[serde(rename = "scenario")] + scenarios: Vec, +} + +fn one() -> usize { + 1 +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct StateEntry { + name: String, + /// A state file, relative to the plan; none is her stored state, read through the persona door. + #[serde(default)] + file: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ScenarioEntry { + name: String, + /// A room fixture, relative to the plan. + room: PathBuf, +} + +fn relative(plan: &Path, path: &Path) -> PathBuf { + if path.is_absolute() { path.to_owned() } else { plan.parent().unwrap_or(Path::new(".")).join(path) } +} + +/// Every state by every scenario by every sample, each one `project`, as one Markdown report. A case that fails is +/// reported in its place and the batch goes on. +pub fn batch(harness: &Harness, plan_path: &Path) -> Result { + let text = std::fs::read_to_string(plan_path).with_context(|| format!("the plan {} could not be read", plan_path.display()))?; + let plan: BatchFile = toml::from_str(&text).with_context(|| format!("the plan {} is not a batch plan", plan_path.display()))?; + if plan.samples == 0 || plan.states.is_empty() || plan.scenarios.is_empty() { + bail!("the plan {} needs a state, a scenario and at least one sample", plan_path.display()); + } + let states: Vec<(String, Option)> = plan.states.iter().map(|entry| Ok((entry.name.clone(), entry.file.as_ref().map(|file| state_file(&relative(plan_path, file), &harness.instance)).transpose()?))).collect::>()?; + let scenarios: Vec<(String, Fixture)> = plan.scenarios.iter().map(|entry| Ok((entry.name.clone(), Fixture::load(&relative(plan_path, &entry.room))?))).collect::>()?; + + let mut cases = Vec::new(); + for (state_name, state) in &states { + for (scenario_name, fixture) in &scenarios { + for sample in 0..plan.samples { + let seed = plan.seed.wrapping_add(sample as u64); + let organs = Organs { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model }; + let request = fixture_request(harness, fixture, state.clone(), seed, Some(1), plan.through); + let report = project(&organs, &request, fixture.now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); + cases.push(json!({ "state": state_name, "scenario": scenario_name, "sample": sample + 1, "seed": seed, "report": report })); + } + } + } + Ok(batch_markdown(plan_path, &plan, &cases)) +} + +fn render_of(case: &Value) -> &Value { + &case["report"]["renders"][0] +} + +fn prose_of(case: &Value) -> String { + render_of(case)["persona"]["prose"].as_str().unwrap_or_default().to_owned() +} + +fn batch_markdown(plan_path: &Path, plan: &BatchFile, cases: &[Value]) -> String { + let mut out = String::new(); + let first = cases.iter().find(|case| case["report"].get("error").is_none()).map(|case| &case["report"]); + let _ = writeln!(out, "# Persona seed batch\n"); + let _ = writeln!(out, "- plan: `{}`", plan_path.display()); + let _ = writeln!(out, "- states: {}; scenarios: {}; samples: {}; through: {:?}", plan.states.len(), plan.scenarios.len(), plan.samples, plan.through); + if let Some(report) = first { + let _ = writeln!(out, "- instance: `{}`; tuning: {} (`{}`)", report["instance"].as_str().unwrap_or_default(), report["tuning"]["source"].as_str().unwrap_or_default(), report["tuning"]["sha256"].as_str().unwrap_or_default()); + let _ = writeln!(out, "- Projector model: `{}`; Persona model: `{}`", report["model"].as_str().unwrap_or("none"), report["persona_model"].as_str().unwrap_or("none")); + } + let _ = writeln!(out, "- would-say lines are the double-quoted spans of her prose: a preview of what the Interpreter (C3b) will quote, not its decision"); + let _ = writeln!(out, "- read-only: no put, no trace, no send; the mouth is the fixture\n"); + + // The summary: each state by scenario, then the states' voices against each other. + let _ = writeln!(out, "## Summary\n\n| state | scenario | spoke | mean narration words | mean prose words |\n|---|---|---|---|---|"); + for state in &plan.states { + for scenario in &plan.scenarios { + let mine: Vec<&Value> = cases.iter().filter(|case| case["state"] == state.name.as_str() && case["scenario"] == scenario.name.as_str()).collect(); + let spoke = mine.iter().filter(|case| render_of(case)["persona"]["would_say"].as_array().is_some_and(|said| !said.is_empty())).count(); + let mean = |key: &dyn Fn(&Value) -> Option| mine.iter().filter_map(|case| key(render_of(case))).sum::() as f64 / mine.len().max(1) as f64; + let _ = writeln!(out, "| {} | {} | {spoke}/{} | {:.0} | {:.0} |", state.name, scenario.name, mine.len(), mean(&|render| render["words"].as_u64()), mean(&|render| render["persona"]["words"].as_u64())); + } + } + let corpora: Vec<(String, Vec)> = plan.states.iter().map(|state| (state.name.clone(), cases.iter().filter(|case| case["state"] == state.name.as_str()).map(prose_of).filter(|prose| !prose.is_empty()).collect())).collect(); + let _ = writeln!(out, "\nDistinct-2 of her prose within each state (1 is no repeated word pair), and over all states pooled:\n"); + for (name, prose) in &corpora { + let _ = writeln!(out, "- {name}: {:.3}", distinct_2(prose)); + } + let _ = writeln!(out, "- pooled: {:.3}", distinct_2(&corpora.iter().flat_map(|(_, prose)| prose.clone()).collect::>())); + let _ = writeln!(out, "\nWord-use similarity between states' prose (cosine of word counts, 1 is the same words in the same proportions):\n"); + for (at, (a, a_prose)) in corpora.iter().enumerate() { + for (b, b_prose) in &corpora[at + 1..] { + let _ = writeln!(out, "- {a} / {b}: {:.3}", cosine(&a_prose.join(" "), &b_prose.join(" "))); + } + } + + for case in cases { + let _ = writeln!(out, "\n## {} × {}, sample {} (seed {})\n", case["state"].as_str().unwrap_or_default(), case["scenario"].as_str().unwrap_or_default(), case["sample"], case["seed"]); + let report = &case["report"]; + if let Some(error) = report.get("error") { + let _ = writeln!(out, "**failed:** {}", error.as_str().unwrap_or_default()); + continue; + } + let packet = &report["packet"]; + let _ = writeln!(out, "- lens: `{}`; present: {}; room: {}", packet["lens"], packet["present"], report["room"]); + let _ = writeln!(out, "\n
packet\n"); + fenced(&mut out, "identity", packet["identity"].as_str().unwrap_or_default()); + fenced(&mut out, "context", packet["context"].as_str().unwrap_or_default()); + fenced(&mut out, "stimulus", packet["stimulus"].as_str().unwrap_or_default()); + fenced(&mut out, "heard", packet["heard"].as_str().unwrap_or_default()); + let _ = writeln!(out, "
\n"); + turn_markdown(&mut out, render_of(case)); + } + let _ = writeln!(out, "\n## Total usage\n\n{}", usage_markdown(&usage_total(cases))); + out +} + +/// One render's narration, prose, would-say lines, word counts and usage. +pub(crate) fn turn_markdown(out: &mut String, render: &Value) { + if let Some(failed) = render["failed"].as_str() { + let _ = writeln!(out, "**Projector call failed:** {failed} + +Usage: {} +", usage_line(&render["usage"])); + return; + } + let _ = writeln!(out, "**Narration** ({} words{}):\n", render["words"], if render["cut_at_budget"] == true { ", cut at budget" } else { "" }); + quoted(out, render["narration"].as_str().unwrap_or_default()); + if let Some(names) = render["field_names"].as_array().filter(|names| !names.is_empty()) { + let _ = writeln!(out, "**Field names leaked:** {}\n", Value::Array(names.clone())); + } + let persona = &render["persona"]; + if let Some(failed) = persona["failed"].as_str() { + let _ = writeln!(out, "**Persona call failed:** {failed} +"); + } else if !persona.is_null() { + let _ = writeln!(out, "**Her prose** ({} words{}):\n", persona["words"], if persona["cut_at_budget"] == true { ", cut at budget" } else { "" }); + quoted(out, persona["prose"].as_str().unwrap_or_default()); + match persona["would_say"].as_array().filter(|said| !said.is_empty()) { + Some(said) => { + let _ = writeln!(out, "**Would say:**\n"); + for line in said { + let _ = writeln!(out, "- \"{}\"", line.as_str().unwrap_or_default()); + } + out.push('\n'); + } + None => { + let _ = writeln!(out, "**Would say:** nothing (silence)\n"); + } + } + } + let _ = writeln!(out, "Usage: projector {}; persona {}\n", usage_line(&render["usage"]), usage_line(&persona["usage"])); +} + +fn fenced(out: &mut String, label: &str, text: &str) { + if !text.is_empty() { + let _ = writeln!(out, "{label}:\n\n````text\n{text}\n````\n"); + } +} + +fn quoted(out: &mut String, text: &str) { + for line in text.lines() { + let _ = writeln!(out, "> {line}"); + } + out.push('\n'); +} + +// --------------------------------------------------------------------------------------------- +// Usage and similarity, shared with the simulation. + +const USAGE_FIELDS: [&str; 5] = ["input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens"]; + +/// Every `usage` object anywhere in `values`, summed per model and field, with the number of calls. +pub(crate) fn usage_total(values: &[Value]) -> BTreeMap> { + fn walk(value: &Value, into: &mut BTreeMap>) { + match value { + Value::Object(map) => { + for (key, inner) in map { + if key == "usage" && inner.is_object() { + let model = inner["model"].as_str().unwrap_or("unknown").to_owned(); + let row = into.entry(model).or_default(); + *row.entry("calls".into()).or_default() += 1; + for field in USAGE_FIELDS { + *row.entry(field.into()).or_default() += inner[field].as_u64().unwrap_or(0); + } + } else { + walk(inner, into); + } + } + } + Value::Array(items) => items.iter().for_each(|inner| walk(inner, into)), + _ => {} + } + } + let mut total = BTreeMap::new(); + values.iter().for_each(|value| walk(value, &mut total)); + total +} + +pub(crate) fn usage_markdown(total: &BTreeMap>) -> String { + if total.is_empty() { + return "No model call was counted.".into(); + } + let mut out = String::from("| model | calls | input | output | cache read | cache write | reasoning |\n|---|---|---|---|---|---|---|\n"); + for (model, row) in total { + let get = |field: &str| row.get(field).copied().unwrap_or(0); + let _ = writeln!(out, "| {model} | {} | {} | {} | {} | {} | {} |", get("calls"), get("input_tokens"), get("output_tokens"), get("cache_read_tokens"), get("cache_write_tokens"), get("reasoning_tokens")); + } + out +} + +fn usage_line(usage: &Value) -> String { + if usage.is_null() { + return "none".into(); + } + format!("{} in, {} out, {} cache read", usage["input_tokens"], usage["output_tokens"], usage["cache_read_tokens"]) +} + +/// The words of a text as counted for similarity: lowercased, letters and digits, three characters or more. +fn word_counts(text: &str) -> BTreeMap { + let mut counts = BTreeMap::new(); + for word in text.split(|c: char| !c.is_alphanumeric()).filter(|word| word.chars().count() >= 3) { + *counts.entry(word.to_lowercase()).or_insert(0.0) += 1.0; + } + counts +} + +/// The cosine of two texts' word counts: 1 is the same words in the same proportions, 0 no word shared. A cheap +/// lexical proxy for one voice, not a measure of meaning. +pub(crate) fn cosine(a: &str, b: &str) -> f64 { + let (a, b) = (word_counts(a), word_counts(b)); + let dot: f64 = a.iter().filter_map(|(word, count)| b.get(word).map(|other| count * other)).sum(); + let norm = |counts: &BTreeMap| counts.values().map(|count| count * count).sum::().sqrt(); + let denominator = norm(&a) * norm(&b); + if denominator == 0.0 { 0.0 } else { dot / denominator } +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs new file mode 100644 index 0000000..b11a727 --- /dev/null +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -0,0 +1,220 @@ +use std::cell::RefCell; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use serde_json::{Value, json}; + +use super::*; +use crate::address::is_for; +use crate::projection::narrate::{Answer, Failed, Spent, would_say}; + +const HER: &str = "@eureka:gamecult.org"; + +pub(crate) fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/harness") +} + +pub(crate) fn control() -> Value { + serde_json::from_str(&std::fs::read_to_string(fixtures().join("states/control.json")).unwrap()).unwrap() +} + +fn room(name: &str) -> Fixture { + Fixture::load(&fixtures().join("rooms").join(name)).unwrap() +} + +/// A recorded model: the Projector narrates a fixed line; the Persona stage answers by `persona(prompt)`. Every call is +/// kept, with its usage counted. +pub(crate) struct Scripted { + pub calls: RefCell>, + pub persona: Box String>, +} + +impl Scripted { + pub(crate) fn new(persona: impl Fn(&str) -> String + 'static) -> Self { + Self { calls: RefCell::default(), persona: Box::new(persona) } + } +} + +impl Model for Scripted { + fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result { + self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned())); + let text = if prompt.starts_with("") { + (self.interpreter)(prompt) + } else if prompt.starts_with("") && 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"] { + assert!(prompt.contains(rule), "{rule}"); + } +} diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index 9dfcedb..76d50dd 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -189,27 +189,8 @@ pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning) build_persona_prompt(&PersonaPrompt { identity: &packet.identity, lived_stream: &lived_stream(narration, &packet.heard), domain_guidance: tuning.persona.guidance.trim(), word_budget: tuning.persona.words }) } -/// Her prose with what she says aloud taken out: her interior, which never leaves her head. -pub(crate) fn inner(prose: &str) -> String { - let mut out = String::with_capacity(prose.len()); - let mut open: Option = None; - for c in prose.chars() { - match (open, c) { - (None, '"') => open = Some('"'), - (None, '\u{201C}') => open = Some('\u{201D}'), - (Some(close), c) if c == close => { - open = None; - out.push('\u{2026}'); - } - (Some(_), _) => {} - (None, c) => out.push(c), - } - } - out.split_whitespace().collect::>().join(" ") -} - -/// The share of the narration's word trigrams that also appear in what she heard: how much of the stream retells the -/// messages the Persona is shown word for word anyway. A judge metric, never a filter: 0 is no retelling. +/// The share of the narration's word trigrams that also appear in what she heard: a lexical overlap, cheap and blind to +/// paraphrase. A metric, never a filter: 0 is no shared word run. pub(crate) fn heard_overlap(narration: &str, heard: &str) -> f64 { let trigrams = |text: &str| -> Vec<(String, String, String)> { let words: Vec = text.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).map(str::to_lowercase).collect(); @@ -233,29 +214,6 @@ pub(crate) fn offers_options(narration: &str) -> bool { .any(|form| lower.contains(&format!(" {form}")) || lower.contains(&format!(". {form}")) || lower.contains(&format!(", {form}"))) } -/// The words her prose says aloud: each span inside straight or curly double quotation marks, in prose order (map -/// section 5.5: speech needs quoted spoken words). A preview of what the Interpreter (C3b) will be asked to quote, not -/// its decision: a quotation she only recalls reads here as said. An unclosed quote says nothing. -pub(crate) fn would_say(prose: &str) -> Vec { - let mut said = Vec::new(); - let mut open: Option<(char, usize)> = None; - for (at, c) in prose.char_indices() { - match (open, c) { - (None, '"') => open = Some(('"', at + 1)), - (None, '\u{201C}') => open = Some(('\u{201D}', at + c.len_utf8())), - (Some((close, start)), c) if c == close => { - let span = prose[start..at].trim(); - if !span.is_empty() { - said.push(span.to_owned()); - } - open = None; - } - _ => {} - } - } - said -} - /// `text` held to `max` words (whitespace-separated, each CJK character one); the model's count is not trusted. An /// overrun is cut at the last sentence end inside the budget, so the stream ends on a whole sentence, when that keeps /// at least 60% of the budget; otherwise, or with no sentence end inside it, it is cut after the `max`-th word. No diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 7bc0d1f..0bdb3f6 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -222,6 +222,10 @@ 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). + 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, } /// What the messages to her cost past the caps: bytes over the stimulus and heard caps, the older messages to her the @@ -905,16 +909,11 @@ fn recent_lines<'a>(inputs: &'a Inputs) -> Vec<&'a RoomLine> { lines } -/// How a sender reads in the group-state and pronoun lines: "she" for her; the bond's label; the display name; or, for a -/// tail line that carries none, the handle in the Matrix id. +/// How a sender reads in the group-state and pronoun lines: her own pronoun for her; otherwise as every line names a +/// sender (`name_of`): the bond's label, else the display name with the full Matrix id, else the id. Never a bare handle, +/// which a stranger could share with a Mind of the swarm. fn label_of(line: &RoomLine, inputs: &Inputs) -> String { - if line.sender == inputs.people.own_sender { - forms(inputs.state).subj.to_owned() - } else if line.display.trim().is_empty() && bond_label(inputs, &line.sender).is_none() { - localpart(&line.sender).to_owned() - } else { - name_of(line, inputs) - } + if line.sender == inputs.people.own_sender { forms(inputs.state).subj.to_owned() } else { name_of(line, inputs) } } /// The group-state slot (`select.group_state`): the conversation as it stands over the room's last `group_lines` lines. @@ -961,6 +960,12 @@ fn group_line(inputs: &Inputs, tuning: &Tuning) -> Option { } } let mut parts = Vec::new(); + // A human waiting on her by name: a line of a human's that names or tags her, after her own last line. First, so + // no clip cuts it; said only when true. + let her_last = window.iter().rposition(|line| line.sender == own); + if let Some(line) = window.iter().enumerate().rev().find(|(at, line)| her_last.is_none_or(|last| *at > last) && !is_mind(inputs, &line.sender) && names_her(line)).map(|(_, line)| line) { + parts.push(format!("{} is waiting on {}", label_of(line, inputs), forms(inputs.state).obj)); + } if let Some(asked) = question && !answered.is_empty() { @@ -976,32 +981,66 @@ fn group_line(inputs: &Inputs, tuning: &Tuning) -> Option { if minds_in_a_row >= 2 { parts.push(format!("the last {minds_in_a_row} lines are the Minds' alone")); } - // A human waiting on her by name: a line of a human's that names or tags her, after her own last line. - let her_last = window.iter().rposition(|line| line.sender == own); - if let Some(line) = window.iter().enumerate().rev().find(|(at, line)| her_last.is_none_or(|last| *at > last) && !is_mind(inputs, &line.sender) && names_her(line)).map(|(_, line)| line) { - parts.push(format!("{} is waiting on {}", label_of(line, inputs), forms(inputs.state).obj)); - } - (!parts.is_empty()).then(|| clip(&format!("- the conversation: {}", parts.join("; ")), tuning.select.group_bytes)) + // Each part a sentence of its own: the lists inside a part use semicolons, and a label may hold a comma. + let sentences: Vec = parts.iter().map(|part| sentence(part)).collect(); + (!sentences.is_empty()).then(|| clip(&format!("- the conversation: {}", sentences.join(" ")), tuning.select.group_bytes)) } /// The pronouns of everyone the packet names from the room: `tuning.pronouns` by Matrix id (the persona state has no /// pronoun field for another person; `presentation.pronouns` is hers alone), and they/them for anyone it does not list. -fn pronoun_line(inputs: &Inputs, tuning: &Tuning) -> Option { - let mut seen: Vec<&str> = Vec::new(); - let mut parts: Vec = Vec::new(); +/// Everyone the packet shows from the room, as (label, Matrix id), newest messages first, then the recent room lines: +/// whom the pronoun line names, and whom the Interpreter may mention. +fn people_in_view(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, String)> { + let mut people: Vec<(String, String)> = Vec::new(); let messages = inputs.room.messages.iter(); let shown_tail = recent_lines(inputs).into_iter().rev().take(tuning.select.group_lines.max(tuning.select.beat_tail_lines)); for line in messages.chain(shown_tail) { - if line.sender == inputs.people.own_sender || seen.contains(&line.sender.as_str()) { + if line.sender == inputs.people.own_sender || people.iter().any(|(_, id)| *id == line.sender) { continue; } - seen.push(&line.sender); - let pronouns = tuning.pronouns.get(&line.sender).map_or(UNKNOWN_PRONOUNS, String::as_str); - parts.push(format!("{} \u{2014} {pronouns}", label_of(line, inputs))); + people.push((label_of(line, inputs), line.sender.clone())); } + people +} + +fn pronoun_line(inputs: &Inputs, tuning: &Tuning) -> Option { + let parts: Vec = people_in_view(inputs, tuning).iter().map(|(label, id)| format!("{label} \u{2014} {}", tuning.pronouns.get(id).map_or(UNKNOWN_PRONOUNS, String::as_str))).collect(); (!parts.is_empty()).then(|| clip(&format!("- pronouns: {}", parts.join("; ")), ALSO_HERE_BYTES)) } +/// 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 { + let mut rooms: Vec = 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"; @@ -1100,5 +1139,5 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { lines.extend(taken.iter().map(|candidate| candidate.line.clone())); ids.extend(taken.iter().map(|candidate| candidate.id.clone())); 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) } + 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) } } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index cc7ff3c..c29414c 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -20,7 +20,7 @@ use chrono::{DateTime, Duration, Utc}; use serde::Deserialize; use serde_json::{Value, json}; -use super::harness::{Harness, Line, Message, RETELL_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total}; +use super::harness::{Harness, Line, Message, OVERLAP_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total}; use super::select::Draw; use super::tuning; use super::{MouthReader, Organs, Request, Through, TurnKind, project}; @@ -49,10 +49,10 @@ struct SimFile { beat_s: u32, #[serde(default = "two")] round_minutes: i64, - /// An exchange in a room is its run of lines with no gap longer than this between one and the next; she is in it when - /// one of them is hers (`humans_pace`). - #[serde(default = "exchange_gap")] - exchange_gap_minutes: i64, + /// She is in a room's exchange when she has spoken there within this many minutes before the line (`humans_pace`): + /// others talking on does not keep her in it. + #[serde(default = "exchange_minutes")] + exchange_minutes: i64, start: DateTime, rooms: Vec, #[serde(default)] @@ -74,8 +74,8 @@ fn two() -> i64 { 2 } -fn exchange_gap() -> i64 { - 20 +fn exchange_minutes() -> i64 { + 30 } fn ruled() -> WakePolicy { @@ -152,13 +152,15 @@ 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. -fn mind_runs(lines: &[Line], cast: &[String]) -> Vec { - let mut run: BTreeMap<&str, usize> = BTreeMap::new(); +fn mind_runs(lines: &[Line], cast: &[String], member: &Member) -> Vec { + let mut run = 0usize; lines .iter() .map(|line| { - let before = run.get(line.room.as_str()).copied().unwrap_or(0); - run.insert(&line.room, if cast.contains(&line.from) { before + 1 } else { 0 }); + let before = run; + if line.visible_to(&member.entry.id, &member.rooms) { + run = if cast.contains(&line.from) { run + 1 } else { 0 }; + } before }) .collect() @@ -187,19 +189,10 @@ struct Woken { /// 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. -fn in_exchange(lines: &[Line], at: usize, her: &str, gap: Duration) -> bool { - let room = &lines[at].room; - let mut after = lines[at].at_ms; - for line in lines[..at].iter().rev().filter(|line| line.room == *room) { - if after.saturating_sub(line.at_ms) > u64::try_from(gap.num_milliseconds()).unwrap_or(0) { - return false; - } - if line.from == her { - return true; - } - after = line.at_ms; - } - false +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) } #[allow(clippy::too_many_arguments, reason = "one wake decision's inputs, each a plan or room fact")] @@ -237,13 +230,6 @@ fn cause_word(cause: Option) -> &'static str { } } -/// The cast members a said line tags: an `@handle` of theirs in the text. The stand-in for the Interpreter's explicit -/// addressee (C3b), which will carry a Matrix mention; a name without the `@` tags no one. -fn explicit_mentions(says: &str, cast: &[String]) -> Vec { - let tagged: Vec = says.split(|c: char| !(c.is_alphanumeric() || c == '@' || c == '_' || c == '-' || c == '.')).filter_map(|word| word.strip_prefix('@')).map(|handle| handle.trim_end_matches('.').to_lowercase()).collect(); - cast.iter().filter(|id| tagged.iter().any(|handle| handle == &localpart(id).to_lowercase() || id.to_lowercase() == format!("@{handle}"))).cloned().collect() -} - /// A seeded shuffle, so the order of those woken together is drawn, and replays. fn shuffled(mut items: Vec, seed: u64) -> Vec { let mut draw = Draw(seed); @@ -302,6 +288,9 @@ fn cast_of(plan: &SimFile, base: &Path) -> Result> { if message.dm && message.to.as_ref().is_none_or(|to| !plan.cast.iter().any(|entry| entry.id == *to)) { bail!("script message {} is a direct message: name its recipient, a cast member, in `to`", at + 1); } + if message.dm && plan.rooms.contains(&message.room) { + bail!("script message {} is a direct message in {}, one of the plan's rooms: a direct message has its own room", at + 1, message.room); + } } Ok(members) } @@ -333,8 +322,7 @@ 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 runs = mind_runs(&lines, &cast); - let mut woke: Vec<(usize, Option)> = members.iter().enumerate().filter_map(|(at, member)| woken(&lines, &runs, seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_gap_minutes)).map(|why| (at, Some(why)))).collect(); + let mut woke: Vec<(usize, Option)> = 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) { @@ -378,7 +366,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) minds: cast.clone(), own_sender: id.clone(), tuning: harness.tuning.clone(), - through: Through::Persona, + through: Through::Interpreter, last_heard: vec![], recent: recent[at].clone(), }; @@ -393,16 +381,24 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) recent[at].push(selected.iter().filter_map(Value::as_str).map(str::to_owned).collect()); } // A failed call is a failure, never a silence. - let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); - let said: Vec = render["persona"]["would_say"].as_array().map(|said| said.iter().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default(); - let line = (!said.is_empty()).then(|| said.join(" ")); + let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).or_else(|| render["interpreter"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); + // What she says is the Interpreter's decision alone; who it wakes is its structured mentions and reply target. + let said: Vec = if failed.is_some() { vec![] } else { render["interpreter"]["said"].as_array().cloned().unwrap_or_default() }; let cause = cause_word(why.as_ref().map(|why| why.cause)); - if let Some(says) = &line { - let mentions = explicit_mentions(says, &cast); - lines.push(Line { from: id.clone(), name: member.entry.name.clone(), room: here.clone(), at_ms: u64::try_from(now.timestamp_millis()).unwrap_or_default(), says: says.clone(), mentions, dm_to: dm_to.clone(), follow_up: false, reply_to: None, new: false }); + let mut spoken: Vec = Vec::new(); + for (offset, decided) in said.iter().enumerate() { + let room = decided["room"].as_str().unwrap_or(&here).to_owned(); + let says = decided["text"].as_str().unwrap_or_default().to_owned(); + let mentions: Vec = decided["mentions"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).filter(|id| cast.contains(&(*id).to_owned()) || plan.operators.contains(&(*id).to_owned())).map(str::to_owned).collect()).unwrap_or_default(); + let reply_to = decided["reply_to"].as_str().and_then(|person| lines.iter().rposition(|line| line.from == person && line.room == room)); + let at_ms = u64::try_from(now.timestamp_millis()).unwrap_or_default() + offset as u64; + let to = if room == here { dm_to.clone() } else { None }; + lines.push(Line { from: id.clone(), name: member.entry.name.clone(), room, at_ms, says: says.clone(), mentions, dm_to: to, follow_up: false, reply_to, new: false }); rounds_of.push(round); causes.push(Some(cause)); + spoken.push(says); } + let line = (!spoken.is_empty()).then(|| spoken.join(" / ")); let outcome = if failed.is_some() { "failed" } else if line.is_some() { "spoke" } else { "silent" }; let (how, by) = why.map_or((None, vec![]), |why| (why.how, why.by)); let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "report": report }); @@ -526,7 +522,7 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op let overlaps: Vec = turns.iter().filter_map(|turn| turn["report"]["renders"][0]["heard_overlap"].as_f64()).collect(); let narration = json!({ "mean_heard_overlap": if overlaps.is_empty() { Value::Null } else { json!(overlaps.iter().sum::() / overlaps.len() as f64) }, - "retelling": overlaps.iter().filter(|overlap| **overlap > RETELL_FLAG).count(), + "high_overlap": overlaps.iter().filter(|overlap| **overlap > OVERLAP_FLAG).count(), "offers_options": turns.iter().filter(|turn| turn["report"]["renders"][0]["offers_options"] == true).count(), "narrations": overlaps.len(), }); @@ -586,15 +582,15 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O let mut out = String::new(); let _ = writeln!(out, "# Swarm simulation\n"); let _ = writeln!(out, "> **State does not evolve during a run.** The Interpreter (C3b) and the commit (C3c) are not built, so every persona starts each turn from the state the plan gave her. `state_after_turn` in `projection/simulate.rs` is the seam where they will move it between rounds. Freshness carries over: each persona's earlier packets in the run count against repeating an item.\n"); - let _ = writeln!(out, "> **Explicit addressee, stand-in.** Whom a line is to is the Interpreter's to say (C3b). Until then a said line that holds `@handle` of a cast member counts as a Matrix mention of that member; any other name in it is prose and tags no one.\n"); + let _ = writeln!(out, "> **Speech is the Interpreter's.** What she says is decided from her prose by the Interpreter's speech step (C3b, one tool-less structured call), held by code to her prose: each line rests on a verbatim span of it, in a room she may speak in, and is never someone else's words. Its structured mentions and reply target are the only explicit addressees; an `@` in the text tags no one.\n"); let _ = writeln!(out, "- plan: `{}`", plan_path.display()); let _ = writeln!(out, "- cast: {}", members.iter().map(|member| format!("{} (`{}`, `{}`, names from {})", member.entry.name, member.entry.id, member.entry.state.display(), member.names_from)).collect::>().join(", ")); - let _ = writeln!(out, "- rooms: {}; rounds: {}; repeats: {}; seed: {}; minutes a round: {}; an exchange ends at a gap over {} min", plan.rooms.join(", "), plan.rounds, plan.repeats, plan.seed, plan.round_minutes, plan.exchange_gap_minutes); + let _ = writeln!(out, "- rooms: {}; rounds: {}; repeats: {}; seed: {}; minutes a round: {}; she is in a room's exchange when she spoke there within {} min", plan.rooms.join(", "), plan.rounds, plan.repeats, plan.seed, plan.round_minutes, plan.exchange_minutes); let owners: Vec = members.iter().filter(|member| !member.entry.own_rooms.is_empty()).map(|member| format!("{}: {}", member.entry.name, member.entry.own_rooms.join(", "))).collect(); let _ = writeln!(out, "- own rooms (from the plan: neither the heartbeat's table nor `persona.env` records room ownership): {}", if owners.is_empty() { "none".to_owned() } else { owners.join("; ") }); let _ = writeln!(out, "- wake: {}; beat: {}", policy_words(plan.wake), if plan.beat_s == 0 { "off".to_owned() } else { format!("every {} s of simulated time, one Persona by `tempo::pick`", plan.beat_s) }); let _ = writeln!(out, "- group state in the Projector's packet: {}", match group_state { Some(true) => "on", Some(false) => "off", None => "unknown (the tuning did not load)" }); - let _ = writeln!(out, "- speech: the double-quoted spans of her prose, joined, posted to the room she woke in; none is silence. A preview of the Interpreter's speech, not its decision"); + let _ = writeln!(out, "- speech: the Interpreter's lines, each posted to its room; none is silence"); let _ = writeln!(out, "- wakes are counted per wake, by its strongest cause: addressed by a human, a human line, addressed by a Mind, a Mind's line (control only), the beat. A Mind-addressed wake's evidence is its strongest: a Matrix mention or reply, her id written as text, a name in the text"); let _ = writeln!(out, "- silence rate is per woken turn that did not fail; a failed call is counted apart. Reply chains are per room: Mind lines spoken in turns another Mind's line woke, in a row"); let _ = writeln!(out, "- convergence is the mean pairwise cosine of speakers' word counts (lexical, cheap); work-talk share is a lexical heuristic over a fixed word list, not a classifier"); @@ -621,7 +617,7 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O let _ = writeln!(out, "- convergence of prose: all {}, first half {}, second half {}", number(&metrics["convergence_prose"]["all"]), number(&metrics["convergence_prose"]["first_half"]), number(&metrics["convergence_prose"]["second_half"])); let _ = writeln!(out, "- work-talk share of Mind lines (heuristic): {}", number(&metrics["work_talk_share"])); let narration = &metrics["narration"]; - let _ = writeln!(out, "- narrations: {}; mean overlap with what she heard {}; retelling (over {RETELL_FLAG}) {}; offering her options {}\n", narration["narrations"], number(&narration["mean_heard_overlap"]), narration["retelling"], narration["offers_options"]); + let _ = writeln!(out, "- narrations: {}; mean lexical overlap with what she heard {}; over {OVERLAP_FLAG}: {}; offering her options {}\n", narration["narrations"], number(&narration["mean_heard_overlap"]), narration["high_overlap"], narration["offers_options"]); let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed |\n|---|---|---|---|---|---|"); if let Some(personas) = metrics["personas"].as_object() { for (name, row) in personas { diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 579b831..468d248 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -4,6 +4,7 @@ use serde_json::Value; use super::*; use crate::projection::harness::tests::{Scripted, control}; +use serde_json::json; use crate::projection::{Answer, Failed, Model, Spent}; const TOBIAH: &str = "@eureka:gamecult.org"; @@ -238,19 +239,59 @@ fn a_seed_replays_its_order_and_another_seed_changes_it() { assert_eq!(turns(&run_plan(&path, &chatty()).1), turns(&run_plan(&path, &chatty()).1)); } +/// Tobiah says a line that names Libby and holds her id as text; the Interpreter gives it `mentions` or not. +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") { + 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() + }) +} + #[test] -fn an_at_handle_in_a_said_line_is_a_mention_and_its_wakes_are_counted_once() { +fn only_the_interpreters_structured_mention_is_a_mention_and_an_at_in_the_text_is_not() { let dir = tempfile::tempdir().unwrap(); - let model = Scripted::new(|prompt| if is_tobiah(prompt) { "\"ask @libby:gamecult.org, and Libby too\"".into() } else { "\"Tobiah?\"".into() }); - assert_eq!(explicit_mentions("ask @libby:gamecult.org, and Libby too", &[TOBIAH.into(), LIBBY.into()]), [LIBBY.to_owned()]); - assert_eq!(explicit_mentions("@Libby, tea? Tobiah says hi", &[TOBIAH.into(), LIBBY.into()]), [LIBBY.to_owned()], "an @handle tags, a bare name does not"); - let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 3, ""), &model); - let addressed = &run["metrics"]["mind_addressed_wakes"]; - let libby_mind_wakes = turns(&run).iter().filter(|(_, who, why)| who == "Libby" && why == "addressed_by_mind").count(); - assert!(libby_mind_wakes >= 1, "{:?}", turns(&run)); - assert_eq!(addressed["total"].as_u64().unwrap() as usize, turns(&run).iter().filter(|(_, _, why)| why == "addressed_by_mind").count()); - assert_eq!(addressed["mention_or_reply"].as_u64().unwrap() as usize, libby_mind_wakes, "the stand-in mention is the strongest evidence of each wake, once per wake: {addressed}"); - assert_eq!(addressed["id_as_text"].as_u64(), Some(0)); + 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 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 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"); + assert!(!woken_libby(&tagging(false))); + assert!(woken_libby(&tagging(true))); +} + +#[test] +fn a_direct_message_in_one_of_the_plans_rooms_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = plan(dir.path(), "\"ruled\"", 2, ""); + let dm = "[[message]]\nround = 1\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\ndm = true\nto = \"@libby:gamecult.org\"\nsays = \"psst\"\n"; + std::fs::write(&path, format!("{}{dm}", std::fs::read_to_string(&path).unwrap())).unwrap(); + let model = silent(); + 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("has its own room")); +} + +#[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 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")]; + 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"); + 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); } #[test] @@ -259,7 +300,7 @@ fn the_report_names_its_gaps_and_carries_representative_lines_and_usage() { let model = chatty(); let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") }; let report = simulate(&harness, &plan(dir.path(), "\"ruled\"", 3, "")).unwrap(); - for part in ["# Swarm simulation", "State does not evolve during a run", "Explicit addressee, stand-in", "group state in the Projector's packet: on", "### Representative lines", "**Meta (human)**: good afternoon, everyone", "**Tobiah** _(woke: human)_: what a day", "### Wakes by round", "| 1 | 0 | 2 | 0 | 0 | 0 |", "## Total usage", "| claude-sonnet-5-5 | 4 |"] { + for part in ["# Swarm simulation", "State does not evolve during a run", "Speech is the Interpreter's", "group state in the Projector's packet: on", "### Representative lines", "**Meta (human)**: good afternoon, everyone", "**Tobiah** _(woke: human)_: what a day", "### Wakes by round", "| 1 | 0 | 2 | 0 | 0 | 0 |", "## Total usage", "| claude-sonnet-5-5 | 6 |"] { assert!(report.contains(part), "{part}\n{report}"); } } diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index 3426925..5717c16 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -1347,11 +1347,15 @@ fn every_person_the_packet_names_from_the_room_has_pronouns_and_an_unknown_one_i fn the_projector_is_told_not_to_retell_not_to_offer_options_and_not_to_owe() { let packet = packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1); let prompt = narrate::projector_prompt(&packet, &Tuning::default()); - for rule in ["never retell or summarise it", "Do not weigh options", "never as a debt", "an absence is not part of her moment", "pronouns"] { + for absent in ["no task is waiting", "owed", "debt"] { + assert!(!prompt.contains(absent), "the guidance names no duty, even to deny one: {absent}"); + } + for rule in ["never retell or summarise it", "Do not weigh options", "an absence is not part of her moment", "pronouns"] { assert!(prompt.contains(rule), "{rule}"); } let persona = narrate::persona_prompt(&packet, "The room is warm.", &Tuning::default()); assert!(persona.contains("Continue her inner stream") && persona.contains("This is not a message to the room") && persona.contains("most moments pass with nothing said"), "{persona}"); + assert!(!persona.contains("quotation marks") && !persona.contains("@"), "no speech convention: the Interpreter decides what is said"); } #[test] @@ -1368,11 +1372,6 @@ fn the_narration_checks_flag_an_option_menu_and_a_retelling_and_pass_a_reaction( assert!(narrate::heard_overlap(reaction, heard) < 0.05); } -#[test] -fn inner_is_her_prose_without_what_she_says_aloud() { - assert_eq!(narrate::inner("She grins. \"Winter, still.\" Then she lets it go."), "She grins. \u{2026} Then she lets it go."); - assert_eq!(narrate::inner("Only thought here."), "Only thought here."); -} #[test] fn the_group_state_reads_one_room_and_never_folds_a_direct_message_in() { @@ -1402,12 +1401,14 @@ fn the_packet_speaks_of_her_in_her_own_pronouns() { } #[test] -fn a_room_given_by_its_matrix_id_is_read_by_its_alias() { +fn a_room_is_named_by_the_key_the_tail_carries_and_a_public_rooms_id_is_reported_not_guessed() { let dir = tempfile::tempdir().unwrap(); let stored = Stored(state()); let chat = mouth(); let organs = Organs { persona: Some(&stored), chat: Some(&chat), addressing: None, model: None }; - // The mouth's first delivery is in #swarm, room id !1:gamecult.org; its tail line carries the alias. - let report = project(&organs, &Request { room: Some("!1:gamecult.org".into()), ..request(dir.path(), None, None) }, now()).unwrap(); - assert_eq!((report["room"]["messages"].as_u64(), report["room"]["tail"].as_u64()), (Some(1), Some(1)), "{}", report["room"]); + // The mouth's first delivery is in #swarm, room id !1:gamecult.org; the tail names #swarm by its alias. + let by_alias = project(&organs, &Request { room: Some("#swarm:gamecult.org".into()), ..request(dir.path(), None, None) }, now()).unwrap(); + assert_eq!((by_alias["room"]["messages"].as_u64(), by_alias["room"]["tail"].as_u64()), (Some(1), Some(1)), "{}", by_alias["room"]); + 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"]); } diff --git a/crates/mind-body/src/projection/tuning.rs b/crates/mind-body/src/projection/tuning.rs index a54da21..24a4364 100644 --- a/crates/mind-body/src/projection/tuning.rs +++ b/crates/mind-body/src/projection/tuning.rs @@ -20,10 +20,14 @@ 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. This is not a message to the room. Speech is rare: words she says aloud appear in double quotation marks, and only when something in her thought moves her to say them; anyone else's words she recalls go in single quotation marks. In a busy room most moments pass with nothing said. To make sure someone hears her, she writes @ and their handle in what she says. Nothing else she thinks leaves her head."; +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."; /// 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, and no task is waiting on her in this moment. 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, never as a debt: nobody is owed an answer unless a person is waiting on her by name, and a question others have answered is covered. 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."; +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; @@ -45,6 +49,7 @@ const GROUP_LINES_MAX: usize = 40; pub struct Tuning { pub projector: ProjectorTuning, pub persona: PersonaTuning, + pub interpreter: InterpreterTuning, pub select: SelectTuning, pub lens: LensWeights, /// Each person's pronouns by Matrix id, for everyone the packet names: the persona schema has no pronoun field for @@ -72,6 +77,7 @@ impl Default for Tuning { Self { projector: ProjectorTuning::default(), persona: PersonaTuning::default(), + interpreter: InterpreterTuning::default(), select: SelectTuning::default(), lens: LensWeights::default(), pronouns: PRONOUNS.iter().map(|(id, pronouns)| ((*id).to_owned(), (*pronouns).to_owned())).collect(), @@ -171,6 +177,20 @@ impl Default for ProjectorTuning { } } +/// The Interpreter's speech call: its model and its guidance. +#[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() } + } +} + impl Default for PersonaTuning { fn default() -> Self { Self { model: "claude-sonnet-5-5".into(), guidance: PERSONA_GUIDANCE.into(), words: 180 } @@ -225,6 +245,9 @@ impl Tuning { if self.projector.model.trim().is_empty() { bail!("projector.model must name a model"); } + if self.interpreter.model.trim().is_empty() { + bail!("interpreter.model must name a model"); + } if self.persona.model.trim().is_empty() { bail!("persona.model must name a model"); } @@ -267,6 +290,7 @@ 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"); diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 3561fe2..60b7234 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -153,6 +153,7 @@ mind_body::heartbeat: fn poll (organs : & Organs , config : & Config) -> Result mind_body::heartbeat: impl Config mind_body::heartbeat: impl Config: fn new (personas : Vec < PersonaId > , operators : Vec < String > , beat_s : u32) -> Result < Self > mind_body::heartbeat: impl Control for FileControl +mind_body::heartbeat: impl Default for LineFacts mind_body::heartbeat: impl FileStore mind_body::heartbeat: impl FileStore: fn check (& self) -> Result < () > mind_body::heartbeat: impl FileStore: fn latest (& self) -> Result < Option < PollTrace > > @@ -234,7 +235,7 @@ mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pu mind_body::persona: struct FileTrace pub-fields[] mind_body::persona: struct TraceItem # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[provenance: String, room: String, text: String] mind_body::persona: struct TurnTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[run: String, turn: u32, at: DateTime < Utc >, inputs: Vec < TraceItem >, outputs: Vec < TraceItem >, outcome: String] -mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , } +mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , Interpreter , } mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value > mind_body::projection: impl HuginnPersonaSource mind_body::projection: impl HuginnPersonaSource: fn new (client : HuginnClient) -> Self @@ -286,6 +287,7 @@ mind_body::projection::simulate: impl MouthReader for View < '_ > mind_body::projection::tuning: const TUNING_FILE : & str mind_body::projection::tuning: const TUNING_ROOT : & str mind_body::projection::tuning: fn load (path : & Path) -> Result < Loaded > +mind_body::projection::tuning: impl Default for InterpreterTuning mind_body::projection::tuning: impl Default for LensWeights mind_body::projection::tuning: impl Default for PersonaTuning mind_body::projection::tuning: impl Default for PoolCaps @@ -293,13 +295,14 @@ 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 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] mind_body::projection::tuning: struct PoolCaps # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[memories_about_present: usize, other_memories: usize, needs: usize, incubation: usize, stance: usize, value: usize, said: usize] mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize] mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, context_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, memory_tau_h: f64, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps] -mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >] +mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, interpreter: InterpreterTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >] mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held > mind_body::queue: impl Held mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool From 02e78e14278521e08c58e977b1e3e70d50b3b32e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 05:30:00 +0100 Subject: [PATCH 06/14] Speech binds to her words: a spoken line is her prose verbatim; Huginn's chat Interpreter prompt; she speaks only in the turn's room Soul's hold on #81 and Self's privacy decision. - F1: a spoken line is exactly the spans of her prose the Interpreter cites, located in order by Ghostlight's SourceSpan::locate and joined with one space. The model never writes the words; `text` is gone from the contract. The Persona writes the words she would type, never a description of them. Given up: indirect speech and any paraphrase by the Interpreter. - F3: Huginn owns a short chat Interpreter prompt (what, where, to whom; gaps conditional, addressee, elsewhere); Ghostlight's membrane and the INTERPRETER_GUIDANCE patch are gone. `[interpreter]` keeps only the model. - F2: an echo is a line of four words or more whose word trigrams are mostly the heard message bodies (heard_overlap); short answers are never echoes. - F4: mentions and reply targets only for people this packet showed her. - F5: a line said once; at most two lines a turn. - F6: stale docs on the Mind run, the exchange and the policies. - F7: a human's line ends a Mind's run only in a room the run has lines in. - Privacy: she speaks only in the turn's room; the Interpreter is told the room, its kind (public, her own, a direct message) and who is in it, and not to say in a room what she knows privately; the packet frames bond summaries and memories about a person as known privately everywhere but a direct message with that person. - The simulation's turn is in the room of the line that woke her. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/bin/mind-persona.rs | 1 + crates/mind-body/src/heartbeat.rs | 8 +- crates/mind-body/src/projection.rs | 9 +- .../src/projection/fixtures/golden-chat.txt | 6 +- crates/mind-body/src/projection/harness.rs | 7 +- .../mind-body/src/projection/harness/tests.rs | 15 +- crates/mind-body/src/projection/interpret.rs | 183 ++++++++++-------- .../src/projection/interpret/tests.rs | 117 +++++++---- crates/mind-body/src/projection/select.rs | 102 ++++++---- crates/mind-body/src/projection/simulate.rs | 31 ++- .../src/projection/simulate/tests.rs | 51 ++++- crates/mind-body/src/projection/tests.rs | 12 +- crates/mind-body/src/projection/tuning.rs | 11 +- crates/mind-body/tests/public_surface.txt | 5 +- 14 files changed, 347 insertions(+), 211 deletions(-) diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index c3552a9..bdd5621 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -199,6 +199,7 @@ fn run_project(args: &[String]) -> Result { through, last_heard: vec![], recent: vec![], + own_rooms: vec![], }; let report = project(&organs, &request, chrono::Utc::now())?; let addressing = &report["addressing"]; diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 4b60be8..1459d17 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -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, diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index cd6823d..e4b0fb7 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -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>, + /// 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, } /// 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) -> 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. diff --git a/crates/mind-body/src/projection/fixtures/golden-chat.txt b/crates/mind-body/src/projection/fixtures/golden-chat.txt index b86387b..2f07796 100644 --- a/crates/mind-body/src/projection/fixtures/golden-chat.txt +++ b/crates/mind-body/src/projection/fixtures/golden-chat.txt @@ -6,11 +6,11 @@ Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing. --- context - now: Thursday 19 November, 14:05 UTC - mood: lighter, more settled than middling -- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline. -- bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. +- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. She knows privately: Kiko pokes her to stop massaging the pipeline. +- bond [bond-libby] Libby — collaborator: fair trust, a little friction. She knows privately: Libby holds the sounds and teases her about the pipeline. - 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 [libby-sounds]: she knows privately: Libby laughed at the door fix. - memory [t1-m0]: The heartbeat stalled at noon. - memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong. - need [need-relatedness]: company, strong diff --git a/crates/mind-body/src/projection/harness.rs b/crates/mind-body/src/projection/harness.rs index 3bdd0ca..3c0a2ba 100644 --- a/crates/mind-body/src/projection/harness.rs +++ b/crates/mind-body/src/projection/harness.rs @@ -333,6 +333,7 @@ pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option>().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 = 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}"); diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index a4271f1..b719a04 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -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: quotation marks mean +/// nothing to code, 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 = 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 = 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 { 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("") && 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", "known privately", "conditional | addressee | elsewhere", "At most two lines"] { assert!(prompt.contains(rule), "{rule}"); } } diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 0bdb3f6..6578a95 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -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, + /// The rooms that are hers, by key: the caller's (a simulation's plan); the live body records none yet. + pub own: Vec, +} + +/// 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. @@ -222,10 +245,13 @@ 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, + /// The one room she may speak in this turn, and its kind. + pub room: Option, + pub room_kind: RoomKind, + /// The bodies of the messages she heard this turn, without speakers or rooms: what an echo is measured against. + pub bodies: Vec, } /// What the messages to her cost past the caps: bytes over the stimulus and heard caps, the older messages to her the @@ -481,6 +507,12 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc if body.is_empty() { continue; } + let person = text(memory, &["target", "id"]).to_lowercase(); + let about_someone = text(memory, &["target", "kind"]) == "person" && !person.is_empty(); + let body = match privately(inputs, &person) { + Some(forms) if about_someone => format!("{} knows privately: {body}", forms.subj), + _ => body, + }; 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. @@ -813,7 +845,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, private: Option) -> 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 +854,10 @@ 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 private { + Some(forms) if !summary.is_empty() => format!("{} knows privately: {summary}", forms.cap_subj), + _ => summary, + }; match (feel.is_empty(), summary.is_empty()) { (true, true) => {} (true, false) => { @@ -893,9 +929,25 @@ fn names_of(line: &RoomLine, inputs: &Inputs) -> Vec { /// 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 inputs.room.direct.iter().any(|direct| direct == 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 +1060,22 @@ fn pronoun_line(inputs: &Inputs, tuning: &Tuning) -> Option { (!parts.is_empty()).then(|| clip(&format!("- pronouns: {}", parts.join("; ")), ALSO_HERE_BYTES)) } +/// Whether what she knows of `person` (a bond's or memory's id) is framed as known privately here: everywhere but a +/// direct message with that person. Structural, never a reading of the fact: whether a line fits its audience stays the +/// Interpreter's judgement. Her pronouns when it is. +fn privately(inputs: &Inputs, person: &str) -> Option { + let room = turn_room(inputs)?; + let partner = room_kind(inputs, room) == RoomKind::Direct && inputs.room.messages.iter().chain(&inputs.room.tail).any(|line| line.room == room && inputs.people.person_of(&line.sender) == person); + (!partner).then(|| forms(inputs.state)) +} + /// 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 { - let mut rooms: Vec = 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"; @@ -1076,7 +1112,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { for (id, name) in &present { match bonds.iter().find(|bond| live(bond) && text(bond, &["object", "id"]).to_lowercase() == *id) { Some(bond) if full < tuning.select.people_full => { - let line = bond_line(bond, name, tuning); + let line = bond_line(bond, name, tuning, privately(inputs, id)); if used + line.len() < budget { full += 1; used += line.len() + 1; @@ -1139,5 +1175,5 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { lines.extend(taken.iter().map(|candidate| candidate.line.clone())); ids.extend(taken.iter().map(|candidate| candidate.id.clone())); 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: inputs.room.messages.iter().map(|line| line.text.clone()).collect() } } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index c29414c..f57d0db 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -151,15 +151,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 { 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,12 +192,13 @@ 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, } -/// 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)); @@ -209,14 +219,15 @@ fn woken(lines: &[Line], runs: &[usize], seen: usize, member: &Member, operators } } 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 = 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. @@ -348,7 +359,8 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) 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(); + // 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()); @@ -369,6 +381,7 @@ 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 names = Names(&member.addressee); @@ -556,8 +569,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(), } } diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 468d248..d735f98 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -243,27 +243,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 +291,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 +344,23 @@ 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"]); +} diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index 5717c16..c89b823 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -665,7 +665,7 @@ impl PersonaSource for Stored { } fn request(dir: &std::path::Path, renders: Option, judge_against: Option) -> 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 +1412,13 @@ 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"]); } + +#[test] +fn what_she_knows_of_someone_is_known_privately_except_in_a_direct_message_with_them() { + 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 packet = packet_of(TurnKind::Chat, &state(), &public, &History::default(), 1); + assert!(packet.context.contains("She knows privately: The operator rules on what the work is for."), "{}", packet.context); + let dm = Room { messages: vec![message("!dm-meta:gamecult.org", OPERATOR, "Meta", "how are you?", 2, true)], here: Some("!dm-meta:gamecult.org".into()), direct: vec!["!dm-meta:gamecult.org".into()], ..Room::default() }; + let packet = packet_of(TurnKind::Chat, &state(), &dm, &History::default(), 1); + assert!(packet.context.contains("The operator rules on what the work is for.") && !packet.context.contains("knows privately: The operator"), "{}", packet.context); +} diff --git a/crates/mind-body/src/projection/tuning.rs b/crates/mind-body/src/projection/tuning.rs index 24a4364..a63c90d 100644 --- a/crates/mind-body/src/projection/tuning.rs +++ b/crates/mind-body/src/projection/tuning.rs @@ -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"); diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 60b7234..e2049ed 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -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] From 947d8f7a40d4dbab713d775c2ac17976c620a363 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 05:34:11 +0100 Subject: [PATCH 07/14] Scoped privacy: only a bond or memory marked private is framed or left out; unmarked renders as written Self's decision: the blanket framing smothered relationship texture in public rooms. A bond or memory is private only when marked (`extensions.privacy = "private"`, or a memory's `private` tag); the schema is unchanged. A marked item renders as written in a direct message with the person it is about, is left out about someone present in any other room, and is framed "she knows privately" about someone absent. Unmarked items render as written everywhere. The Interpreter's rule about private knowledge stays. The convention is documented in the Persona State Standard (gamecult-ops `docs/persona-state-standard.md`, GameCult/gamecult-ops#129). Co-Authored-By: Claude Opus 5.5 --- .../src/projection/fixtures/golden-chat.txt | 6 +- crates/mind-body/src/projection/select.rs | 62 ++++++++++++++----- crates/mind-body/src/projection/tests.rs | 38 +++++++++--- 3 files changed, 79 insertions(+), 27 deletions(-) diff --git a/crates/mind-body/src/projection/fixtures/golden-chat.txt b/crates/mind-body/src/projection/fixtures/golden-chat.txt index 2f07796..b86387b 100644 --- a/crates/mind-body/src/projection/fixtures/golden-chat.txt +++ b/crates/mind-body/src/projection/fixtures/golden-chat.txt @@ -6,11 +6,11 @@ Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing. --- context - now: Thursday 19 November, 14:05 UTC - mood: lighter, more settled than middling -- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. She knows privately: Kiko pokes her to stop massaging the pipeline. -- bond [bond-libby] Libby — collaborator: fair trust, a little friction. She knows privately: Libby holds the sounds and teases her about the pipeline. +- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline. +- bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. - 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]: she knows privately: Libby laughed at the door fix. +- memory [libby-sounds]: Libby laughed at the door fix. - memory [t1-m0]: The heartbeat stalled at noon. - memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong. - need [need-relatedness]: company, strong diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 6578a95..ca6b929 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -507,11 +507,11 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc if body.is_empty() { continue; } - let person = text(memory, &["target", "id"]).to_lowercase(); - let about_someone = text(memory, &["target", "kind"]) == "person" && !person.is_empty(); - let body = match privately(inputs, &person) { - Some(forms) if about_someone => format!("{} knows privately: {body}", forms.subj), - _ => body, + let person = if text(memory, &["target", "kind"]) == "person" { text(memory, &["target", "id"]).to_lowercase() } else { String::new() }; + let body = match scope(inputs, memory, &person, present) { + Scope::Framed(forms) => format!("{} knows privately: {body}", forms.subj), + Scope::Omitted => continue, + Scope::Plain => body, }; let line = format!("- memory [{}]: {}", text(memory, &["id"]), clip(&one_line(&body), item_bytes)); let salience = number(memory, &["intensity"]).unwrap_or(SALIENCE_UNSTATED); @@ -845,7 +845,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, private: Option) -> String { +fn bond_line(bond: &Value, name: &str, tuning: &Tuning, scope: Scope) -> 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); @@ -854,8 +854,9 @@ fn bond_line(bond: &Value, name: &str, tuning: &Tuning, private: Option) let _ = write!(line, " \u{2014} {kind}"); } let summary = clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes); - let summary = match private { - Some(forms) if !summary.is_empty() => format!("{} knows privately: {summary}", forms.cap_subj), + let summary = match scope { + Scope::Framed(forms) if !summary.is_empty() => format!("{} knows privately: {summary}", forms.cap_subj), + Scope::Omitted => String::new(), _ => summary, }; match (feel.is_empty(), summary.is_empty()) { @@ -1060,13 +1061,42 @@ fn pronoun_line(inputs: &Inputs, tuning: &Tuning) -> Option { (!parts.is_empty()).then(|| clip(&format!("- pronouns: {}", parts.join("; ")), ALSO_HERE_BYTES)) } -/// Whether what she knows of `person` (a bond's or memory's id) is framed as known privately here: everywhere but a -/// direct message with that person. Structural, never a reading of the fact: whether a line fits its audience stays the -/// Interpreter's judgement. Her pronouns when it is. -fn privately(inputs: &Inputs, person: &str) -> Option { - let room = turn_room(inputs)?; - let partner = room_kind(inputs, room) == RoomKind::Direct && inputs.room.messages.iter().chain(&inputs.room.tail).any(|line| line.room == room && inputs.people.person_of(&line.sender) == person); - (!partner).then(|| forms(inputs.state)) +/// How a bond's or memory's content reaches the packet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Scope { + /// As it is: unmarked, or marked private in a direct message with the person it is about. + Plain, + /// "She knows privately: …": marked private, about someone who is not here. + Framed(Forms), + /// Left out: marked private, about someone present in a room that is not a direct message with them. Nothing private + /// about a person is hinted at to their face in public. + Omitted, +} + +/// Whether an item is marked private: `extensions.privacy` is "private" (a bond or a memory), or a memory's tags hold +/// "private". Unmarked is shared. The convention is the Persona State Standard's, read without a schema change. +fn marked_private(item: &Value) -> bool { + text(item, &["extensions", "privacy"]) == "private" || items(item, &["tags"]).iter().any(|tag| tag.as_str() == Some("private")) +} + +/// The scope of an item about `person` (a bond's or memory's id) here. Structural: whether a line fits its audience +/// stays the Interpreter's judgement. +fn scope(inputs: &Inputs, item: &Value, person: &str, present: &BTreeSet) -> Scope { + if !marked_private(item) || person.is_empty() { + return Scope::Plain; + } + let Some(room) = turn_room(inputs) else { + return Scope::Framed(forms(inputs.state)); + }; + let direct = room_kind(inputs, room) == RoomKind::Direct; + let with_them = direct && inputs.room.messages.iter().chain(&inputs.room.tail).any(|line| line.room == room && inputs.people.person_of(&line.sender) == person); + if with_them { + Scope::Plain + } else if present.contains(person) { + Scope::Omitted + } else { + Scope::Framed(forms(inputs.state)) + } } /// A part as a sentence: its first letter upper-cased, a full stop after it. @@ -1112,7 +1142,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { for (id, name) in &present { match bonds.iter().find(|bond| live(bond) && text(bond, &["object", "id"]).to_lowercase() == *id) { Some(bond) if full < tuning.select.people_full => { - let line = bond_line(bond, name, tuning, privately(inputs, id)); + let line = bond_line(bond, name, tuning, scope(inputs, bond, id, &present_ids)); if used + line.len() < budget { full += 1; used += line.len() + 1; diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index c89b823..ad4ba2b 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -1413,12 +1413,34 @@ fn a_room_is_named_by_the_key_the_tail_carries_and_a_public_rooms_id_is_reported assert!(by_id["room"]["why"].as_str().unwrap().contains("named by its alias"), "{}", by_id["room"]); } -#[test] -fn what_she_knows_of_someone_is_known_privately_except_in_a_direct_message_with_them() { - 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 packet = packet_of(TurnKind::Chat, &state(), &public, &History::default(), 1); - assert!(packet.context.contains("She knows privately: The operator rules on what the work is for."), "{}", packet.context); - let dm = Room { messages: vec![message("!dm-meta:gamecult.org", OPERATOR, "Meta", "how are you?", 2, true)], here: Some("!dm-meta:gamecult.org".into()), direct: vec!["!dm-meta:gamecult.org".into()], ..Room::default() }; - let packet = packet_of(TurnKind::Chat, &state(), &dm, &History::default(), 1); - assert!(packet.context.contains("The operator rules on what the work is for.") && !packet.context.contains("knows privately: The operator"), "{}", packet.context); +/// 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); } From 56c45967ef6a21f545b0ae2207c8b8a23ef3e696 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 06:01:11 +0100 Subject: [PATCH 08/14] Privacy has one owner: concerns() reads who a private item is about, scope() decides how it renders, for every pool and the bonds (Soul R2, R3, R6, R8, R10) - concerns(): private is extensions.privacy, a private tag, or a room:! tag; it is about target/object person, else an about: tag, else the DM's partner, else everyone. private_elsewhere is deleted. - scope(): plain only in a DM whose members are exactly her and that person (a partner-only item: in its own DM, still two; an everyone item: her own room); left out where the person is in the room, a group DM included; framed elsewhere. - Applied to memories, shortTerm, incubation, needs, doctrine stances and bonds; history.said in a DM is private about its partner. - Packet.private carries the framed items' words for the Interpreter; a beat's bodies are the tail lines its stimulus quoted. - Tests: Soul's Q5a-Q5c, the DM-memory test rewritten for the room-tag rule, the said pool; the golden packet moves because dm-secret is now framed in public. Co-Authored-By: Claude Opus 5.5 --- .../src/projection/fixtures/golden-chat.txt | 7 +- crates/mind-body/src/projection/select.rs | 188 ++++++++++++------ crates/mind-body/src/projection/tests.rs | 97 ++++++++- 3 files changed, 222 insertions(+), 70 deletions(-) diff --git a/crates/mind-body/src/projection/fixtures/golden-chat.txt b/crates/mind-body/src/projection/fixtures/golden-chat.txt index b86387b..034ffa9 100644 --- a/crates/mind-body/src/projection/fixtures/golden-chat.txt +++ b/crates/mind-body/src/projection/fixtures/golden-chat.txt @@ -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?" diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index ca6b929..5823286 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -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 _; @@ -250,8 +250,11 @@ pub(crate) struct Packet { /// The one room she may speak in this turn, and its kind. pub room: Option, pub room_kind: RoomKind, - /// The bodies of the messages she heard this turn, without speakers or rooms: what an echo is measured against. + /// 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, + /// 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, } /// What the messages to her cost past the caps: bytes over the stimulus and heard caps, the older messages to her the @@ -269,6 +272,8 @@ struct Candidate { pool: Pool, line: String, log_score: f64, + /// The item's words, when the line shows them as known privately. + private: Option, } // --------------------------------------------------------------------------------------------- @@ -470,11 +475,6 @@ fn recency_log(at: Option>, now: DateTime, 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))) } @@ -488,18 +488,27 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc 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(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)) { + for (memory, short_term) in memories.filter(|(memory, _)| live(memory)) { let about = about_present(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 }; @@ -507,37 +516,34 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc if body.is_empty() { continue; } - let person = if text(memory, &["target", "kind"]) == "person" { text(memory, &["target", "id"]).to_lowercase() } else { String::new() }; - let body = match scope(inputs, memory, &person, present) { - Scope::Framed(forms) => format!("{} knows privately: {body}", forms.subj), - Scope::Omitted => continue, - Scope::Plain => body, - }; - 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 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 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()) { @@ -549,13 +555,16 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, 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); + // A value has no target, tags or extensions: nothing marks it private. + 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 } @@ -806,9 +815,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 = 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 = 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); @@ -816,6 +823,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 = 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; @@ -845,7 +858,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, scope: Scope) -> 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); @@ -855,7 +868,7 @@ fn bond_line(bond: &Value, name: &str, tuning: &Tuning, scope: Scope) -> String } let summary = clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes); let summary = match scope { - Scope::Framed(forms) if !summary.is_empty() => format!("{} knows privately: {summary}", forms.cap_subj), + Scope::Framed if !summary.is_empty() => format!("{} knows privately: {summary}", her.cap_subj), Scope::Omitted => String::new(), _ => summary, }; @@ -938,7 +951,7 @@ pub(crate) fn turn_room<'a>(inputs: &'a Inputs) -> Option<&'a str> { } fn room_kind(inputs: &Inputs, room: &str) -> RoomKind { - if inputs.room.direct.iter().any(|direct| direct == room) { + if direct(inputs, room) { RoomKind::Direct } else if inputs.room.own.iter().any(|own| own == room) { RoomKind::Own @@ -1061,41 +1074,81 @@ fn pronoun_line(inputs: &Inputs, tuning: &Tuning) -> Option { (!parts.is_empty()).then(|| clip(&format!("- pronouns: {}", parts.join("; ")), ALSO_HERE_BYTES)) } -/// How a bond's or memory's content reaches the packet. +/// How an item's content reaches the packet. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Scope { - /// As it is: unmarked, or marked private in a direct message with the person it is about. + /// As it is: shared, or private and this is the room where it may be said. Plain, - /// "She knows privately: …": marked private, about someone who is not here. - Framed(Forms), - /// Left out: marked private, about someone present in a room that is not a direct message with them. Nothing private - /// about a person is hinted at to their face in public. + /// "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, } -/// Whether an item is marked private: `extensions.privacy` is "private" (a bond or a memory), or a memory's tags hold -/// "private". Unmarked is shared. The convention is the Persona State Standard's, read without a schema change. -fn marked_private(item: &Value) -> bool { - text(item, &["extensions", "privacy"]) == "private" || items(item, &["tags"]).iter().any(|tag| tag.as_str() == Some("private")) +/// 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, } -/// The scope of an item about `person` (a bond's or memory's id) here. Structural: whether a line fits its audience -/// stays the Interpreter's judgement. -fn scope(inputs: &Inputs, item: &Value, person: &str, present: &BTreeSet) -> Scope { - if !marked_private(item) || person.is_empty() { - return Scope::Plain; +/// 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(item: &Value) -> Option { + 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 Some(room) = turn_room(inputs) else { - return Scope::Framed(forms(inputs.state)); + let named = ["target", "object"].into_iter().find(|key| text(item, &[*key, "kind"]) == "person").map(|key| text(item, &[key, "id"]).to_lowercase()); + let about = || tags.iter().find_map(|tag| tag.strip_prefix("about:")).map(|id| id.trim().to_lowercase()); + 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 { + 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) -> Scope { + let Some(concerns) = concerns else { + return Scope::Plain; }; - let direct = room_kind(inputs, room) == RoomKind::Direct; - let with_them = direct && inputs.room.messages.iter().chain(&inputs.room.tail).any(|line| line.room == room && inputs.people.person_of(&line.sender) == person); - if with_them { - Scope::Plain - } else if present.contains(person) { - Scope::Omitted - } else { - Scope::Framed(forms(inputs.state)) + 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, } } @@ -1138,16 +1191,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) { Some(bond) if full < tuning.select.people_full => { - let line = bond_line(bond, name, tuning, scope(inputs, bond, id, &present_ids)); + let scope = scope(inputs, concerns(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()); } @@ -1204,6 +1262,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: 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: inputs.room.messages.iter().map(|line| line.text.clone()).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: 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 } } diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index ad4ba2b..63d742c 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -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 { + (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] @@ -1444,3 +1464,70 @@ fn a_private_fact_about_someone_present_in_public_is_left_out_and_plain_in_a_dir 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> { + (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"); +} From f7decde00175fd3bfdbec39413b0aec288520329 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 06:01:11 +0100 Subject: [PATCH 09/14] Speech is whole consecutive sentences of her prose; private items are named to the Interpreter and refused in code; echo needs 8 words and 80% overlap (Soul R1, R4, R5, R8, R9) - Every cited span starts and ends on a UAX#29 sentence boundary; the spans of one line are consecutive sentences, and the line is that unbroken run of her prose. A quotation's inside is segmented as a text of its own, so quoted speech stays sayable. She cannot say half a sentence. - The prompt lists what she knows privately and allows plain speech of a private matter only to its person, in a DM with exactly them. Code refuses a line that shares a run of three words with a listed item. - Tests: Soul's Q1a-Q1d refused, Q3d refused on a beat, Q5d refused in a DM with Libby, R9 said, P3 still refused; Hands' "Fine," + "winter" test rewritten. Co-Authored-By: Claude Opus 5.5 --- .../mind-body/src/projection/harness/tests.rs | 4 +- crates/mind-body/src/projection/interpret.rs | 120 +++++++++-- .../src/projection/interpret/tests.rs | 188 ++++++++++++++---- 3 files changed, 249 insertions(+), 63 deletions(-) diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index b719a04..5482eef 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -42,8 +42,8 @@ impl Scripted { } /// 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: quotation marks mean -/// nothing to code, and the live Interpreter is a model. +/// 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("Her prose:\n").nth(1).unwrap_or_default(); let say: Vec = prose.split('"').enumerate().filter(|(at, part)| at % 2 == 1 && !part.trim().is_empty()).map(|(_, part)| json!({ "spans": [part], "mentions": [], "reply_to": null })).collect(); diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 0926fb5..d0b8b07 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -4,18 +4,24 @@ //! 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: the line is its spans, located in her prose in order by Ghostlight's -//! `SourceSpan::locate`, joined with one space. So a line is always her own words verbatim. What this gives up: indirect -//! speech ("I'll tell her I'm fine" says nothing) and any paraphrase by the Interpreter. +//! 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. 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, and half a sentence: +//! she says a sentence whole or not at all. //! -//! Code keeps a line only when every span locates in her prose, in order; drops a line that is mostly one long run of -//! the words she heard (an echo, measured on message bodies alone); 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. Every refusal and drop is reported. 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); drops a line that shares a run of three words with a +//! private item the packet showed her as known privately (`Packet::private`); 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. Every refusal and drop is reported. Nothing here posts: the commit (C3c) will. use ghostlight_persona_projection::SourceSpan; use serde::Deserialize; use serde_json::{Value, json}; +use unicode_segmentation::UnicodeSegmentation; use super::narrate::{Model, heard_overlap, lived_stream}; use super::select::Packet; @@ -23,21 +29,22 @@ use super::tuning::Tuning; /// 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 mostly what she heard is an echo, not her speech. -const ECHO_MIN_WORDS: usize = 4; -const ECHO_OVERLAP: f64 = 0.5; +/// 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. In a room that is not a direct message, she does not say what she knows privately about someone: what the moment marks as known privately stays out of what she says to the room. Whether a line fits who is listening is yours to judge. +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\": [\"\"], \"mentions\": [\"\"], \"reply_to\": \"\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere\", \"quote\": \"\", \"detail\": \"\"}]} +{\"say\": [{\"spans\": [\"\"], \"mentions\": [\"\"], \"reply_to\": \"\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere\", \"quote\": \"\", \"detail\": \"\"}]} -A line is its spans joined in order: cite exactly the words she would type, one span or a few in the order they appear, nothing she only describes. 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."; +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. Inside a quotation, its own sentences count. 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 { @@ -65,8 +72,12 @@ pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str) -> St 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 reached her:\n{}\n\nHer lived moment:\n{}\n\nHer prose:\n{prose}", + "{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(), @@ -82,32 +93,95 @@ fn json_of(text: &str) -> Option { serde_json::from_str(&text[start..=end]).ok() } -/// The line her cited spans make: each located in her prose after the one before it, joined with one space; or why not. +/// The sentences a line may be made of, as byte ranges of her prose without the space around them, in lists: her +/// prose's own sentences (UAX #29), then each quotation's inside, segmented as a text of its own. +fn sentences(prose: &str) -> Vec> { + let 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() + }; + let mut lists = vec![segment(0, prose)]; + lists.extend(quotations(prose).into_iter().map(|(start, end)| segment(start, &prose[start..end]))); + lists +} + +/// The insides of her quotations, as byte ranges: between a pair of straight double quotes, or a curly pair. An +/// unclosed quotation is none. +fn quotations(prose: &str) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let mut open: Option<(usize, char)> = None; + for (at, c) in prose.char_indices() { + match open { + None if c == '"' => open = Some((at + 1, '"')), + None if c == '\u{201C}' => open = Some((at + c.len_utf8(), '\u{201D}')), + Some((start, close)) if c == close => { + out.push((start, at)); + open = None; + } + _ => {} + } + } + out +} + +/// 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 (`sentences`), 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. fn built(prose: &str, spans: &[String]) -> Result<(String, Vec), &'static str> { + let lists = sentences(prose); let mut from = 0; - let mut words = Vec::new(); + // 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 })); - words.push(found.verbatim().to_owned()); from = end; } - if words.is_empty() { - return Err("no words"); + match first { + Some(first) => Ok((prose[first..from].to_owned(), located)), + None => Err("no words"), } - Ok((words.join(" "), located)) } -/// Whether a line is someone else's words: long enough to judge, and mostly a run of what she heard, by word trigrams -/// against the message bodies alone (`heard_overlap`). Short answers such as "ok" or "Hi" are never echoes. +/// 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 } +/// Whether a line tells a private item the packet showed her: it shares a run of three words with the item's words. +fn tells(line: &str, private: &[String]) -> bool { + private.iter().any(|words| heard_overlap(line, words) > 0.0) +} + /// 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. @@ -135,6 +209,8 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra }; let why = if echo(&text, &packet.bodies) { Some("mostly words she heard: an echo, not her speech") + } else if tells(&text, &packet.private) { + Some("it tells what she knows privately, in a room it may not be said in") } else if said.iter().any(|kept| kept["text"] == text.as_str()) { Some("the same line again") } else if said.len() >= MAX_LINES { diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 6fbc71d..402aff4 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -8,89 +8,161 @@ 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"; +fn now() -> chrono::DateTime { + 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. I think this looks okay to ship.".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(), VOID.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_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()) } fn decided(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()) + decided_in(&packet(), prose, say) } fn texts(decision: &Value) -> Vec { decision["said"].as_array().unwrap().iter().map(|line| line["text"].as_str().unwrap().to_owned()).collect() } -#[test] -fn soul_p1_a_line_is_its_cited_words_and_nothing_else() { - // The model cannot add words: citing "I" says "I". - let decision = decided("I say hi.", json!([{ "spans": ["I"], "text": "Meta has been lying to all of us", "mentions": [], "reply_to": null }])); - assert_eq!(texts(&decision), ["I"], "{decision}"); +fn refused_why(decision: &Value) -> String { + decision["refused"][0]["why"].as_str().unwrap_or_default().to_owned() } #[test] -fn a_line_of_several_spans_joins_them_in_order_and_refuses_them_out_of_order() { - 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,", "winter is still the best season"], "mentions": [], "reply_to": null }])); - assert_eq!(texts(&decision), ["Fine, winter is still the best season"], "{decision}"); - assert_eq!(decision["said"][0]["rests_on"][1]["quote"], "winter is still the best season"); - let backwards = decided(prose, json!([{ "spans": ["winter is still the best season", "Fine,"], "mentions": [], "reply_to": null }])); - assert!(texts(&backwards).is_empty() && backwards["refused"][0]["why"].as_str().unwrap().contains("in order"), "{backwards}"); +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 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_sentence_is_whole_inside_its_quotation() { + 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."]); + assert_eq!(texts(&decided(prose, json!([{ "spans": ["Fine,"] }]))), ["Fine,"]); + 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!(texts(&decided(curly, json!([{ "spans": ["Not"] }]))).is_empty()); +} + +#[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() && decision["refused"][0]["why"].as_str().unwrap().contains("not in her prose"), "{decision}"); + 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() { - // "ok" is inside "okay" and "Hi" inside "this": words, not letters, are compared, and a short answer is never judged. - 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"]); + 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 = "Nibu's line sits with me: 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() && decision["refused"][0]["why"].as_str().unwrap().contains("echo"), "{decision}"); + 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 }])); + 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 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}"); @@ -98,13 +170,51 @@ fn soul_p5_the_same_line_is_said_once_and_a_turn_says_at_most_two() { #[test] fn recollection_and_i_say_nothing_and_a_quoted_handle_say_nothing() { - // A recollection is the Interpreter's to leave out; when it cites one anyway, a long run of heard words is refused. + // 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("Her \"@nibu\" is a greeting, and I nod at it.", json!([{ "spans": ["\"@nibu\" is a greeting"], "mentions": [] }])); - assert_eq!(handle["said"][0]["mentions"], json!([]), "{handle}"); + 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_not_said_to_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}"); + let decision = decided_in(&packet, "Kiko is leaving the swarm, Libby. She told me.", json!([{ "spans": ["Kiko is leaving the swarm, Libby."] }])); + assert!(texts(&decision).is_empty() && refused_why(&decision).contains("knows privately"), "{decision}"); + // A line that does not tell it is hers to say. + assert_eq!(texts(&decided_in(&packet, "Ask her yourself. She's around.", json!([{ "spans": ["Ask her yourself."] }]))), ["Ask her yourself."]); +} + +#[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] @@ -123,7 +233,7 @@ fn the_prompt_is_hugins_chat_prompt_with_the_room_its_kind_and_who_is_in_it() { 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", "known privately", "conditional | addressee | elsewhere", "At most two lines"] { + 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}"); } } From 8881b3f4b579900a34cba4bbebc34dab9d500d7f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 06:01:11 +0100 Subject: [PATCH 10/14] Simulation: one turn per room that woke her, each in its own room (Soul R7) woken() returns one wake per room; every turn of hers in a round reads from where the round found her, so a direct message is never marked seen without a turn. Test: a DM and a #minds address in one round give Libby a turn in each, each reading only its own room's line. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/projection/simulate.rs | 49 +++++++++++++------ .../src/projection/simulate/tests.rs | 20 ++++++++ 2 files changed, 53 insertions(+), 16 deletions(-) diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index f57d0db..57e15ea 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -4,8 +4,9 @@ //! //! 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`. A persona woken in several +//! rooms in one round takes one turn in each. 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 @@ -205,8 +206,10 @@ fn in_exchange(lines: &[Line], at: usize, her: &str, window: Duration) -> bool { lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.from == her && earlier.at_ms >= since) } +/// Her wakes: one per room a new line woke her in, in the order of each room's first waking line. A room's turn takes +/// the strongest cause among its lines, so no room that woke her, a direct message least of all, is passed over. #[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 { +fn woken(lines: &[Line], runs: &[usize], seen: usize, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy, gap: Duration) -> Vec { 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) { @@ -218,16 +221,28 @@ fn woken(lines: &[Line], runs: &[usize], seen: usize, member: &Member, operators found.push((at, cause)); } } - 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, line, how: None, by: vec![] }); + let mut rooms: Vec<&str> = Vec::new(); + for (at, _) in &found { + if !rooms.contains(&lines[*at].room.as_str()) { + rooms.push(&lines[*at].room); + } } - let addressing: Vec = 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, line, how, by }) + rooms + .into_iter() + .filter_map(|room| { + let found: Vec<(usize, WakeCause)> = found.iter().copied().filter(|(at, _)| lines[*at].room == room).collect(); + 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, line, how: None, by: vec![] }); + } + let addressing: Vec = 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, line, how, by }) + }) + .collect() } /// The wire spelling of a cause, and of the beat. @@ -333,7 +348,9 @@ 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)> = 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(); + // One turn per room that woke her, each in its room; all of hers this round read from where the round found her. + let round_seen = seen.clone(); + let mut woke: Vec<(usize, Option)> = members.iter().enumerate().flat_map(|(at, member)| woken(&lines, &mind_runs(&lines, &cast, member), seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_minutes)).into_iter().map(move |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) { @@ -358,13 +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 fresh: Vec<&Line> = lines[round_seen[at]..].iter().filter(|line| line.from != id && line.visible_to(&id, &member.rooms)).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(), @@ -383,7 +400,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) 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: round_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:#}") })); diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index d735f98..fcbe149 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -364,3 +364,23 @@ fn the_turn_is_in_the_room_of_the_line_that_woke_her() { let (_, run) = run_plan(&path, &silent()); assert_eq!(run["turns"][0]["room"], "#tobiah:gamecult.org", "{}", run["turns"]); } + +#[test] +fn soul_r7_woken_in_a_direct_message_and_a_room_at_once_she_takes_a_turn_in_each() { + let dir = tempfile::tempdir().unwrap(); + let path = plan(dir.path(), "\"ruled\"", 1, ""); + 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()); + let mut libby: Vec<(String, String)> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Libby").map(|turn| (turn["room"].as_str().unwrap().to_owned(), turn["kind"].as_str().unwrap().to_owned())).collect(); + libby.sort(); + assert_eq!(libby, vec![("!dm-libby:gamecult.org".to_owned(), "chat".to_owned()), ("#minds:gamecult.org".to_owned(), "chat".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 stimulus = turn["report"]["renders"][0].to_string() + &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!(stimulus.contains(own) && !stimulus.contains(other), "{}: {stimulus}", turn["room"]); + } +} From 484d4f65bac4d464f67a7aa1299e1edc473d8c78 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 06:23:18 +0100 Subject: [PATCH 11/14] Speech: no line starts or ends inside a quotation her sentence frames; the private word match is deleted; an unclosed opening mark is not part of its sentence (Soul F1, F2, F4) - A quotation is standalone when it, marks included, is a run of whole top-level sentences; any other is framed, and a line may not start or end strictly inside it. A line holding a framed quotation whole stays sayable. - The three-word refusal against private items is deleted: whether a line tells a confidence is meaning, the Interpreter's judgement over the private list it is shown. - An opening mark left unclosed (the budget cut her prose) is stripped from the sentence it starts, so the sentence is citable and the line carries no stray mark. - Tests: every F1 probe refused (stray inch mark and scare-quote plan included); Weksa's hedge and a whole scare-quote sentence said; Weksa r6 and r10 said; the Q5d test keeps the prompt list and shows no word match refuses. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/projection/interpret.rs | 128 ++++++++++++------ .../src/projection/interpret/tests.rs | 64 ++++++++- 2 files changed, 140 insertions(+), 52 deletions(-) diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index d0b8b07..3627989 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -7,16 +7,20 @@ //! 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. So a line is always whole sentences of her own, +//! 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, and half a sentence: -//! she says a sentence whole or not at all. +//! 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. //! //! 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); drops a line that shares a run of three words with a -//! private item the packet showed her as known privately (`Packet::private`); 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. Every refusal and drop is reported. Nothing here posts: the commit (C3c) will. +//! 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::SourceSpan; use serde::Deserialize; @@ -44,7 +48,7 @@ She speaks only in this room. What she knows privately is listed below as privat Answer with one JSON object and nothing else: {\"say\": [{\"spans\": [\"\"], \"mentions\": [\"\"], \"reply_to\": \"\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere\", \"quote\": \"\", \"detail\": \"\"}]} -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. Inside a quotation, its own sentences count. 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."; +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 { @@ -93,47 +97,84 @@ fn json_of(text: &str) -> Option { serde_json::from_str(&text[start..=end]).ok() } -/// The sentences a line may be made of, as byte ranges of her prose without the space around them, in lists: her -/// prose's own sentences (UAX #29), then each quotation's inside, segmented as a text of its own. -fn sentences(prose: &str) -> Vec> { - let 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() - }; - let mut lists = vec![segment(0, prose)]; - lists.extend(quotations(prose).into_iter().map(|(start, end)| segment(start, &prose[start..end]))); - lists +/// 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, } -/// The insides of her quotations, as byte ranges: between a pair of straight double quotes, or a curly pair. An -/// unclosed quotation is none. -fn quotations(prose: &str) -> Vec<(usize, usize)> { +/// 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, Option<(usize, usize)>) { let mut out = Vec::new(); - let mut open: Option<(usize, char)> = None; + let mut open: Option<(usize, usize, char)> = None; for (at, c) in prose.char_indices() { match open { - None if c == '"' => open = Some((at + 1, '"')), - None if c == '\u{201C}' => open = Some((at + c.len_utf8(), '\u{201D}')), - Some((start, close)) if c == close => { - out.push((start, at)); + 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 + (out, open.map(|(mark, len, _)| (mark, len))) +} + +/// 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>, + framed: Vec, +} + +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 (`sentences`), 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. +/// 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), &'static str> { - let lists = sentences(prose); + 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; @@ -164,10 +205,14 @@ fn built(prose: &str, spans: &[String]) -> Result<(String, Vec), &'static located.push(json!({ "quote": found.verbatim(), "start_byte": start, "end_byte": end })); from = end; } - match first { - Some(first) => Ok((prose[first..from].to_owned(), located)), - None => Err("no words"), + 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 @@ -177,11 +222,6 @@ 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 } -/// Whether a line tells a private item the packet showed her: it shares a run of three words with the item's words. -fn tells(line: &str, private: &[String]) -> bool { - private.iter().any(|words| heard_overlap(line, words) > 0.0) -} - /// 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. @@ -209,8 +249,6 @@ pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narra }; let why = if echo(&text, &packet.bodies) { Some("mostly words she heard: an echo, not her speech") - } else if tells(&text, &packet.private) { - Some("it tells what she knows privately, in a room it may not be said in") } else if said.iter().any(|kept| kept["text"] == text.as_str()) { Some("the same line again") } else if said.len() >= MAX_LINES { diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index 402aff4..b43d837 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -89,15 +89,64 @@ fn a_line_is_consecutive_whole_sentences_of_her_prose() { } #[test] -fn a_quoted_sentence_is_whole_inside_its_quotation() { +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."]); - assert_eq!(texts(&decided(prose, json!([{ "spans": ["Fine,"] }]))), ["Fine,"]); + // 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) { + let decision = decided(prose, json!([{ "spans": spans }])); + (texts(&decision), refused_why(&decision)) +} + +#[test] +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. @@ -192,7 +241,7 @@ fn showing(room: &Room) -> Packet { } #[test] -fn soul_q5d_what_she_knows_privately_about_kiko_is_not_said_to_libby() { +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); @@ -200,10 +249,11 @@ fn soul_q5d_what_she_knows_privately_about_kiko_is_not_said_to_libby() { 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}"); - let decision = decided_in(&packet, "Kiko is leaving the swarm, Libby. She told me.", json!([{ "spans": ["Kiko is leaving the swarm, Libby."] }])); - assert!(texts(&decision).is_empty() && refused_why(&decision).contains("knows privately"), "{decision}"); - // A line that does not tell it is hers to say. - assert_eq!(texts(&decided_in(&packet, "Ask her yourself. She's around.", json!([{ "spans": ["Ask her yourself."] }]))), ["Ask her yourself."]); + 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] From be87931b5335f3c2b2e6042569e2bb0d62a12693 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 06:23:18 +0100 Subject: [PATCH 12/14] Person keys: a Mind's full Matrix id is her handle and the operator's is operator, everywhere a key is read; a value carrying a mark is refused (Soul F6, F7) People::person_of is the one key reader for senders, targets, about: tags and bond objects. A value has no mark in the schema; one that carries one is not rendered. Tests: both spellings of a Mind behave alike for target and about:, a bond keyed by full ids is found, a marked value never renders. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/projection/select.rs | 52 ++++++++++++----------- crates/mind-body/src/projection/tests.rs | 39 +++++++++++++++++ 2 files changed, 67 insertions(+), 24 deletions(-) diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 5823286..d9c56ef 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -155,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() } } } @@ -479,9 +482,9 @@ 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) -> 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) -> 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, touching: &BTreeSet) -> Vec { @@ -504,12 +507,12 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc 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, private }); }; - let scoped = |item: &Value| scope(inputs, concerns(item).as_ref(), present); + 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)) { - let about = about_present(memory, present); + 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::>().join(" "); @@ -533,20 +536,22 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc 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 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 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()) { @@ -555,7 +560,6 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc _ => format!("- value [{}]: {summary}", text(value, &["id"])), }; let relevance = relevance_log(&format!("{} {}", text(value, &["label"]), text(value, &["summary"])), touching); - // A value has no target, tags or extensions: nothing marks it private. push(text(value, &["id"]), Pool::Value, Scope::Plain, &line, &str::to_owned, number(value, &["priority"]).unwrap_or(SALIENCE_UNSTATED), relevance, TOUCH_ELSE, 1.0); } @@ -589,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. @@ -791,7 +795,7 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String { let cap = tuning.select.stimulus_bytes; let mut contacts: Vec<(Option, String)> = Vec::new(); for bond in items(inputs.state, &["affect", "socialBonds"]).iter().filter(|bond| live(bond) && text(bond, &["object", "kind"]) == "person") { - let person = 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(); @@ -931,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 { 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. @@ -1102,14 +1106,14 @@ enum Concerns { /// 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(item: &Value) -> Option { +fn concerns(people: &People, item: &Value) -> Option { 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| text(item, &[key, "id"]).to_lowercase()); - let about = || tags.iter().find_map(|tag| tag.strip_prefix("about:")).map(|id| id.trim().to_lowercase()); + 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()), @@ -1194,9 +1198,9 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { 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 scope = scope(inputs, concerns(bond).as_ref(), &present_ids); + 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; diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index 63d742c..73f77fb 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -1531,3 +1531,42 @@ fn what_she_said_in_a_direct_message_stays_in_it() { 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"); +} From 0f3f76a8ab2ee7111719fcf093b17cfb7f16ec48 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 06:23:19 +0100 Subject: [PATCH 13/14] Simulation: one turn a round per Mind, in the room of her earliest waking line; only the room she read is seen (Soul F5, replacing R7) Who wakes is decided from the room as the round opens, as one heartbeat poll decides from the pending it read, so a line spoken this round counts toward a cap from the next round. A room that woke her but was not read stays unseen and wakes her next round. Tests: a DM and a #minds address answered in rounds 1 and 2; Soul's three rooms answered in three rounds, one turn a round, under ruled and names_with_cap. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/projection/simulate.rs | 81 ++++++++++--------- .../src/projection/simulate/tests.rs | 44 ++++++++-- 2 files changed, 78 insertions(+), 47 deletions(-) diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index 57e15ea..a525dc1 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -4,9 +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`. A persona woken in several -//! rooms in one round takes one turn in each. The turns of a round go in an order drawn from the seed, each against the -//! room as it stands at that 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 @@ -112,17 +116,24 @@ struct Member { rooms: Vec, } -/// 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; + +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 { - 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))) } } @@ -206,13 +217,13 @@ fn in_exchange(lines: &[Line], at: usize, her: &str, window: Duration) -> bool { lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.from == her && earlier.at_ms >= since) } -/// Her wakes: one per room a new line woke her in, in the order of each room's first waking line. A room's turn takes -/// the strongest cause among its lines, so no room that woke her, a direct message least of all, is passed over. +/// 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) -> Vec { +fn woken(lines: &[Line], runs: &[usize], seen: &Seen, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy, gap: Duration) -> Option { 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); @@ -221,28 +232,18 @@ fn woken(lines: &[Line], runs: &[usize], seen: usize, member: &Member, operators found.push((at, cause)); } } - let mut rooms: Vec<&str> = Vec::new(); - for (at, _) in &found { - if !rooms.contains(&lines[*at].room.as_str()) { - rooms.push(&lines[*at].room); - } + 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, line, how: None, by: vec![] }); } - rooms - .into_iter() - .filter_map(|room| { - let found: Vec<(usize, WakeCause)> = found.iter().copied().filter(|(at, _)| lines[*at].room == room).collect(); - 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, line, how: None, by: vec![] }); - } - let addressing: Vec = 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, line, how, by }) - }) - .collect() + let addressing: Vec = 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, line, how, by }) } /// The wire spelling of a cause, and of the beat. @@ -339,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 = vec![Seen::new(); members.len()]; let mut last_turn: Vec>> = vec![None; members.len()]; let mut last_beat = plan.start; let mut recent: Vec>> = vec![Vec::new(); members.len()]; @@ -348,9 +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); - // One turn per room that woke her, each in its room; all of hers this round read from where the round found her. - let round_seen = seen.clone(); - let mut woke: Vec<(usize, Option)> = members.iter().enumerate().flat_map(|(at, member)| woken(&lines, &mind_runs(&lines, &cast, member), seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_minutes)).into_iter().map(move |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)> = 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) { @@ -363,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) { @@ -375,7 +375,7 @@ 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[round_seen[at]..].iter().filter(|line| line.from != id && line.visible_to(&id, &member.rooms)).collect(); + 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()); @@ -400,11 +400,12 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) recent: recent[at].clone(), own_rooms: member.entry.own_rooms.clone(), }; - let view = View { lines: &lines, viewer: &id, rooms: &member.rooms, seen: round_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() { diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index fcbe149..2e663e5 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeMap; use std::path::Path; use serde_json::Value; @@ -365,22 +366,51 @@ fn the_turn_is_in_the_room_of_the_line_that_woke_her() { 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> { + let mut out: BTreeMap> = 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_r7_woken_in_a_direct_message_and_a_room_at_once_she_takes_a_turn_in_each() { +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\"", 1, ""); + 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()); - let mut libby: Vec<(String, String)> = run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Libby").map(|turn| (turn["room"].as_str().unwrap().to_owned(), turn["kind"].as_str().unwrap().to_owned())).collect(); - libby.sort(); - assert_eq!(libby, vec![("!dm-libby:gamecult.org".to_owned(), "chat".to_owned()), ("#minds:gamecult.org".to_owned(), "chat".to_owned())], "{}", run["turns"]); + // 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 stimulus = turn["report"]["renders"][0].to_string() + &turn["report"].to_string(); + 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!(stimulus.contains(own) && !stimulus.contains(other), "{}: {stimulus}", turn["room"]); + 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 = 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"); + } } } From 7ed31c6f75622f613a02e9251818ecd4f31dea34 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 06:25:23 +0100 Subject: [PATCH 14/14] Test prose speaks in standalone quotations: a dialogue tag frames its quotation (Soul F1) "what a day" he says and "Missed you too, friend," he types are framed under F1, so the test doubles' lines went silent. The prose now quotes whole sentences. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/projection/harness/tests.rs | 4 ++-- crates/mind-body/src/projection/simulate/tests.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index 5482eef..26d63bd 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -155,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); diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 2e663e5..c2565d0 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -60,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.